Looking at the web I find some simple way to style scrollbars.
This is THE guy! http://almaer.com/blog/creating-custom-scrollbars-with-css-how-css-isnt-great-for-every-task
And here my implementation! https://dl.dropbox.com/u/1471066/cloudBI/cssScrollbars.png
/* Turn on a 13x13 scrollbar */
::-webkit-scrollbar {
width: 10px;
height: 13px;
}
::-webkit-scrollbar-button:vertical {
background-color: silver;
border: 1px solid gray;
}
/* Turn on single button up on top, and down on bottom */
::-webkit-scrollbar-button:start:decrement,
::-webkit-scrollbar-button:end:increment {
display: block;
}
/* Turn off the down area up on top, and up area on bottom */
::-webkit-scrollbar-button:vertical:start:increment,
::-webkit-scrollbar-button:vertical:end:decrement {
display: none;
}
/* Place The scroll down button at the bottom */
::-webkit-scrollbar-button:vertical:increment {
display: none;
}
/* Place The scroll up button at the up */
::-webkit-scrollbar-button:vertical:decrement {
display: none;
}
/* Place The scroll down button at the bottom */
::-webkit-scrollbar-button:horizontal:increment {
display: none;
}
/* Place The scroll up button at the up */
::-webkit-scrollbar-button:horizontal:decrement {
display: none;
}
::-webkit-scrollbar-track:vertical {
background-color: blue;
border: 1px dashed pink;
}
/* Top area above thumb and below up button */
::-webkit-scrollbar-track-piece:vertical:start {
border: 0px;
}
/* Bottom area below thumb and down button */
::-webkit-scrollbar-track-piece:vertical:end {
border: 0px;
}
/* Track below and above */
::-webkit-scrollbar-track-piece {
background-color: silver;
}
/* The thumb itself */
::-webkit-scrollbar-thumb:vertical {
height: 50px;
background-color: gray;
}
/* The thumb itself */
::-webkit-scrollbar-thumb:horizontal {
height: 50px;
background-color: gray;
}
/* Corner */
::-webkit-scrollbar-corner:vertical {
background-color: black;
}
/* Resizer */
::-webkit-scrollbar-resizer:vertical {
background-color: gray;
}
CURSORS are an option here, but generally frowned upon as they often do not make best use of the query engine. Consider investigating 'SET Based Queries' to see if you can achieve what it is you want to do without using a CURSOR.
Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.
In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.
In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it
Then, Im used:
c = len(list)-1
for element in (reversed(list)):
if condition(element):
del list[c]
c -= 1
print(list)
where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]
Also You can do more pythonic using enumerate:
for i, element in enumerate(reversed(list)):
if condition(element):
del list[(i+1)*-1]
print(list)
Now (with JDK 9 onwards), you can just use java to get that executed. In order to execute "Hello.java" containing the main, one can use: java Hello.java
You do not need to compile using separately using javac anymore.
do adb pull \sdcard\log.txt C:Users\admin\Desktop
When i had the issue i saved the value into a hidden input:
in html body:
<body>
<?php
if (isset($_POST['Id'])){
$fid= $_POST['Id'];
}
?>
... then put the hidden input on the page and write the value $fid with php echo
<input type=hidden id ="fid" name=fid value="<?php echo $fid ?>">
then in $(document).ready( function () {
var postId=document.getElementById("fid").value;
so i got my hidden url parameter in php an js.
Using @Dan 's approach, you can create JOINs. Just use a different @variable for each sub query.
SELECT current_row.row, current_row.id, previous_row.row, previous_row.id
FROM (
SELECT @rownum:=@rownum+1 row, a.*
FROM articles a, (SELECT @rownum:=0) r
ORDER BY date, id
) as current_row
LEFT JOIN (
SELECT @rownum2:=@rownum2+1 row, a.*
FROM articles a, (SELECT @rownum2:=0) r
ORDER BY date, id
) as previous_row ON
(current_row.id = previous_row.id) AND (current_row.row = previous_row.row - 1)
Align the text area box to the label, not the label to the text area,
label {
width: 180px;
display: inline-block;
}
textarea{
vertical-align: middle;
}
<label for="myfield">Label text</label><textarea id="myfield" rows="5" cols="30"></textarea>
I was getting the same exception, but in my case I am using PowerShell to run commands
So, I fixed this with an instruction to unblock multiple files first.
PS C:\> dir C:\executable_file_Path\*PowerShell* | Unblock-File
and then use the following to load the package
& 'C:\path_to_executable\php.exe' "c:\path_to_composer_.phar_file\composer.phar "require desired/package
it's well documented here:
https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6
How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:
http://tomcat.apache.org/tomcat-7.0-doc/config/http.html
Standard Implementation -> address
"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."
pip
is designed to upgrade python packages and not to upgrade python itself. pip
shouldn't try to upgrade python when you ask it to do so.
Don't type pip install python
but use an installer instead.
-ArgumentList
is based on use with scriptblock commands, like:
Invoke-Command -Cn (gc Servers.txt) {param($Debug=$False, $Clear=$False) C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 } -ArgumentList $False,$True
When you call it with a -File
it still passes the parameters like a dumb splatted array. I've submitted a feature request to have that added to the command (please vote that up).
So, you have two options:
If you have a script that looked like this, in a network location accessible from the remote machine (note that -Debug
is implied because when I use the Parameter
attribute, the script gets CmdletBinding implicitly, and thus, all of the common parameters):
param(
[Parameter(Position=0)]
$one
,
[Parameter(Position=1)]
$two
,
[Parameter()]
[Switch]$Clear
)
"The test is for '$one' and '$two' ... and we $(if($DebugPreference -ne 'SilentlyContinue'){"will"}else{"won't"}) run in debug mode, and we $(if($Clear){"will"}else{"won't"}) clear the logs after."
Without getting hung up on the meaning of $Clear
... if you wanted to invoke that you could use either of the following Invoke-Command
syntaxes:
icm -cn (gc Servers.txt) {
param($one,$two,$Debug=$False,$Clear=$False)
C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 @PSBoundParameters
} -ArgumentList "uno", "dos", $false, $true
In that one, I'm duplicating ALL the parameters I care about in the scriptblock so I can pass values. If I can hard-code them (which is what I actually did), there's no need to do that and use PSBoundParameters
, I can just pass the ones I need to. In the second example below I'm going to pass the $Clear one, just to demonstrate how to pass switch parameters:
icm -cn $Env:ComputerName {
param([bool]$Clear)
C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $(Test-Path $Profile)
If the script is on your local machine, and you don't want to change the parameters to be positional, or you want to specify parameters that are common parameters (so you can't control them) you will want to get the content of that script and embed it in your scriptblock:
$script = [scriptblock]::create( @"
param(`$one,`$two,`$Debug=`$False,`$Clear=`$False)
&{ $(Get-Content C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -delimiter ([char]0)) } @PSBoundParameters
"@ )
Invoke-Command -Script $script -Args "uno", "dos", $false, $true
If you really need to pass in a variable for the script name, what you'd do will depend on whether the variable is defined locally or remotely. In general, if you have a variable $Script
or an environment variable $Env:Script
with the name of a script, you can execute it with the call operator (&): &$Script
or &$Env:Script
If it's an environment variable that's already defined on the remote computer, that's all there is to it. If it's a local variable, then you'll have to pass it to the remote script block:
Invoke-Command -cn $Env:ComputerName {
param([String]$Script, [bool]$Clear)
& $ScriptPath "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $ScriptPath, (Test-Path $Profile)
Small addition to @user995502's answer on how to run the program.
g++ player.cpp main.cpp -o main.out && ./main.out
Given its name, I think the standard way should be delete
:
import numpy as np
A = np.delete(A, 1, 0) # delete second row of A
B = np.delete(B, 2, 0) # delete third row of B
C = np.delete(C, 1, 1) # delete second column of C
According to numpy's documentation page, the parameters for numpy.delete
are as follow:
numpy.delete(arr, obj, axis=None)
arr
refers to the input array, obj
refers to which sub-arrays (e.g. column/row no. or slice of the array) andaxis
refers to either column wise (axis = 1
) or row-wise (axis = 0
) delete operation.Angular convention : write business logic in controller and DOM manipulation in link.
Apart from this you can call one controller function from link function of another directive.For example you have 3 custom directives
<animal>
<panther>
<leopard></leopard>
</panther>
</animal>
and you want to access animal from inside of "leopard" directive.
http://egghead.io/lessons/angularjs-directive-communication will be helpful to know about inter-directive communication
I made a method to do this below called jsonArrayToObjectList
. Its a handy static class that will take a filename and the file contains an array in JSON form.
List<Items> items = jsonArrayToObjectList(
"domain/ItemsArray.json", Item.class);
public static <T> List<T> jsonArrayToObjectList(String jsonFileName, Class<T> tClass) throws IOException {
ObjectMapper mapper = new ObjectMapper();
final File file = ResourceUtils.getFile("classpath:" + jsonFileName);
CollectionType listType = mapper.getTypeFactory()
.constructCollectionType(ArrayList.class, tClass);
List<T> ts = mapper.readValue(file, listType);
return ts;
}
Why JSON RPC:
In case of REST APIs, we have to define a controller for each functionality/method we might need. As a result if we have 10 methods that we want accessible to a client, we have to write 10 controllers to interface the client's request to a particular method.
Another factor is, even though we have different controllers for each method/functionality, the client has to remember wether to use POST or GET. This complicates things further. On top of that to send data, one has to set the content type of the request if POST is used.
In case of JSON RPC, things are greatly simplified because most JSONRPC servers operate on POST HTTP methods and the content type is always application/json. This takes the load off of remembering to use proper HTTP method and content settings on client side.
One doesn't have to create separate controllers for different methods/functionalities the server wants to expose to a client.
Why REST:
You have separate URLs for different functionality the server wants to expose to client side. As a result, you can embed these urls.
Most of these points are debatable and completely depend upon the need of a person.
If your log4j.properties or log4j.xml file not found under src/main/resources use this PropertyConfigurator.configure("log4j.xml");
PropertyConfigurator.configure("log4j.xml");
Logger logger = LoggerFactory.getLogger(MyClass.class);
logger.error(message);
See How to Make Dialogs.
You can use:
JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");
And you can also change the symbol to an error message or an warning. E.g see JOptionPane Features.
Use new Date(dateString)
if your string is compatible with Date.parse()
. If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.
Changing the above options form Help menu didn't work for me. You have edit idea.properties file and change to some large no.
MAC: /Applications/<Android studio>.app/Contents/bin[Open App contents]
Idea.max.intellisense.filesize=999999
WINDOWS: IDE_HOME\bin\idea.properties
Log in to your box with ssh [email protected] -p 2222
(password vagrant)
Then: sudo nano /etc/mysql/my.cnf
and comment out the following lines with #
#skip-external-locking
#bind-address
save it & exit
then: sudo service mysql restart
Then you can connect through SSH to your MySQL server.
To increase the phpMyAdmin
Session Timeout, open config.inc.php
in the root phpMyAdmin
directory and add this setting (anywhere).
$cfg['LoginCookieValidity'] = <your_new_timeout>;
Where <your_new_timeout>
is some number larger than 1800.
Note:
Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.
This will do the trick for you:
ng update @angular/cli @angular/core
ng s
or ng build
respectively.I had the same problem and found out that I had forgotten to include the script in the file which I want to include in the live site.
Also, you should try this:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
you can install the script ;
pip3 install --user advance-touch
After installed, you can use ad command
ad airport/plane/captain.txt
airport/
+-- plane/
¦ +-- captain.txt
There is an easy way...
$(arr1).not(arr2).length === 0 && $(arr2).not(arr1).length === 0
If the above returns true, both the arrays are same even if the elements are in different order.
NOTE: This works only for jquery versions < 3.0.0 when using JSON objects
Short solution that works even with arrays which keys are given in different order:
public static function arrays_are_equal($array1, $array2)
{
array_multisort($array1);
array_multisort($array2);
return ( serialize($array1) === serialize($array2) );
}
You might have some luck calling the Win32 API's MessageBoxA, although whether Win16 supports that particular method is for someone else to answer.
Add this before you connect to a URL behind a proxy.
System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");
To go directly to that folder, you can use the Set-Location
cmdlet or cd
alias:
Set-Location "Q:\My Test Folder"
TL;DR For conforming browsers, yes; but there are no conforming browsers, so no.
According to the HTML 4 specification, <!------> hello-->
is a perfectly valid comment. However, I've not found a browser which implements this correctly (i.e. per the specification) due to developers not knowing, nor following, the standards (as digitaldreamer pointed out).
You can find the definition of a comment for HTML4 on the w3c's website: http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.4
Another thing that many browsers get wrong is that -- >
closes a comment just like -->
.
I don't know if anyone is still reading this thread or not, but Jeff's solution will only get you halfway there (kinda literally). What his onMeasure will do is display half the image in half the parent. The problem is that calling super.onMeasure prior to the setMeasuredDimension
will measure all the children in the view based on the original size, then just cut the view in half when the setMeasuredDimension
resizes it.
Instead, you need to call setMeasuredDimension
(as required for an onMeasure override) and provide a new LayoutParams
for your view, then call super.onMeasure
. Remember, your LayoutParams
are derived from your view's parent type, not your view's type.
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth/2, parentHeight);
this.setLayoutParams(new *ParentLayoutType*.LayoutParams(parentWidth/2,parentHeight));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
I believe the only time you'll have problems with the parent LayoutParams
is if the parent is an AbsoluteLayout
(which is deprecated but still sometimes useful).
location / {
is the most general location (with location {
). It will match anything, AFAIU. I doubt that it would be useful to have location / { index index.html; }
because of a lot of duplicate content for every subdirectory of your site.
The approach with
try_files $uri $uri/index.html index.html;
is bad, as mentioned in a comment above, because it returns index.html
for pages which should not exist on your site (any possible $uri
will end up in that).
Also, as mentioned in an answer above, there is an internal redirect in the last argument of try_files
.
Your approach
location = / { index index.html;
is also bad, since index
makes an internal redirect too. In case you want that, you should be able to handle that in a specific location
. Create e.g.
location = /index.html {
as was proposed here. But then you will have a working link http://example.org/index.html
, which may be not desired. Another variant, which I use, is:
root /www/my-root;
# http://example.org
# = means exact location
location = / {
try_files /index.html =404;
}
# disable http://example.org/index as a duplicate content
location = /index { return 404; }
# This is a general location.
# (e.g. http://example.org/contacts <- contacts.html)
location / {
# use fastcgi or whatever you need here
# return 404 if doesn't exist
try_files $uri.html =404;
}
P.S. It's extremely easy to debug nginx (if your binary allows that). Just add into the server {
block:
error_log /var/log/nginx/debug.log debug;
and see there all internal redirects etc.
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
You can use this:
org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")
This error may be triggered by insufficient memory on RDP server.
After few tries with this error, RDP managed to get a connection to the server and I was able to stop a bogus service consuming too much memory. This can be done also with sysinternals or sc.
Here's an easy way using jQuery.
var scrollbarWidth = jQuery('div.withScrollBar').get(0).scrollWidth - jQuery('div.withScrollBar').width();
Basically we subtract the scrollable width from the overall width and that should provide the scrollbar's width. Of course, you'd want to cache the jQuery('div.withScrollBar') selection so you're not doing that part twice.
if(window.location.href.indexOf("?added-to-cart=555") >= 0)
It's window.location.href
, not window.location
.
One simple way can be the use of assign()
function that is pre-defined in vector
class.
e.g.
array[5]={1,2,3,4,5};
vector<int> v;
v.assign(array, array+5); // 5 is size of array.
You can use border bottom with dotted
option.
border-bottom: 1px dotted #807f80;
After a lot of research and discussions, it's clear there's no magic bullet that would work in all situations, at least not in the current version of Git.
That's why I wrote a couple of patches that add the concept of a tail
branch. Each time a branch is created, a pointer to the original point is created too, the tail
ref. This ref gets updated every time the branch is rebased.
To find out the branch point of the devel branch, all you have to do is use devel@{tail}
, that's it.
The easiest way only if you don't need return something it'ts just return null
You could split the string on the whitespace and then re-add it, since you know its in between every one of the entries.
var string = "text to split";
string = string.split(" ");
var stringArray = new Array();
for(var i =0; i < string.length; i++){
stringArray.push(string[i]);
if(i != string.length-1){
stringArray.push(" ");
}
}
Update: Removed trailing space.
I tried several of the proposed answers but the problem is that the media queries conflicted with other queries and instead of displaying the mobile CSS on the iPad Pro, it was displaying the desktop CSS. So instead of using max and min for dimensions, I used the EXACT VALUES and it works because on the iPad pro you can't resize the browser.
Note that I added a query for mobile CSS that I use for devices with less than 900px width; feel free to remove it if needed.
This is the query, it combines both landscape and portrait, it works for the 12.9" and if you need to target the 10.5" you can simply add the queries for these dimensions:
@media only screen and (max-width: 900px),
(height: 1024px) and (width: 1366px) and (-webkit-min-device-pixel-ratio: 1.5) and (orientation: landscape),
(width: 1024px) and (height: 1366px) and (-webkit-min-device-pixel-ratio: 1.5) and (orientation: portrait) {
// insert mobile and iPad Pro 12.9" CSS here
}
Change your subplot settings to:
plt.subplot(1, 2, 1)
...
plt.subplot(1, 2, 2)
The parameters for subplot
are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1
means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2
means "a 1-row, 2-column figure: go to the second subplot."
You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:
In order to minimize the overlap of subplots, you might want to kick in a:
plt.tight_layout()
before the show. Yielding:
Erik's answer doesn't work on Windows Phone as is. The following does:
class WebClientEx : WebClient
{
private WebResponse m_Resp = null;
protected override WebResponse GetWebResponse(WebRequest Req, IAsyncResult ar)
{
try
{
this.m_Resp = base.GetWebResponse(request);
}
catch (WebException ex)
{
if (this.m_Resp == null)
this.m_Resp = ex.Response;
}
return this.m_Resp;
}
public HttpStatusCode StatusCode
{
get
{
if (m_Resp != null && m_Resp is HttpWebResponse)
return (m_Resp as HttpWebResponse).StatusCode;
else
return HttpStatusCode.OK;
}
}
}
At least it does when using OpenReadAsync
; for other xxxAsync
methods, careful testing would be highly recommended. The framework calls GetWebResponse somewhere along the code path; all one needs to do is capture and cache the response object.
The fallback code is 200 in this snippet because genuine HTTP errors - 500, 404, etc - are reported as exceptions anyway. The purpose of this trick is to capture non-error codes, in my specific case 304 (Not modified). So the fallback assumes that if the status code is somehow unavailable, at least it's a non-erroneous one.
In Android Studio, go to app --> src --> main --> res-->
File --> new --> Activity --> ActivityType [choose a acticity that you want]
Fill in the details of the New Android Activity and click Finish.
I have an example I would like to share
$File = "C:\Foo.txt"
#retrieves the Systems current Date and Time in a DateTime Format
$today = Get-Date
#subtracts 12 hours from the date to ensure the file has been written to recently
$today = $today.AddHours(-12)
#gets the last time the $file was written in a DateTime Format
$lastWriteTime = (Get-Item $File).LastWriteTime
#If $File doesn't exist we will loop indefinetely until it does exist.
# also loops until the $File that exists was written to in the last twelve hours
while((!(Test-Path $File)) -or ($lastWriteTime -lt $today))
{
#if a file exists then the write time is wrong so update it
if (Test-Path $File)
{
$lastWriteTime = (Get-Item $File).LastWriteTime
}
#Sleep for 5 minutes
$time = Get-Date
Write-Host "Sleep" $time
Start-Sleep -s 300;
}
There is a labels
property in the HTML5 standard which points to labels which are associated to an input element.
So you could use something like this (support for native labels
property but with a fallback for retrieving labels in case the browser doesn't support it)...
var getLabelsForInputElement = function(element) {
var labels = [];
var id = element.id;
if (element.labels) {
return element.labels;
}
id && Array.prototype.push
.apply(labels, document.querySelector("label[for='" + id + "']"));
while (element = element.parentNode) {
if (element.tagName.toLowerCase() == "label") {
labels.push(element);
}
}
return labels;
};
// ES6
var getLabelsForInputElement = (element) => {
let labels;
let id = element.id;
if (element.labels) {
return element.labels;
}
if (id) {
labels = Array.from(document.querySelector(`label[for='${id}']`)));
}
while (element = element.parentNode) {
if (element.tagName.toLowerCase() == "label") {
labels.push(element);
}
}
return labels;
};
Even easier if you're using jQuery...
var getLabelsForInputElement = function(element) {
var labels = $();
var id = element.id;
if (element.labels) {
return element.labels;
}
id && (labels = $("label[for='" + id + "']")));
labels = labels.add($(element).parents("label"));
return labels;
};
basename() has a bug when processing Asian characters like Chinese.
I use this:
function get_basename($filename)
{
return preg_replace('/^.+[\\\\\\/]/', '', $filename);
}
let's think urls = "http://example1.com http://example2.com"
function somefunction(urls){
var urlarray = urls.split(" ");
var text = "\"'" + urlarray[0] + "'\"";
}
output will be text = "'http://example1.com'"
This will work but the element will still in the DOM.
.hidden {
display: none;
}
<div [class.hidden]="!show" *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
I would recommend using Apache Commons Collections
which implements it quite ok and well documented:
/**
* Null-safe check if the specified collection is empty.
* <p>
* Null returns true.
*
* @param coll the collection to check, may be null
* @return true if empty or null
* @since Commons Collections 3.2
*/
public static boolean isEmpty(Collection coll) {
return (coll == null || coll.isEmpty());
}
@Component
@Scope(value="prototype")
public class TennisCoach implements Coach {
// some code
}
You can't pass str
to your model fit()
method. as it mentioned here
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
Try transforming your data to float and give a try to LabelEncoder.
In Xamarin Use this
Control.SetBackgroundColor(global::Android.Graphics.Color.ParseColor("#F5F1F1"));
In Apache 2.4, the authorization configuration syntax has changed, and the Order
, Deny
or Allow
directives should no longer be used.
The new way to do this would be:
<VirtualHost *:8080>
<Location />
Require ip 192.168.1.0
</Location>
...
</VirtualHost>
Further examples using the new syntax can be found in the Apache documentation: Upgrading to 2.4 from 2.2
Your Make file will have one or two dependency rules depending on whether you compile and link with a single command, or with one command for the compile and one for the link.
Dependency are a tree of rules that look like this (note that the indent must be a TAB):
main_target : source1 source2 etc
command to build main_target from sources
source1 : dependents for source1
command to build source1
There must be a blank line after the commands for a target, and there must not be a blank line before the commands. The first target in the makefile is the overall goal, and other targets are built only if the first target depends on them.
So your makefile will look something like this.
a3a.exe : a3driver.obj
link /out:a3a.exe a3driver.obj
a3driver.obj : a3driver.cpp
cc a3driver.cpp
From the Window Menu in top bar of Xcode, select Devices and Simulators.
(or Press SHIFT + COMMAND + 2)
Then select your device, right click and select Unpair.
Once you do this Trust or Don't trust will appear on your device.
Trust the device again and it will begin preparing it for Development.
Wait for Xcode to pair device for development and then you are good to go!
There is 2 alternative which I use (for jasmine 2)
This one is not quite explicit because it seems that the function is actually a fake.
test = createSpy().and.callFake(test);
The second more verbose, more explicit, and "cleaner":
test = createSpy('testSpy', test).and.callThrough();
-> jasmine source code to see the second argument
You are calling nextInt
statically by using Random.nextInt
.
Instead, create a variable, Random r = new Random();
and then call r.nextInt(10)
.
It would be definitely worth while to check out:
You really should replace this line,
Random Random = new Random();
with something like this,
Random r = new Random();
If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.
I added
"types": [
"node"
]
in my tsconfig file and its worked for me tsconfig.json file look like
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"baseUrl": "./",
"module": "es2015",
"types": [
"node",
"underscore"
]
},
If you haven't created the form and want to change the queryset you can do:
formmodel.base_fields['myfield'].queryset = MyModel.objects.filter(...)
This is pretty useful when you are using generic views!
[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
Hope it helps.
Note: Apple may reject (0.01% chances) your app as we are accessing private API. I am using this in all my projects since two years, but Apple didn't ask for this.
It also worth noting that Concat works in constant time and in constant memory. For example, the following code
long boundary = 60000000;
for (long i = 0; i < boundary; i++)
{
list1.Add(i);
list2.Add(i);
}
var listConcat = list1.Concat(list2);
var list = listConcat.ToList();
list1.AddRange(list2);
gives the following timing/memory metrics:
After lists filled mem used: 1048730 KB
concat two enumerables: 00:00:00.0023309 mem used: 1048730 KB
convert concat to list: 00:00:03.7430633 mem used: 2097307 KB
list1.AddRange(list2) : 00:00:00.8439870 mem used: 2621595 KB
Depending on your privileges, this query might work:
SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
Ref: http://blog.sqlauthority.com/2009/01/07/sql-server-find-currently-running-query-t-sql
Start by turning the text into a list of lists. That will take care of the parsing part:
lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))
The rest can be done with indexed lookups:
d = dict()
key = lol[6][0] # cell A7
value = lol[6][3] # cell D7
d[key] = value # add the entry to the dictionary
...
I would seriously consider making a CLR UDF instead and using regular expressions (both the string and the pattern can be passed in as parameters) to do a complete search and replace for a range of characters. It should easily outperform this SQL UDF.
You can also use this command to delete the keys:-
Suppose there are many types of keys in your redis like-
Ex- 'xyz_category_fpc' here xyz is a sitename, and these keys are related to products and categories of a E-Commerce site and generated by FPC.
If you use this command as below-
redis-cli --scan --pattern 'key*' | xargs redis-cli del
OR
redis-cli --scan --pattern 'xyz_category_fpc*' | xargs redis-cli del
It deletes all the keys like 'xyz_category_fpc' (delete 1, 2 and 3 keys). For delete other 4, 5 and 6 number keys use 'xyz_product_fpc' in above command.
If you want to Delete Everything in Redis, then follow these Commands-
With redis-cli:
For Example:- in your shell:
redis-cli flushall
redis-cli flushdb
Using FilenameUtils
in Apache Commons IO :
String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");
Sometimes you need to use a macro variable without asking the user to enter a value. Most often this has to be done with optional script parameters. The following code is fully functional
column 1 noprint new_value 1
select '' "1" from dual where 2!=2;
select nvl('&&1', 'VAH') "1" from dual;
column 1 clear
define 1
Similar code was somehow found in the rdbms/sql directory.
It works if you remove flexDirection: row
from descriptionContainerVer
and descriptionContainerVer2
respectively.
UPDATE (see comments)
I made a few changes to achieve what I think you're after. First of all I removed the descriptionContainerHor
component. Then I set the flexDirection
of the vertical views to row
and added alignItems: 'center'
and justifyContent: 'center'
. Since the vertical views are now in fact stacked along the horizontal axis I removed the Ver
part from the name.
So now you have a wrapper view that should vertically and horizontally align it's content and stack it along the x-axis. I then simply put two invisible View
components on the left and right side of the Text
component to do the padding.
Like this:
<View style={styles.descriptionContainer}>
<View style={styles.padding}/>
<Text style={styles.descriptionText} numberOfLines={5} >
Here is a really long text that you can do nothing about, its gonna be long wether you like it or not, so be prepared for it to go off screen. Right? Right..!
</Text>
<View style={styles.padding}/>
</View>
And this:
descriptionContainer:{
flex:0.5, //height (according to its parent),
flexDirection: 'row',
backgroundColor: 'blue',
alignItems: 'center',
justifyContent: 'center',
// alignSelf: 'center',
},
padding: {
flex: 0.1
},
descriptionText: {
backgroundColor: 'green',//Colors.transparentColor,
fontSize: 16,
flex: 0.8,
color: 'white',
textAlign: 'center',
flexWrap: 'wrap'
},
Then you get what I believe you were after.
FURTHER IMPROVEMENTS
Now if you would like to stack multiple text areas within the blue and orange views you can do something like this:
<View style={styles.descriptionContainer2}>
<View style={styles.padding}/>
<View style={styles.textWrap}>
<Text style={styles.descriptionText} numberOfLines={5} >
Some other long text which you can still do nothing about.. Off the screen we go then.
</Text>
<Text style={styles.descriptionText} numberOfLines={5} >
Another column of text.
</Text>
</View>
<View style={styles.padding}/>
</View>
Where textWrap
is styled like this:
textWrap: {
flexDirection: 'column',
flex: 0.8
},
Hope this helps!
First, make sure you don't have spaces (or other illegal characters like '+','=','/',etc) in the "AVD Name" field. Spaces broke it for me.
I'd like to add some thoughts/findings of mine to this topic. I'm writing a script that checks all requirements for a custom made program. There are many checks with python modules too.
There's a little issue with the
try:
import ..
except:
..
solution.
In my case one of the python modules called python-nmap
, but you import it with import nmap
and as you see the names mismatch. Therefore the test with the above solution returns a False result, and it also imports the module on hit, but maybe no need to use a lot of memory for a simple test/check.
I also found that
import pip
installed_packages = pip.get_installed_distributions()
installed_packages
will have only the packages has been installed with pip.
On my system pip freeze
returns over 40
python modules, while installed_packages
has only 1
, the one I installed manually (python-nmap).
Another solution below that I know it may not relevant to the question, but I think it's a good practice to keep the test function separate from the one that performs the install it might be useful for some.
The solution that worked for me. It based on this answer How to check if a python module exists without importing it
from imp import find_module
def checkPythonmod(mod):
try:
op = find_module(mod)
return True
except ImportError:
return False
NOTE: this solution can't find the module by the name python-nmap
too, I have to use nmap
instead (easy to live with) but in this case the module won't be loaded to the memory whatsoever.
Very simple, no library required:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
or you might prefer:
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
Some browsers will treat two digit years as being in the 20th century, so that:
new Date(14, 0, 1);
gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:
var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14
I prefer to use WebClient, it seems to handle SSL transparently:
http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
Some troubleshooting help here:
Add /Y to the command line
Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).
So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.
Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.
>>> books = {}
>>> books['book'] = 3
>>> books['book'] -= 1
>>> books
{'book': 2}
In your case:
book_shop[ch1] -= 1
Here's what I did in Linux to be able to program my Arduino Micro which was stuck in a loop sending the 0 key when connected by USB;
# while true; do xinput float $(xinput --list | grep -i Arduino | awk '{print $7}' | cut -d'=' -f 2); done
Your output might be slightly different so just try running;
# watch xinput --list
then plug in the Arduino and see how the output is formatted.
This stopped X from accepting the keypresses and allowed the Arduino IDE to program finally!
How to change orientation in some of the view
Instead of locking orientation of entire activity you can use this class to dynamically lock orientation from any of your view pragmatically:-
Make your view Landscape
OrientationUtils.lockOrientationLandscape(mActivity);
Make your view Portrait
OrientationUtils.lockOrientationPortrait(mActivity);
Unlock Orientation
OrientationUtils.unlockOrientation(mActivity);
Orientation Util Class
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.view.Surface;
import android.view.WindowManager;
/* * This class is used to lock orientation of android app in nay android devices
*/
public class OrientationUtils {
private OrientationUtils() {
}
/** Locks the device window in landscape mode. */
public static void lockOrientationLandscape(Activity activity) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
}
/** Locks the device window in portrait mode. */
public static void lockOrientationPortrait(Activity activity) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
/** Locks the device window in actual screen mode. */
public static void lockOrientation(Activity activity) {
final int orientation = activity.getResources().getConfiguration().orientation;
final int rotation = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
.getRotation();
// Copied from Android docs, since we don't have these values in Froyo
// 2.2
int SCREEN_ORIENTATION_REVERSE_LANDSCAPE = 8;
int SCREEN_ORIENTATION_REVERSE_PORTRAIT = 9;
// Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO
if (!(Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO)) {
SCREEN_ORIENTATION_REVERSE_LANDSCAPE = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
SCREEN_ORIENTATION_REVERSE_PORTRAIT = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}
if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} else if (rotation == Surface.ROTATION_180 || rotation == Surface.ROTATION_270) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_PORTRAIT);
} else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
}
}
/** Unlocks the device window in user defined screen mode. */
public static void unlockOrientation(Activity activity) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
}
}
It's the array that's causing trouble in:
void print_graph(g_node graph_node[], double weight[][], int nodes);
The second and subsequent dimensions must be given:
void print_graph(g_node graph_node[], double weight[][32], int nodes);
Or you can just give a pointer to pointer:
void print_graph(g_node graph_node[], double **weight, int nodes);
However, although they look similar, those are very different internally.
If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):
void fvla(int m, int C[m][m]); // valid: VLA with prototype scope
void fvla(int m, int C[m][m]) // valid: adjusted to auto pointer to VLA
{
typedef int VLA[m][m]; // valid: block scope typedef VLA
struct tag {
int (*y)[n]; // invalid: y not ordinary identifier
int z[n]; // invalid: z not ordinary identifier
};
int D[m]; // valid: auto VLA
static int E[m]; // invalid: static block scope VLA
extern int F[m]; // invalid: F has linkage and is VLA
int (*s)[m]; // valid: auto pointer to VLA
extern int (*r)[m]; // invalid: r has linkage and points to VLA
static int (*q)[m] = &B; // valid: q is a static block pointer to VLA
}
[...] In my main(), the variable I am trying to pass into the function is a
double array[][]
, so how would I pass that into the function? Passingarray[0][0]
into it gives me incompatible argument type, as does&array
and&array[0][0]
.
In your main()
, the variable should be:
double array[10][20];
or something faintly similar; maybe
double array[][20] = { { 1.0, 0.0, ... }, ... };
You should be able to pass that with code like this:
typedef struct graph_node
{
int X;
int Y;
int active;
} g_node;
void print_graph(g_node graph_node[], double weight[][20], int nodes);
int main(void)
{
g_node g[10];
double array[10][20];
int n = 10;
print_graph(g, array, n);
return 0;
}
That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:
/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c
/var/lib/tomcat7/webapps/
find / -name 'tomcat_version' -type d
I didn't check all the code but my guess is that the error is in the malloc call. You have to replace
double *ptr = malloc(sizeof(double*) * TIME);
for
double *ptr = malloc(sizeof(double) * TIME);
since you want to allocate size for a double (not the size of a pointer to a double).
Use two view types in the your RVAdapter
. One for expanded layout and other for collapsed.
And the magic happens with setting android:animateLayoutChanges="true"
for RecyclerView
Checkout the effect achieved using this at 0:42 in this video
The command :hide will hide the currently focused window. I think this is the functionality you are looking for.
In order to navigate between windows type Ctrl+w followed by a navigation key (h,j,k,l, or arrow keys)
For more information run :help window
and :help hide
in vim.
IN SWIFT
func captureScreen() -> UIImage
{
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, 0);
self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
Most of these answers have milliseconds / microseconds which clearly isn't supported by ISO 8601. The correct answer would be:
System.DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
// or
System.DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
References:
there is another simple solution for this. I have 2 modules which are somehow deep in the structure using each other. I ran into the same problem with circular dependencies with webpack and angular 2. I simply changed the way of how the one module is declared:
....
@NgModule({
imports: [
CommonModule,
FormsModule,
require('../navigation/navigation.module')
],
declarations: COMPONENTS,
exports: COMPONENTS
})
class DppIncludeModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: DppIncludeModule
};
}
}
export = DppIncludeModule;
When I now using the imports statement on ngModule attribute I simply use:
@NgModule({
imports: [
CommonModule,
ServicesModule.forRoot(),
NouisliderModule,
FormsModule,
ChartModule,
DppAccordeonModule,
PipesModule,
require('../../../unbranded/include/include.module')
],
....
With this all problems are away.
Add some jquery code, you need jquery to do this :
<script>
$(".btn[data-toggle='collapse']").click(function() {
if ($(this).text() == '+') {
$(this).text('-');
} else {
$(this).text('+');
}
});
</script>
To post a clarification answer here for those who get directed here by Google.
The document size includes everything in the document including the subdocuments, nested objects etc.
So a document of:
{
"_id": {},
"na": [1, 2, 3],
"naa": [
{ "w": 1, "v": 2, "b": [1, 2, 3] },
{ "w": 5, "b": 2, "h": [{ "d": 5, "g": 7 }, {}] }
]
}
Has a maximum size of 16 MB.
Subdocuments and nested objects are all counted towards the size of the document.
$("element").data('bs.modal').isShown
won't work if the modal hasn't been shown before. You will need to add an extra condition:
$("element").data('bs.modal')
so the answer taking into account first appearance:
if ($("element").data('bs.modal') && $("element").data('bs.modal').isShown){
...
}
sc delete sericeName
Just make sure the service is stopped before doing this. I have seen this work most times. There are times where I have seen windows get stuck on something and it insists on a reboot.
if you've installed php
and mysql
in your linux machine, php needs php-mysql
extention to communicate with mysql. so make sure you've also installed this extention using:
sudo yum install php-mysql
in redhat based machines.
and
sudo apt-get install php-mysql
in debian machines.
For me this meant I was running this:
a = Mockito.mock(SomeClass.class);
b = new RealClass();
when(b.method1(a)).thenReturn(c);
// within this method1, it calls param1.method2() -- note, b is not a spy or mock
So what was happening is that mockito was detecting that a.method2()
was being called, and telling me I couldn't return c
from a.method2()
which is wrong.
Fix: use the doReturn(c).when(b).method1(a)
style syntax (instead of when(b.method1(a)).thenReturn(c);
), which will help you discover the hidden bug more concisely and quickly.
Or in this particular case, after doing that it started showing the more accurate "NotAMockException", and I changed it to not longer try to set a return value from a non-mock object.
Now it is part of official Design Support Library.
In your gradle:
compile 'com.android.support:design:22.2.0'
http://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html
If you have multiple, dynamic height items, use the CSS display values of table and table-cell:
HTML
<html>
<body>
<div class="valign bottom">
<div>
<div>my bottom aligned div 1</div>
<div>my bottom aligned div 2</div>
<div>my bottom aligned div 3</div>
</div>
</div>
</body>
</html>
CSS
html,
body {
width: 100%;
height: 100%;
}
.valign {
display: table;
width: 100%;
height: 100%;
}
.valign > div {
display: table-cell;
width: 100%;
height: 100%;
}
.valign.bottom > div {
vertical-align: bottom;
}
I've created a JSBin demo here: http://jsbin.com/INOnAkuF/2/edit
The demo also has an example how to vertically center align using the same technique.
I had issues getting through a form because of this error.
I used Ctrl+Click to click the submit button and navigate through the form as usual.
From https://golang.org/doc/effective_go.html#composite_literals:
Sometimes the zero value isn't good enough and an initializing constructor is necessary, as in this example derived from package os.
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
f := new(File)
f.fd = fd
f.name = name
f.dirinfo = nil
f.nepipe = 0
return f
}
Your command line should look like this:
rsync -rvz -e 'ssh -p 2222' --progress ./dir user@host:/path
this works fine - I use it all the time without needing any new firewall rules - just note the SSH command itself is enclosed in quotes.
When you don't want to search any locator, you can use the Robot class. For example,
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
For intel drivers, there is also this method
Disable Vertical Synchronization (VSYNC)
The intel-driver uses Triple Buffering for vertical synchronization, this allows for full performance and avoids tearing. To turn vertical synchronization off (e.g. for benchmarking) use this .drirc in your home directory:
<device screen="0" driver="dri2">
<application name="Default">
<option name="vblank_mode" value="0"/>
</application>
</device>
string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>(); foreach (var line in lines) { string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); list1.Add(values[0]); list2.Add(values[1]); }
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
This worked for me:
<string name="text_with_bullet">Text with a \u2022</string>
Converting from file with base64 string to png image.
4 variants which works.
var {promisify} = require('util');
var fs = require("fs");
var readFile = promisify(fs.readFile)
var writeFile = promisify(fs.writeFile)
async function run () {
// variant 1
var d = await readFile('./1.txt', 'utf8')
await writeFile("./1.png", d, 'base64')
// variant 2
var d = await readFile('./2.txt', 'utf8')
var dd = new Buffer(d, 'base64')
await writeFile("./2.png", dd)
// variant 3
var d = await readFile('./3.txt')
await writeFile("./3.png", d.toString('utf8'), 'base64')
// variant 4
var d = await readFile('./4.txt')
var dd = new Buffer(d.toString('utf8'), 'base64')
await writeFile("./4.png", dd)
}
run();
You can not use argv[0] for that purpose, usually it does contain full path to the executable, but not nessesarily - process could be created with arbitrary value in the field.
Also mind you, the current directory and the directory with the executable are two different things, so getcwd() won't help you either.
On Windows use GetModuleFileName(), on Linux read /dev/proc/procID/.. files.
You can use the below method, which will take your target URL as the only input (Don't forget http://)
void GoToURL(String url){
Uri uri = Uri.parse(url);
Intent intent= new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
First, go to your VS Code then press "ctrl + shift + p"
Then search settings.json
Then paste the below code inside the settings.jason.I hope the problem will be solved.
{
"python.pythonPath": "venv/bin/python",
"python.linting.pylintPath": "venv/bin/pylint"
}
The range of char is 127 to -128. If you assign 212, ch stores -44 (212-128-128) not 212.So if you try to print a negative number as unsigned you get (MAX value of unsigned int)-abs(number) which in this case is 4294967252
So if you want to store 212 as it is in ch the only thing you can do is declare ch as
unsigned char ch;
now the range of ch is 0 to 255.
You can now use ScriptIntrinsicBlur from the RenderScript library to blur quickly. Here is how to access the RenderScript API. The following is a class I made to blur Views and Bitmaps:
public class BlurBuilder {
private static final float BITMAP_SCALE = 0.4f;
private static final float BLUR_RADIUS = 7.5f;
public static Bitmap blur(View v) {
return blur(v.getContext(), getScreenshot(v));
}
public static Bitmap blur(Context ctx, Bitmap image) {
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_SCALE);
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
RenderScript rs = RenderScript.create(ctx);
ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
theIntrinsic.setRadius(BLUR_RADIUS);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
private static Bitmap getScreenshot(View v) {
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
}
You can either:
Examples are on the msdn pages provided
JQuery:
$(function () {
$('.SendEmail').click(function (event) {
var email = '[email protected]';
var subject = 'Test';
var emailBody = 'Hi Sample,';
var attach = 'path';
document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody+
"?attach="+attach;
});
});
HTML:
<button class="SendEmail">Send Email</button>
You're looking for the OpenFileDialog
class.
For example:
Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
Using dialog As New OpenFileDialog
If dialog.ShowDialog() <> DialogResult.OK Then Return
File.Copy(dialog.FileName, newPath)
End Using
End Sub
You should use the get()
method from the dict
class
d = {}
r = d.get('missing_key', None)
This will result in r == None
. If the key isn't found in the dictionary, the get function returns the second argument.
Keep in mind that you're NEVER zooming in on a UIImage
. EVER.
Instead, you're zooming in and out on the view
that displays the UIImage
.
In this particular case, you chould choose to create a custom UIView
with custom drawing to display the image, a UIImageView
which displays the image for you, or a UIWebView
which will need some additional HTML to back it up.
In all cases, you'll need to implement touchesBegan
, touchesMoved
, and the like to determine what the user is trying to do (zoom, pan, etc.).
Seems easiest to just add a
GET
/api/members/count
and return the total count of members
Correct final syntax for [Mr. C]s answer.
With the release of VS2017RC and its C#7 support it works this way:
switch(message)
{
case string a when a.Contains("test2"): return "no";
case string b when b.Contains("test"): return "yes";
}
You should take care of the case ordering as the first match will be picked. That's why "test2" is placed prior to test.
Another way to achieve this is to add a class .btn-space in your buttons
<button type="button" class="btn btn-outline-danger btn-space"
</button>
<button type="button" class="btn btn-outline-primary btn-space"
</button>
and define this class as follows
.btn-space {
margin-right: 15px;
}
The ISO C99 standard specifies that these macros must only be defined if explicitly requested.
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
... now PRIu64 will work
If anyone looking to have retry limit:
max_retry=5
counter=0
until $command
do
sleep 1
[[ counter -eq $max_retry ]] && echo "Failed!" && exit 1
echo "Trying again. Try #$counter"
((counter++))
done
Extracting the address all by itself is a bit difficult, but you can get the entire IP Address line easily.
To show all IP addresses on any English-language Windows OS:
ipconfig | findstr /R /C:"IP.* Address"
To show only IPv4 or IPv6 addresses on Windows 7+:
ipconfig | findstr /R /C:"IPv4 Address"
ipconfig | findstr /R /C:"IPv6 Address"
Here's some sample output from an XP machine with 3 network adapters.
IP Address. . . . . . . . . . . . : 192.168.1.10
IP Address. . . . . . . . . . . . : 10.6.102.205
IP Address. . . . . . . . . . . . : 192.168.56.1
Here is another dirty hack :)
.application-title > img {
display: none;
}
.application-title::before {
content: url(path/example.jpg);
}
The poor mans compromise solution is to use a simplistic multi signature approach.
For Example the DBA sets the applications database password to a 50 character random string. TAKqWskc4ncvKaJTyDcgAHq82X7tX6GfK2fc386bmNw3muknjU
He or she give half the password to the application developer who then hard codes it into the java binary.
private String pass1 = "TAKqWskc4ncvKaJTyDcgAHq82"
The other half of the password is passed as a command line argument. the DBA gives pass2 to the system support or admin person who either enters it a application start time or puts it into the automated application start up script.
java -jar /myapplication.jar -pass2 X7tX6GfK2fc386bmNw3muknjU
When the application starts it uses pass1 + pass2 and connects to the database.
This solution has many advantages with out the downfalls mentioned.
You can safely put half the password in a command line arguments as reading it wont help you much unless you are the developer who has the other half of the password.
The DBA can also still change the second half of the password and the developer need not have to re-deploy the application.
The source code can also be semi public as reading it and the password will not give you application access.
You can further improve the situation by adding restrictions on the IP address ranges the database will accept connections from.
I used a variant of Alex's - but needed to to convert the param appearing multiple times to an array. There seem to be many options. I didn't want rely on another library for something this simple. I suppose one of the other options posted here may be better - I adapted Alex's because of the straight forwardness.
parseQueryString = function() {
var str = window.location.search;
var objURL = {};
// local isArray - defer to underscore, as we are already using the lib
var isArray = _.isArray
str.replace(
new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
function( $0, $1, $2, $3 ){
if(objURL[ $1 ] && !isArray(objURL[ $1 ])){
// if there parameter occurs more than once, convert to an array on 2nd
var first = objURL[ $1 ]
objURL[ $1 ] = [first, $3]
} else if(objURL[ $1 ] && isArray(objURL[ $1 ])){
// if there parameter occurs more than once, add to array after 2nd
objURL[ $1 ].push($3)
}
else
{
// this is the first instance
objURL[ $1 ] = $3;
}
}
);
return objURL;
};
This query stands good for fetching the values between current date and its next 3 dates
SELECT * FROM tableName
WHERE columName BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
This will eventually add extra 3 days of buffer to the current date.
Instead of an unneeded counter, now you have an unneeded list. Best solution is to use a variable that starts with "_", that tells syntax checkers that you are aware you are not using the variable.
x = range(5)
while x:
x.pop()
print "Work!"
I had the same problem and i saw waruna manjula giving the best answer. However writing it all down on the console is not what you might want. To get string off al info use the following
Step one: declare values at begin
//drive 1
public static string drivename = "";
public static string drivetype = "";
public static string drivevolumelabel = "";
public static string drivefilesystem = "";
public static string driveuseravailablespace = "";
public static string driveavailablespace = "";
public static string drivetotalspace = "";
//drive 2
public static string drivename2 = "";
public static string drivetype2 = "";
public static string drivevolumelabel2 = "";
public static string drivefilesystem2 = "";
public static string driveuseravailablespace2 = "";
public static string driveavailablespace2 = "";
public static string drivetotalspace2 = "";
//drive 3
public static string drivename3 = "";
public static string drivetype3 = "";
public static string drivevolumelabel3 = "";
public static string drivefilesystem3 = "";
public static string driveuseravailablespace3 = "";
public static string driveavailablespace3 = "";
public static string drivetotalspace3 = "";
Step 2: actual code
DriveInfo[] allDrives = DriveInfo.GetDrives();
int drive = 1;
foreach (DriveInfo d in allDrives)
{
if (drive == 1)
{
drivename = String.Format("Drive {0}", d.Name);
drivetype = String.Format("Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
drivevolumelabel = String.Format("Volume label: {0}", d.VolumeLabel);
drivefilesystem = String.Format("File system: {0}", d.DriveFormat);
driveuseravailablespace = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
driveavailablespace = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
drivetotalspace = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
}
drive = 2;
}
else if (drive == 2)
{
drivename2 = String.Format("Drive {0}", d.Name);
drivetype2 = String.Format("Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
drivevolumelabel2 = String.Format("Volume label: {0}", d.VolumeLabel);
drivefilesystem2 = String.Format("File system: {0}", d.DriveFormat);
driveuseravailablespace2 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
driveavailablespace2 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
drivetotalspace2 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
}
drive = 3;
}
else if (drive == 3)
{
drivename3 = String.Format("Drive {0}", d.Name);
drivetype3 = String.Format("Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
drivevolumelabel3 = String.Format("Volume label: {0}", d.VolumeLabel);
drivefilesystem3 = String.Format("File system: {0}", d.DriveFormat);
driveuseravailablespace3 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
driveavailablespace3 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
drivetotalspace3 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
}
drive = 4;
}
if (drive == 4)
{
drive = 1;
}
}
//part 2: possible debug - displays in output
//drive 1
Console.WriteLine(drivename);
Console.WriteLine(drivetype);
Console.WriteLine(drivevolumelabel);
Console.WriteLine(drivefilesystem);
Console.WriteLine(driveuseravailablespace);
Console.WriteLine(driveavailablespace);
Console.WriteLine(drivetotalspace);
//drive 2
Console.WriteLine(drivename2);
Console.WriteLine(drivetype2);
Console.WriteLine(drivevolumelabel2);
Console.WriteLine(drivefilesystem2);
Console.WriteLine(driveuseravailablespace2);
Console.WriteLine(driveavailablespace2);
Console.WriteLine(drivetotalspace2);
//drive 3
Console.WriteLine(drivename3);
Console.WriteLine(drivetype3);
Console.WriteLine(drivevolumelabel3);
Console.WriteLine(drivefilesystem3);
Console.WriteLine(driveuseravailablespace3);
Console.WriteLine(driveavailablespace3);
Console.WriteLine(drivetotalspace3);
I want to note that you can just make all the console writelines comment code, but i thought it would be nice for you to test it. If you display all these after each other you get the same list as waruna majuna
Drive C:\ Drive type: Fixed Volume label: File system: NTFS Available space to current user: 134880153600 bytes Total available space: 134880153600 bytes Total size of drive: 499554185216 bytes
Drive D:\ Drive type: CDRom
Drive H:\ Drive type: Fixed Volume label: HDD File system: NTFS Available space to current user: 2000010817536 bytes Total available space: 2000010817536 bytes Total size of drive: 2000263573504 bytes
However you can now acces all of the loose information at strings
found = df[df['Column'].str.contains('Text_to_search')]
print(found.count())
the found.count()
will contains number of matches
And if it is 0 then means string was not found in the Column.
You can do that by using following code
$('#button_id').on('click', function(){
$('#element_want_to_target').addClass('.animation_class');});
I found this answer ( Prevent Highlight of Text Table ) most helpful, and perhaps it can be combined with another way of providing IE compatibility.
#yourTable
{
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
user-select: none;
}
As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.
new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1
The Uri.parse(extras.getString("imageUri"))
was causing an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.putExtra(java.lang.String, android.os.Parcelable)' on a null object reference
So I changed to the following:
intent.putExtra("imageUri", imageUri)
and
Uri uri = (Uri) getIntent().get("imageUri");
This solved the problem.
If you want to unit test code then you need to isolate your code you want to test (in this case your service) from external resources (e.g. databases). You could probably do this with some sort of in-memory EF provider, however a much more common way is to abstract away your EF implementation e.g. with some sort of repository pattern. Without this isolation any tests you write will be integration tests, not unit tests.
As for testing EF code - I write automated integration tests for my repositories that write various rows to the database during their initialization, and then call my repository implementations to make sure that they behave as expected (e.g. making sure that results are filtered correctly, or that they are sorted in the correct order).
These are integration tests not unit tests, as the tests rely on having a database connection present, and that the target database already has the latest up-to-date schema installed.
$('form[name="frmSave"]')
is correct. You mentioned you thought this would get all children with the name frmsave
inside the form; this would only happen if there was a space or other combinator between the form and the selector, eg: $('form [name="frmSave"]');
$('form[name="frmSave"]')
literally means find all forms with the name frmSave
, because there is no combinator involved.
This worked for me. Create WebViewClient like this below and set the webclient to your webview. I had to use webview.loadDataWithBaseURL as my urls (in my content) did not have the baseurl but only relative urls. You will get the url correctly only when there is a baseurl set using loadDataWithBaseURL.
public WebViewClient getWebViewClientWithCustomHeader(){
return new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
OkHttpClient httpClient = new OkHttpClient();
com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
.url(url.trim())
.addHeader("<your-custom-header-name>", "<your-custom-header-value>")
.build();
com.squareup.okhttp.Response response = httpClient.newCall(request).execute();
return new WebResourceResponse(
response.header("content-type", response.body().contentType().type()), // You can set something other as default content-type
response.header("content-encoding", "utf-8"), // Again, you can set another encoding as default
response.body().byteStream()
);
} catch (ClientProtocolException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
} catch (IOException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
}
}
};
}
$id = array(2222,3333,4444,5555,6666);
$ids = "'".implode("','",$id)."'";
$ids = sprintf("'%s'", implode("','", $id ) );
Extending on what @vabhatia said, this is what you want in native JavaScript (without JQuery).
ParentNode.insertBefore(<your element>, ParentNode.firstChild);
The direct cast var ListOfY = (List<Y>)ListOfX
is not possible because it would require co/contravariance of the List<T>
type, and that just can't be guaranteed in every case. Please read on to see the solutions to this casting problem.
While it seems normal to be able to write code like this:
List<Animal> animals = (List<Animal>) mammalList;
because we can guarantee that every mammal will be an animal, this is obviously a mistake:
List<Mammal> mammals = (List<Mammal>) animalList;
since not every animal is a mammal.
However, using C# 3 and above, you can use
IEnumerable<Animal> animals = mammalList.Cast<Animal>();
that eases the casting a little. This is syntactically equivalent to your one-by-one adding code, as it uses an explicit cast to cast each Mammal
in the list to an Animal
, and will fail if the cast is not successfull.
If you like more control over the casting / conversion process, you could use the ConvertAll
method of the List<T>
class, which can use a supplied expression to convert the items. It has the added benifit that it returns a List
, instead of IEnumerable
, so no .ToList()
is necessary.
List<object> o = new List<object>();
o.Add("one");
o.Add("two");
o.Add(3);
IEnumerable<string> s1 = o.Cast<string>(); //fails on the 3rd item
List<string> s2 = o.ConvertAll(x => x.ToString()); //succeeds
If the dicts have identical sets of keys and you need all those prints for any value difference, there isn't much you can do; maybe something like:
diffkeys = [k for k in dict1 if dict1[k] != dict2[k]]
for k in diffkeys:
print k, ':', dict1[k], '->', dict2[k]
pretty much equivalent to what you have, but you might get nicer presentation for example by sorting diffkeys before you loop on it.
If you choose to use a generic collection, such as List<MyObject>
instead of ArrayList
, you'll find that the List<MyObject>
will provide both generic and non-generic enumerators that you can use.
using System.Collections;
class MyObjects : IEnumerable<MyObject>
{
List<MyObject> mylist = new List<MyObject>();
public MyObject this[int index]
{
get { return mylist[index]; }
set { mylist.Insert(index, value); }
}
public IEnumerator<MyObject> GetEnumerator()
{
return mylist.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %> <i class="fa fa-facebook"> Facebook Share </i> <%end%>
I am assuming that current_article_url
is http://0.0.0.0:4567/link_to_title
Use DATE_FORMAT function to change the format.
SELECT DATE_FORMAT(CURDATE(), '%d/%m/%Y')
SELECT DATE_FORMAT(column_name, '%d/%m/%Y') FROM tablename
Refer DOC for more details
Here is some workaround to make numpys look more like Lists
np_arr = np.array([])
np_arr = np.append(np_arr , 2)
np_arr = np.append(np_arr , 24)
print(np_arr)
OUTPUT: array([ 2., 24.])
It depends upon lower_case_table_names
system variable:
show variables where Variable_name='lower_case_table_names'
There are three possible values for this:
0
- lettercase specified in the CREATE TABLE
or CREATE DATABASE
statement. Name comparisons are case sensitive. 1
- Table names are stored in lowercase on disk and name comparisons are not case sensitive. 2
- lettercase specified in the CREATE TABLE
or CREATE DATABASE
statement, but MySQL converts them to lowercase on lookup.
Name comparisons are not case sensitive.Update:
Now you can follow all redirects with var request = require('request');
using the followAllRedirects
param.
request({
followAllRedirects: true,
url: url
}, function (error, response, body) {
if (!error) {
console.log(response);
}
});
Enabled
property to false
or
this.dataGridView1.DefaultCellStyle.SelectionBackColor = this.dataGridView1.DefaultCellStyle.BackColor;
this.dataGridView1.DefaultCellStyle.SelectionForeColor = this.dataGridView1.DefaultCellStyle.ForeColor;
Follow this:
List<string> name = new List<string>();
name.Add("Latif");
name.Add("Ram");
name.Add("Adam");
string nameOfString = (string.Join(",", name.Select(x => x.ToString()).ToArray()));
I found that running the npm install
command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.
Specifically, I was trying to use ng2-completer
$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.
I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.
cd foo/foo_app
$ npm install ng2-completer --save
I struggled with the same error code recently, due to a change in MySQL Server 5.6.20. I was able to solve the problem by changing the innodb_log_file_size in the my.ini text file.
In the release notes, it is explained that an innodb_log_file_size that is too small will trigger a "Row size too large error."
http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-20.html
Both the regex and included files are good methods, and I frequently use those. But another alternative is to use a "named location", which is a useful approach in many situations — especially more complicated ones. The official "If is Evil" page shows essentially the following as a good way to do things:
error_page 418 = @common_location;
location /first/location/ {
return 418;
}
location /second/location/ {
return 418;
}
location @common_location {
# The common configuration...
}
There are advantages and disadvantages to these various approaches. One big advantage to a regex is that you can capture parts of the match and use them to modify the response. Of course, you can usually achieve similar results with the other approaches by either setting a variable in the original block or using map
. The downside of the regex approach is that it can get unwieldy if you want to match a variety of locations, plus the low precedence of a regex might just not fit with how you want to match locations — not to mention that there are apparently performance impacts from regexes in some cases.
The main advantage of including files (as far as I can tell) is that it is a little more flexible about exactly what you can include — it doesn't have to be a full location block, for example. But it's also just subjectively a bit clunkier than named locations.
Also note that there is a related solution that you may be able to use in similar situations: nested locations. The idea is that you would start with a very general location, apply some configuration common to several of the possible matches, and then have separate nested locations for the different types of paths that you want to match. For example, it might be useful to do something like this:
location /specialpages/ {
# some config
location /specialpages/static/ {
try_files $uri $uri/ =404;
}
location /specialpages/dynamic/ {
proxy_pass http://127.0.0.1;
}
}
// 1. Read xml from file to StringBuilder (StringBuffer)
// 2. call s = stringBuffer.toString()
// 3. remove all "\n" and "\t":
s.replaceAll("\n","");
s.replaceAll("\t","");
edited:
I made a small mistake, it is better to use StringBuilder in your case (I suppose you don't need thread-safe StringBuffer)
If your current line wraps around the visible screen onto the next line, you can use g$ to get to the end of the screen line.
<configuration>
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
</configuration>
From here.
For IIS7 and above, you also need to add the lines below:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
You can check out this post on SuperUser.
Word starts page numbering over for each new section by default.
I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.
My method:
Format Page Numbers
Continue from Previous Section
radio button under Page numbering
I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.
try this:
$('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() {
$(this).remove(); // prevent memory leaks as @benweet suggested
$('body').css('background-image', 'url(http://picture.de/image.png)');
});
this will create new image in memory and use load event to detect when the src is loaded.
function converToLocalTime(serverDate) {
var dt = new Date(Date.parse(serverDate));
var localDate = dt;
var gmt = localDate;
var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
var localNow = new Date().getTimezoneOffset(); // get the timezone
// offset in minutes
var localTime = min - localNow; // get the local time
var dateStr = new Date(localTime * 1000 * 60);
// dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return dateStr;
}
An utility method like the following can be used to solve this.
import (
"os"
"path/filepath"
"log"
)
func ensureDir(fileName string) {
dirName := filepath.Dir(fileName)
if _, serr := os.Stat(dirName); serr != nil {
merr := os.MkdirAll(dirName, os.ModePerm)
if merr != nil {
panic(merr)
}
}
}
func main() {
_, cerr := os.Create("a/b/c/d.txt")
if cerr != nil {
log.Fatal("error creating a/b/c", cerr)
}
log.Println("created file in a sub-directory.")
}
Felipsmartins is correct.
It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.
Which means you can do this:
curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'
Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.
I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.
curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros
This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)
Hope it helps.
std
namespace (where features of the C++ Standard Library, such as string
or vector
, are declared).After you write this instruction, if the compiler sees string
it will know that you may be referring to std::string
, and if it sees vector
, it will know that you may be referring to std::vector
. (Provided that you have included in your compilation unit the header files where they are defined, of course.)
If you don't write it, when the compiler sees string
or vector
it will not know what you are refering to. You will need to explicitly tell it std::string
or std::vector
, and if you don't, you will get a compile error.
You can first make a conditional selection, and sum up the results of the selection using the sum
function.
>> df = pd.DataFrame({'a': [1, 2, 3]})
>> df[df.a > 1].sum()
a 5
dtype: int64
Having more than one condition:
>> df[(df.a > 1) & (df.a < 3)].sum()
a 2
dtype: int64
It is almost fine. Just have:
Player[] thePlayers = new Player[playerCount + 1];
And let the loop be:
for(int i = 0; i < thePlayers.length; i++)
And note that java convention dictates that names of methods and variables should start with lower-case.
Update: put your method within the class body.
UITableView
has a property separatorInset
. You can use that to set the insets of the table view separators to zero to let them span the full width of the screen.
[tableView setSeparatorInset:UIEdgeInsetsZero];
Note: If your app is also targeting other iOS versions, you should check for the availability of this property before calling it by doing something like this:
if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
Going to provide a slightly different answer to those provided so far.
If you have a row for an anonymous user from localhost in your users table ''@'localhost'
then this will be treated as more specific than your user with wildcard'd host 'user'@'%'
. This is why it is necessary to also provide 'user'@'localhost'
.
You can see this explained in more detail at the bottom of this page.
None of these solutions work for me, process.stdout.write('ok\033[0G')
and just using '\r'
just create a new line but don't overwrite on Mac OSX 10.9.2.
EDIT: I had to use this to replace the current line:
process.stdout.write('\033[0G');
process.stdout.write('newstuff');
I just installed conda 4.7.11 in Windows 10. OpenCV can be easily installed in Anaconda Navigator. After launching Navigator, click on Environments on the left panel. In the top drop-down, select Not installed. Then search for py-opencv, tick on the left checkbox to install it. It will install the dependent package libopencv. I use import cv2
in Spyder to access it.
This is somewhat cleaner, i think. Note the usage of the "defaultValue" property of the input:
<script>
function onBlur(el) {
if (el.value == '') {
el.value = el.defaultValue;
}
}
function onFocus(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
}
</script>
<form>
<input type="text" value="[some default value]" onblur="onBlur(this)" onfocus="onFocus(this)" />
</form>
You can use float on that particular div, e.g.
<div style="float:right;">
Float the div you want more space to have to the left as well:
<div style="float:left;">
If all else fails give the div on the right position:absolute and then move it as right as you want it to be.
<div style="position:absolute; left:-500px; top:30px;">
etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.
I want this function to work with all positive 64-bit signed integers
Math.sqrt()
works with doubles as input parameters, so you won't get accurate results for integers bigger than 2^53.
This The out and ref Paramerter in C# has some good examples.
The basic difference outlined is that out
parameters don't need to be initialized when passed in, while ref parameters do.
Although a bit
late in posting an answer, here is an alternative approach without using margins.
<style>
#divMain { width: 500px; }
#div1 { width: 100px; float: left; background-color: #fcc; }
#div2 { overflow:hidden; background-color: #cfc; }
#div3 { width: 100px; float: right; background-color: #ccf; }
</style>
<div id="divMain">
<div id="div1">
div 1
</div>
<div id="div3">
div 3
</div>
<div id="div2">
div 2<br />bit taller
</div>
</div>
This method works like magic, but here is an explanation :)\
I used that and it worked Perfectly :)
UIView* footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 500)];
[footerView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"ProductCellBackground.png"]]];
self.tableView.tableFooterView = footerView;
[self.tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
[self.tableView setContentInset:(UIEdgeInsetsMake(0, 0, -500, 0))];
Here is the another solution to hide dynamically a column
define class for both th and td of the column to hide
<table>
<tr>
<th> Column 1 </th>
<th class="dynamic-hidden-col"> Column 2 </th>
<th Column 3 </th>
</tr>
<tr>
<td> Value 1 </td>
<td class="dynamic-hidden-col"> Value 2 </td>
<td> Value 3 </td>
</tr>
<td> row 2 Value 1 </td>
<td class="dynamic-hidden-col"> row 2 Value 2 </td>
<td> row 2 Value 3 </td>
<tr>
</table>
Here is the Jquery script for hide column.
$('#hide-col').click(function () {
$(".dynmic-hidden-col").hide();
});
This way the table column can be hidden dynamically.
For anyone who is aware of the risks this implementation imposes, to have the password sync to your ViewModel simply add Mode=OneWayToSource.
XAML
<PasswordBox
ff:PasswordHelper.Attach="True"
ff:PasswordHelper.Password="{Binding Path=Password, Mode=OneWayToSource}" />
When the using()
for your StreamReader
is ending, it's disposing the object and closing the stream, which your StreamWriter
is still trying to use.
As an addition to the solution:
ul li:before {
content: '?';
}
You can use any SVG icon as the content, such as the Font Aswesome.
ul {_x000D_
list-style: none;_x000D_
padding-left: 0;_x000D_
}_x000D_
li {_x000D_
position: relative;_x000D_
padding-left: 1.5em; /* space to preserve indentation on wrap */_x000D_
}_x000D_
li:before {_x000D_
content: ''; /* placeholder for the SVG */_x000D_
position: absolute;_x000D_
left: 0; /* place the SVG at the start of the padding */_x000D_
width: 1em;_x000D_
height: 1em;_x000D_
background: url("data:image/svg+xml;utf8,<?xml version='1.0' encoding='utf-8'?><svg width='18' height='18' viewBox='0 0 1792 1792' xmlns='http://www.w3.org/2000/svg'><path d='M1671 566q0 40-28 68l-724 724-136 136q-28 28-68 28t-68-28l-136-136-362-362q-28-28-28-68t28-68l136-136q28-28 68-28t68 28l294 295 656-657q28-28 68-28t68 28l136 136q28 28 28 68z'/></svg>") no-repeat;_x000D_
}
_x000D_
<ul>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>This is my text, it's pretty long so it needs to wrap. Note that wrapping preserves the indentation that bullets had!</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>
_x000D_
Note: To solve the wrapping problem that other answers had:
<li>
position: absolute; left: 0
)Here are more Font Awesome black icons.
Check this CODEPEN to see how you can add colors and change their size.
I think that Proguard is the best. It is also possible to integrate it with your IDE (for example NetBeans). However, consider that if you obfuscate your code it could be difficult to track problems in your logs..
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
For completeness, the simplest solution i know with seaborn as of late 2019, if one is using Jupyter:
import seaborn as sns
sns.heatmap(dataframe.corr())
For me, the problem was that when I copied the solution to a new folder and opened it, it was missing the Nuget folder as shown below. I copied this folder over and everything worked. Note: This same folder was in our source control but not in this solutions project, it was up one directory.
Another approach would be like this:
temp = df['Seatblocks'].str.split(' ')
data = data.reindex(data.index.repeat(temp.apply(len)))
data['new_Seatblocks'] = np.hstack(temp)
You can get the milliseconds since 1/1/1970 using such code:
private static DateTime JanFirst1970 = new DateTime(1970, 1, 1);
public static long getTime()
{
return (long)((DateTime.Now.ToUniversalTime() - JanFirst1970).TotalMilliseconds + 0.5);
}
None of previous answers is good on Ubuntu. Try this:
find . ! -path "*/test/*" -type f -name "*.js" ! -name "*-min-*" ! -name "*console*"
I have found this here
You could use componentDidMount and componentWillUnmount methods:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class MovieItem extends Component
{
_handleNVEvent = event => {
...
};
componentDidMount() {
ReactDOM.findDOMNode(this).addEventListener('nv-event', this._handleNVEvent);
}
componentWillUnmount() {
ReactDOM.findDOMNode(this).removeEventListener('nv-event', this._handleNVEvent);
}
[...]
}
export default MovieItem;
In addition to @obscur's answer, here is an example of how you can access both the key
and value
from the @View.
Pipe:
@Pipe({
name: 'keyValueFilter'
})
export class keyValueFilterPipe {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(function(key) {
let pair = {};
let k = 'key';
let v = 'value'
pair[k] = key;
pair[v] = value[key];
return pair;
});
}
}
View:
<li *ngFor="let u of myObject |
keyValueFilter">First Name: {{u.key}} <br> Last Name: {{u.value}}</li>
So if the object were to look like:
myObject = {
Daario: Naharis,
Victarion: Greyjoy,
Quentyn: Ball
}
The generated outcome would be:
First name: Daario
Last Name: Naharis
First name: Victarion
Last Name: Greyjoy
First name: Quentyn
Last Name: Ball
When using JavaScript to access an HTML element, there is a good chance that the element is not on the page and therefore not in the dom as far as JavaScript is concerned, when the code to access that element runs.
This problem can occur even though you can visually see the HTML element in the browser window or have the code set to be called in the onload method.
I ran into this problem after writing code to repopulate specific div elements on a page after retrieving the cookies.
What is apparently happening is that even though the HTML has loaded and is outputted by the browser, the JavaScript code is running before the page has completed loading.
The solution to this problem which just may be a JavaScript bug, is to place the code you want to run within a timer that delays the code run by 400 milliseconds or so. You will need to test it to determine how quick you can run the code.
I also made a point to test for the element before attempting to assign values to it.
window.setTimeout(function() {
if( document.getElementById("book") )
{ // Code goes here }, 400 /* but after 400 ms */);
This may or may not help you solve your problem, but keep this in mind and understand that browsers do not always function as expected.
I had same problem finding out what kind of Hash does Wordpress Uses .
It is wp hash password.
Example
Compare an already hashed password with its plain-text string:
<?php
$wp_hasher = new PasswordHash(8, TRUE);
$password_hashed = '$P$B55D6LjfHDkINU5wF.v2BuuzO0/XPk/';
$plain_password = 'test';
if($wp_hasher->CheckPassword($plain_password, $password_hashed)) {
echo "YES, Matched";
} else {
echo "No, Wrong Password";
}
?>
See These Links: https://codex.wordpress.org/Function_Reference/wp_hash_password
https://developer.wordpress.org/reference/functions/wp_hash_password
It uses PasswordHash, which adds salt to the password and hashes it with 8 passes of MD5.
I discovered that the order of adding roles and features is important. On a fresh system I activate the role "application server" and there check explicitly .net, web server support and finally process activation service Then automatically a dialogue comes up that the role "Web server" needs to be added also.
It seems more elegant combining two classes. You can drop two-lines
class if only one row need see:
.ellipse {_x000D_
white-space: nowrap;_x000D_
display:inline-block;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
}_x000D_
.two-lines {_x000D_
-webkit-line-clamp: 2;_x000D_
display: -webkit-box;_x000D_
-webkit-box-orient: vertical;_x000D_
white-space: normal;_x000D_
}_x000D_
.width{_x000D_
width:100px;_x000D_
border:1px solid hotpink;_x000D_
}
_x000D_
<span class='width ellipse'>_x000D_
some texts some texts some texts some texts some texts some texts some texts_x000D_
</span>_x000D_
_x000D_
<span class='width ellipse two-lines'>_x000D_
some texts some texts some texts some texts some texts some texts some texts_x000D_
</span>
_x000D_
Again, even though this is an old question, it is very relevant! And I have found a simple way to normalise certain columns without the need of any packages:
normFunc <- function(x){(x-mean(x, na.rm = T))/sd(x, na.rm = T)}
For example
x<-rnorm(10,14,2)
y<-rnorm(10,7,3)
z<-rnorm(10,18,5)
df<-data.frame(x,y,z)
df[2:3] <- apply(df[2:3], 2, normFunc)
You will see that the y and z columns have been normalised. No packages needed :-)
Whilst you certainly can use MySQL's IF()
control flow function as demonstrated by dbemerlin's answer, I suspect it might be a little clearer to the reader (i.e. yourself, and any future developers who might pick up your code in the future) to use a CASE
expression instead:
UPDATE Table
SET A = CASE
WHEN A > 0 AND A < 1 THEN 1
WHEN A > 1 AND A < 2 THEN 2
ELSE A
END
WHERE A IS NOT NULL
Of course, in this specific example it's a little wasteful to set A
to itself in the ELSE
clause—better entirely to filter such conditions from the UPDATE
, via the WHERE
clause:
UPDATE Table
SET A = CASE
WHEN A > 0 AND A < 1 THEN 1
WHEN A > 1 AND A < 2 THEN 2
END
WHERE (A > 0 AND A < 1) OR (A > 1 AND A < 2)
(The inequalities entail A IS NOT NULL
).
Or, if you want the intervals to be closed rather than open (note that this would set values of 0
to 1
—if that is undesirable, one could explicitly filter such cases in the WHERE
clause, or else add a higher precedence WHEN
condition):
UPDATE Table
SET A = CASE
WHEN A BETWEEN 0 AND 1 THEN 1
WHEN A BETWEEN 1 AND 2 THEN 2
END
WHERE A BETWEEN 0 AND 2
Though, as dbmerlin also pointed out, for this specific situation you could consider using CEIL()
instead:
UPDATE Table SET A = CEIL(A) WHERE A BETWEEN 0 AND 2
Only SortedSet
can do the ordering of the Set
SELECT group, COUNT(*) FROM table GROUP BY group ORDER BY group
or to order by the count
SELECT group, COUNT(*) AS count FROM table GROUP BY group ORDER BY count DESC