SHA1 and a salt should suffice (depending, naturally, on whether you are coding something for Fort Knox or a login system for your shopping list) for the foreseeable future. If SHA1 isn't good enough for you, use SHA256.
The idea of a salt is to throw the hashing results off balance, so to say. It is known, for example, that the MD5-hash of an empty string is d41d8cd98f00b204e9800998ecf8427e
. So, if someone with good enough a memory would see that hash and know that it's the hash of an empty string. But if the string is salted (say, with the string "MY_PERSONAL_SALT
"), the hash for the 'empty string' (i.e. "MY_PERSONAL_SALT
") becomes aeac2612626724592271634fb14d3ea6
, hence non-obvious to backtrace. What I'm trying to say, that it's better to use any salt, than not to. Therefore, it's not too much of an importance to know which salt to use.
There are actually websites that do just this - you can feed it a (md5) hash, and it spits out a known plaintext that generates that particular hash. If you would get access to a database that stores plain md5-hashes, it would be trivial for you to enter the hash for the admin to such a service, and log in. But, if the passwords were salted, such a service would become ineffective.
Also, double-hashing is generally regarded as bad method, because it diminishes the result space. All popular hashes are fixed-length. Thus, you can have only a finite values of this fixed length, and the results become less varied. This could be regarded as another form of salting, but I wouldn't recommend it.
In a generic Markdown document, use:
<style>body {text-align: right}</style>
or
<style>body {text-align: justify}</style>
Does not seem to work with Jupyter though.
One additional point to note here is that, as the basic principle of Spark RDD is immutability. The repartition or coalesce will create new RDD. The base RDD will continue to have existence with its original number of partitions. In case the use case demands to persist RDD in cache, then the same has to be done for the newly created RDD.
scala> pairMrkt.repartition(10)
res16: org.apache.spark.rdd.RDD[(String, Array[String])] =MapPartitionsRDD[11] at repartition at <console>:26
scala> res16.partitions.length
res17: Int = 10
scala> pairMrkt.partitions.length
res20: Int = 2
If you want to compare based on the commit messages, you can do the following:
git fetch
git log --oneline origin/master | cut -d' ' -f2- > master_log
git log --oneline origin/branch-X | cut -d' ' -f2- > branchx_log
diff <(sort master_log) <(sort branchx_log)
There are some differences between Function overloading & overriding though both contains the same function name.In overloading ,between the same name functions contain different type of argument or return type;Such as: "function add (int a,int b)" & "function add(float a,float b); Here the add() function is overloaded. In the case of overriding both the argument and function name are same.It generally found in inheritance or in traits.We have to follow some tactics to introduce, what function will execute now. So In overriding the programmer follows some tactics to execute the desired function where in the overloading the program can automatically identify the desired function...Thanks!
git commit -am "msg"
is not same as git add file
and git commit -m "msg"
If you have some files which were never added to git tracking you still need to do git add file
The “git commit -a” command is a shortcut to a two-step process. After you modify a file that is already known by the repo, you still have to tell the repo, “Hey! I want to add this to the staged files and eventually commit it to you.” That is done by issuing the “git add” command. “git commit -a” is staging the file and committing it in one step.
Source: "git commit -a" and "git add"
Another alternative using reorder to order the levels of a factor. In ascending (n) or descending order (-n) based on the count. Very similar to the one using fct_reorder
from the forcats
package:
Descending order
df %>%
count(Position) %>%
ggplot(aes(x = reorder(Position, -n), y = n)) +
geom_bar(stat = 'identity') +
xlab("Position")
Ascending order
df %>%
count(Position) %>%
ggplot(aes(x = reorder(Position, n), y = n)) +
geom_bar(stat = 'identity') +
xlab("Position")
Data frame:
df <- structure(list(Position = structure(c(3L, 3L, 1L, 1L, 1L, 2L), .Label = c("Defense",
"Striker", "Zoalkeeper"), class = "factor"), Name = structure(c(2L,
1L, 3L, 5L, 4L, 6L), .Label = c("Frank", "James", "Jean", "John",
"Steve", "Tim"), class = "factor")), class = "data.frame", row.names = c(NA,
-6L))
Java allocates 2 of 2 bytes for character as it follows UTF-16. It occupies minimum 2 bytes while storing a character, and maximum of 4 bytes. There is no 1 byte or 3 bytes of storage for character.
If you just want to print a decimal number with 2 digits after decimal point in specific format no matter of locals use something like this
dim d as double = 1.23456789
dim s as string = d.Tostring("0.##", New System.Globalization.CultureInfo("en-US"))
It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.
A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t
... which yields:
t a avg
----------
1 1 3.00
2 5 3.00
3 3 4.33
4 5 4.00
5 4 6.67
6 11 7.50
As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding
) and the subsequent row (1 following
).
When you write ROWS UNBOUNDED PRECEDING
, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t
yielding...
t a sum
---------
1 1 1
2 5 6
3 3 9
4 5 14
5 4 18
6 11 29
Here's another very good explanations of SQL window functions.
You can try using:
textBox.ReadOnly = true;
textBox.BackColor = System.Drawing.SystemColors.Window;
The last line is only neccessary if you want a non-grey background color.
Counting Words in a String:
This might also help -->
package data.structure.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CountWords {
public static void main(String[] args) throws IOException {
// Couting number of words in a string
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter Your String");
String input = br.readLine();
char[] arr = input.toCharArray();
int i = 0;
boolean notCounted = true;
int counter = 0;
while (i < arr.length) {
if (arr[i] != ' ') {
if (notCounted) {
notCounted = false;
counter++;
}
} else {
notCounted = true;
}
i++;
}
System.out.println("words in the string are : " + counter);
}
}
The difference between factory and service is just like the difference between a function and an object
Factory Provider
Gives us the function's return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)
Singleton and will only be created once
Reusable components
Factory are a great way for communicating between controllers like sharing data.
Can use other dependencies
Usually used when the service instance requires complex creation logic
Cannot be injected in .config()
function.
Used for non configurable services
If you're using an object, you could use the factory provider.
Syntax: module.factory('factoryName', function);
Service Provider
Gives us the instance of a function (object)- You just instantiated with the ‘new’ keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. (Hypothetical Scenario)
Singleton and will only be created once
Reusable components
Services are used for communication between controllers to share data
You can add properties and functions to a service object by using the this
keyword
Dependencies are injected as constructor arguments
Used for simple creation logic
Cannot be injected in .config()
function.
If you're using a class you could use the service provider
Syntax: module.service(‘serviceName’, function);
In below example I have define MyService
and MyFactory
. Note how in .service
I have created the service methods using this.methodname.
In .factory
I have created a factory object and assigned the methods to it.
AngularJS .service
module.service('MyService', function() {
this.method1 = function() {
//..method1 logic
}
this.method2 = function() {
//..method2 logic
}
});
AngularJS .factory
module.factory('MyFactory', function() {
var factory = {};
factory.method1 = function() {
//..method1 logic
}
factory.method2 = function() {
//..method2 logic
}
return factory;
});
Also Take a look at this beautiful stuffs
Confused about service vs factory
A callback is an idea of passing a function as a parameter to another function and have this one invoked once the process has completed.
If you get the concept of callback through awesome answers above, I recommend you should learn the background of its idea.
"What made them(Computer-Scientists) develop callback?" You might learn a problem, which is blocking.(especially blocking UI) And callback is not the only solution to it. There are a lot of other solutions(ex: Thread, Futures, Promises...).
Something like this page ?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>BSO Communication</title>
<style type="text/css">
.submit {
border : 0;
background : url(ok.gif) left top no-repeat;
height : 24px;
width : 24px;
cursor : pointer;
text-indent : -9999px;
}
html:first-child .submit {
padding-left : 1000px;
}
</style>
<!--[if IE]>
<style type="text/css">
.submit {
text-indent : 0;
color : expression(this.value = '');
}
</style>
<![endif]-->
</head>
<body>
<h1>Display input submit as image with CSS</h1>
<p>Take a look at <a href="/2007/07/26/afficher-un-input-submit-comme-une-image/">the related article</a> (in french).</p>
<form action="" method="get">
<fieldset>
<legend>Some form</legend>
<p class="field">
<label for="input">Some value</label>
<input type="text" id="input" name="value" />
<input type="submit" class="submit" />
</p>
</fieldset>
</form>
<hr />
<p>This page is part of the <a href="http://www.bsohq.fr">BSO Communication blog</a>.</p>
</body>
</html>
You're calling writer.close();
after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.
public void writeToFile(){
String file_text= pedStatusText + " " + gatesStatus + " " + DrawBridgeStatusText;
try {
writer.write(file_text);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And add a method cleanUp
to close the stream.
public void cleanUp() {
writer.close();
}
This means that you have the responsibility to make sure that you're calling cleanUp
when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.
EDIT: You can create a new stream each time you want to write to the file, by moving writer
into the writeToFile()
method..
public void writeToFile() {
FileWriter writer = new FileWriter("status.txt", true);
// ... Write to the file.
writer.close();
}
Same Network Connectivity issue for me in android emulator V 7.1.1, Then I have decreased the Android Version below 7.1.1 in my Android Emulator then its work fine.
You can use NSInputStream
which has a basic implementation for file streams. You can read bytes into a buffer (read:maxLength:
method). You have to scan the buffer for newlines yourself.
I was experiencing this issue on a drupal site and none of the other solutions in this thread helped. After some troubleshooting I found the local.settings.php had a closing tag with a space after it like so:
<?php
$databases = array(
'default' =>
array (
'default' =>
array (
'driver' => 'mysql',
'database' => 'xxx',
'username' => 'xxx',
'password' => 'xxx',
'port' => '',
'host' => 'xxx',
),
),
);
?>
Updating local.settings.php to the following resolved:
<?php
$databases = array(
'default' =>
array (
'default' =>
array (
'driver' => 'mysql',
'database' => 'xxx',
'username' => 'xxx',
'password' => 'xxx',
'port' => '',
'host' => 'xxx',
),
),
);
The closing "?>" PHP tag is not necessary here. If you choose to use a closing tag you must ensure there are no characters / whitespace after it.
Basically, you should include the class' header file in the code where you want to use the class in the shared library. Then, when you link, use the '-l' flag to link your code with the shared library. Of course, this requires the .so to be where the OS can find it. See 3.5. Installing and Using a Shared Library
Using dlsym is for when you don't know at compile time which library you want to use. That doesn't sound like it's the case here. Maybe the confusion is that Windows calls the dynamically loaded libraries whether you do the linking at compile or run-time (with analogous methods)? If so, then you can think of dlsym as the equivalent of LoadLibrary.
If you really do need to dynamically load the libraries (i.e., they're plug-ins), then this FAQ should help.
If you have the Adblock extension, make sure you add the domain into the exception list. I had that problem with Google Analytics
stdbool.h
defines macros true
and false
, but remember they are defined to be 1 and 0.
That is why sizeof(true)
is 4.
You could use IFS (internal field separator) temporally using :
OLD_IFS=$IFS # Stores Default IFS
IFS=$'\n' # Set it to line break
for f in `find test/* -type d`; do
echo $f
done
IFS=$OLD_IFS
<!>
A small update on the "New Way" answer from Jhon.
You need to build the path instead of using the CodeBase string when working with ASP.NET/MVC
var codeBase = assembly.GetName().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
As android latest update doesn't support 'compile' keyword use 'implementation' in place inside your module build.gradle file.
And check thoroughly in build.gradle for dependancy with + sign like this.
implementation 'com.android.support:support-v4:28.+'
If there are any dependencies like this, just update them with a specific version. After that:
Working fiddle:
$.ajax({
url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
dataType: 'JSONP',
jsonpCallback: 'callback',
type: 'GET',
success: function (data) {
console.log(data);
}
});
I had to manually set the callback to callback
, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.
Use something like LiquiBase this lets you keep revision control of your Liquibase files. you can tag changes for production only, and have lb keep your DB up to date for either production or development, (or whatever scheme you want).
I've made a single powerfull script that will:
-Compile and run multi language code like C
, C++
, Java
, Python
and C#
.
-Delete the old executable before compiling code.
-Only run the code if it's compiled successfully.
I've also made a very noob friendly tutorial Transform Notepad++ to Powerful Multi Languages IDE which contains some additional scripts like to only run or Compile the code, run code inside CMD etc.
npp_console 1 //open console
NPP_CONSOLE - //disable output of commands
npe_console m- //disable unnecessary output
con_colour bg= 191919 fg= F5F5F5 //set console colors
npp_save //save the file
cd $(CURRENT_DIRECTORY) //follow current directory
NPP_CONSOLE + //enable output
IF $(EXT_PART)==.c GOTO C //if .c file goto C label
IF $(EXT_PART)==.cpp GOTO CPP //if .cpp file goto CPP label
IF $(EXT_PART)==.java GOTO JAVA //if .java file goto JAVA label
IF $(EXT_PART)==.cs GOTO C# //if .cs file goto C# label
IF $(EXT_PART)==.py GOTO PYTHON //if .py file goto PYTHON label
echo FILE SAVED
GOTO EXITSCRIPT // else treat it as a text file and goto EXITSCRIPT
//C label
:C
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"//delete existing executable file if exists
gcc "$(FILE_NAME)" -o $(NAME_PART) //compile file
IF $(EXITCODE) != 0 GOTO EXITSCRIPT //if any compilation error then abort
echo C CODE COMPILED SUCCESSFULLY: //print message on console
$(NAME_PART) //run file in cmd, set color to green and pause cmd after output
GOTO EXITSCRIPT //finally exits
:CPP
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"
g++ "$(FILE_NAME)" -o $(NAME_PART)
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo C++ CODE COMPILED SUCCESSFULLY:
$(NAME_PART)
GOTO EXITSCRIPT
:JAVA
cmd /C if exist "$(NAME_PART).class" cmd /c del "$(NAME_PART).class"
javac $(FILE_NAME) -Xlint
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo JAVA CODE COMPILED SUCCESSFULLY:
java $(NAME_PART)
GOTO EXITSCRIPT
:C#
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"
csc $(FILE_NAME)
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo C# CODE COMPILED SUCCESSFULLY:
$(NAME_PART)
GOTO EXITSCRIPT
:PYTHON
echo RUNNING PYTHON SCRIPT IN CMD: //python is a script so no need to compile
python $(NAME_PART).py
GOTO EXITSCRIPT
:EXITSCRIPT
// that's all, folks!
Original (And Correct) Answer:
You can use is()
and check for the selector :hover
.
var isHovered = $('#elem').is(":hover"); // returns true or false
Example: http://jsfiddle.net/Meligy/2kyaJ/3/
(This only works when the selector matches ONE element max. See Edit 3 for more)
.
Edit 1 (June 29, 2013): (Applicable to jQuery 1.9.x only, as it works with 1.10+, see next Edit 2)
This answer was the best solution at the time the question was answered. This ':hover' selector was removed with the .hover()
method removal in jQuery 1.9.x.
Interestingly a recent answer by "allicarn" shows it's possible to use :hover
as CSS selector (vs. Sizzle) when you prefix it with a selector $($(this).selector + ":hover").length > 0
, and it seems to work!
Also, hoverIntent plugin mentioned in a another answer looks very nice as well.
Edit 2 (September 21, 2013): .is(":hover")
works
Based on another comment I have noticed that the original way I posted, .is(":hover")
, actually still works in jQuery, so.
It worked in jQuery 1.7.x.
It stopped working in 1.9.1, when someone reported it to me, and we all thought it was related to jQuery removing the hover
alias for event handling in that version.
It worked again in jQuery 1.10.1 and 2.0.2 (maybe 2.0.x), which suggests that the failure in 1.9.x was a bug or so not an intentional behaviour as we thought in the previous point.
If you want to test this in a particular jQuery version, just open the JSFidlle example at the beginning of this answer, change to the desired jQuery version and click "Run". If the colour changes on hover, it works.
.
As shown by @Wilmer in the comments, he has a fiddle which doesn't even work against jQuery versions I and others here tested it against. When I tried to find what's special about his case I noticed that he was trying to check multiple elements at a time. This was throwing Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: hover
.
So, working with his fiddle, this does NOT work:
var isHovered = !!$('#up, #down').filter(":hover").length;
While this DOES work:
var isHovered = !!$('#up,#down').
filter(function() { return $(this).is(":hover"); }).length;
It also works with jQuery sequences that contain a single element, like if the original selector matched only one element, or if you called .first()
on the results, etc.
This is also referenced at my JavaScript + Web Dev Tips & Resources Newsletter.
As in most languages the format is
%.2f
you can see more examples here
Edit: I also got this if your concerned about the display of the point in cases of 25.00
{
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setPositiveFormat:@"0.##"];
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.3]]);
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.0]]);
}
2010-08-22 15:04:10.614 a.out[6954:903] 25.34 2010-08-22 15:04:10.616 a.out[6954:903] 25.3 2010-08-22 15:04:10.617 a.out[6954:903] 25
Below you can find my implementation of gradient descent for linear regression problem.
At first, you calculate gradient like X.T * (X * w - y) / N
and update your current theta with this gradient simultaneously.
Here is the python code:
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import random
def generateSample(N, variance=100):
X = np.matrix(range(N)).T + 1
Y = np.matrix([random.random() * variance + i * 10 + 900 for i in range(len(X))]).T
return X, Y
def fitModel_gradient(x, y):
N = len(x)
w = np.zeros((x.shape[1], 1))
eta = 0.0001
maxIteration = 100000
for i in range(maxIteration):
error = x * w - y
gradient = x.T * error / N
w = w - eta * gradient
return w
def plotModel(x, y, w):
plt.plot(x[:,1], y, "x")
plt.plot(x[:,1], x * w, "r-")
plt.show()
def test(N, variance, modelFunction):
X, Y = generateSample(N, variance)
X = np.hstack([np.matrix(np.ones(len(X))).T, X])
w = modelFunction(X, Y)
plotModel(X, Y, w)
test(50, 600, fitModel_gradient)
test(50, 1000, fitModel_gradient)
test(100, 200, fitModel_gradient)
img{display: flex; max-width: 80%; margin: auto;}
This is working for me. You can also use display: table in this case. Moreover, if you don't want to stick to this approach you can use the following:
img{position: relative; left: 50%;}
Follow the steps below:
1- git stash
2- git add .
3- git commit -m "your commit message"
In case of WSS 3.0 recently I experienced same issue. It was because of column that was accessed from code was not present in the wss list.
It was my own stupidity:
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
Putting this inside onCreate()
method fixed my problem.
You may try to use Trove http://trove.starlight-systems.com/
TIntObjectHashMap is probably what you are looking for.
Use the autoescape
to turn HTML escaping off:
{% autoescape off %}{{ message }}{% endautoescape %}
There is also a method in the test util. So all that has to be done is:
tf.test.is_gpu_available()
and/or
tf.test.gpu_device_name()
Look up the Tensorflow docs for arguments.
I just had the same issue and this helped me:
html {
height: auto;
min-height: 100%;
background-size:cover;
}
Depending on how big your arrays are you might consider an efficient algorithm O(n log n)
def equal_a(a1, a2)
a1sorted = a1.sort
a2sorted = a2.sort
return false if a1.length != a2.length
0.upto(a1.length - 1) do
|i| return false if a1sorted[i] != a2sorted[i]
end
end
Sorting costs O(n log n) and checking each pair costs O(n) thus this algorithm is O(n log n). The other algorithms cannot be faster (asymptotically) using unsorted arrays.
InputProperty[] ip = new InputProperty[nvPairs.Length];
Or, you can use a list like so:
List<InputProperty> list = new List<InputProperty>();
InputProperty ip = new (..);
list.Add(ip);
update.items = list.ToArray();
Another thing I'd like to point out, in C# you can delcare your int variable use in a for loop right inside the loop:
for(int i = 0; i<nvPairs.Length;i++
{
.
.
}
And just because I'm in the mood, here's a cleaner way to do this method IMO:
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
var ip = new List<InputProperty>();
foreach(var nvPair in nvPairs)
{
if (nvPair == null) break;
var inputProp = new InputProperty
{
Name = "udf:" + nvPair.Name,
Val = nvPair.Value
};
ip.Add(inputProp);
}
update.Items = ip.ToArray();
return update;
}
May be answer would depend on what problem you have with using iterator? may be use
i = 100
while i:
print i
i-=1
or
def loop(N, doSomething):
if not N:
return
print doSomething(N)
loop(N-1, doSomething)
loop(100, lambda a:a)
but frankly i see no point in using such approaches
How about this one using BlueBird?
function fetchUserDetails(arr) {
return Promise.each(arr, function(email) {
return db.getUser(email).done(function(res) {
logger.log(res);
});
});
}
This snippet will handle more than two checkboxes in case you decide to expand the form.
$("input[type=text]").keyup(function(){
var count = 0, attr = "disabled", $sub = $("#submit"), $inputs = $("input[type=text]");
$inputs.each(function(){
count += ($.trim($(this).val())) ? 1:0;
});
(count >= $inputs.length ) ? $sub.removeAttr(attr):$sub.attr(attr,attr);
});
Working Example: http://jsfiddle.net/sr4gq/
The xmlhttp request method is not valid for the files on local disk because the browser security does not allow us to do so.But we can override the browser security by creating a shortcut->right click->properties In target "... browser location path.exe" append --allow-file-access-from-files.This is tested on chrome,however care should be taken that all browser windows should be closed and the code should be run from the browser opened via this shortcut.
Supposing you use sql server:
WHERE StartTime BETWEEN DATEADD(HOUR, -1, GetDate())
AND DATEADD(HOUR, 1, GetDate())
If you are using ajax as a function remember it expects JSON data to be returned to it, with the parameters set.
$('#example').dataTable({
"ajax" : function (data, callback, settings) {
callback({
data: [...],
recordsTotal: 40,
recordsFiltered: 40}
));
}
})
If you want to efficiently display big number of images I recommend using IPyPlot package
import ipyplot
ipyplot.plot_images(images_array, max_images=20, img_width=150)
There are some other useful functions in that package where you can display images in interactive tabs (separate tab for each label/class) which is very helpful for all the ML classification tasks.
What is missing in the question and all the answers is that you might need the passphrase to read public data from the PKCS#12 (.pfx) keystore. If you need a passphrase or not depends on how the PKCS#12 file was created. You can check the ASN1 structure of the file (by running it through a ASN1 parser, openssl or certutil can do this too), if the PKCS#7 data (e.g. OID prefix 1.2.840.113549.1.7) is listed as 'encrypted' or with a cipher-spec or if the location of the data in the asn1 tree is below an encrypted node, you won't be able to read it without knowledge of the passphrase. It means your 'openssl pkcs12' command will fail with errors (output depends on the version). For those wondering why you might be interested in the certificate of a PKCS#12 without knowledge of the passphrase. Imagine you have many keystores and many phassphrases and you are really bad at keeping them organized and you don't want to test all combinations, the certificate inside the file could help you find out which password it might be. Or you are developing software to migrate/renew a keystore and you need to decide in advance which procedure to initiate based on the contained certicate without user interaction. So the latter examples work without passphrase depending on the PKCS#12 structure.
Just wanted to add that, because I didn't find an answer myself and spend a lot of time to figure it out.
When nothing else works when it should work, restart ng serve. It's sad to find this kind of bugs.
Check if you access internet through a proxy, and then your add internet proxy address to yum
configuration.
add
proxy=http://ip:port
to /etc/yum.conf
As a follow-up to another answer, I was asked how I changed the spinner icon to get something like this:
One pretty easy way is to use a custom spinner item layout:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
R.layout.view_spinner_item,
ITEMS
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
In res/layout/view_spinner_item.xml
, define a TextView with android:drawableRight
pointing to the desired icon (along with any customisations to text size, paddings and so on, if you wish):
<?xml version="1.0" encoding="utf-8"?>
<!-- Custom spinner item layout -->
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerItemStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="@dimen/text_size_medium"
android:drawablePadding="@dimen/spacing_medium"
android:drawableRight="@drawable/ic_arrow_down"
/>
(For the opened state, just use android.R.layout.simple_spinner_dropdown_item
or similarly create a customised layout if you want to tweak every aspect of your spinner.)
To get the background & colours looking nice, set the Spinner's android:background
and android:popupBackground
as shown in that other question. And if you were wondering about the custom font in the screenshot above, you'll need a custom SpinnerAdapter.
That's a very complex question for a simple answer.
You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.
Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.
At the very top level I think quality REST API docs require at least the following:
Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.
An O(n) way would be as below:
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 4, 4);
Set<Integer> duplicatedNumbersRemovedSet = new HashSet<>();
Set<Integer> duplicatedNumbersSet = numbers.stream().filter(n -> !duplicatedNumbersRemovedSet.add(n)).collect(Collectors.toSet());
The space complexity would go double in this approach, but that space is not a waste; in-fact, we now have the duplicated alone only as a Set as well as another Set with all the duplicates removed too.
Handling the rows / sections logic similar to iOS's UITableView is not as simple in Android as it is in iOS, however, when you use RecyclerView - the flexibility of what you can do is far greater.
In the end, it's all about how you figure out what type of view you're displaying in the Adapter. Once you got that figured out, it should be easy sailing (not really, but at least you'll have that sorted).
The Adapter exposes two methods which you should override:
getItemViewType(int position)
This method's default implementation will always return 0, indicating that there is only 1 type of view. In your case, it is not so, and so you will need find a way to assert which row corresponds to which view type. Unlike iOS, which manages this for you with rows and sections, here you will have only one index to rely on, and you'll need to use your developer skills to know when a position correlates to a section header, and when it correlates to a normal row.
createViewHolder(ViewGroup parent, int viewType)
You need to override this method anyway, but usually people just ignore the viewType parameter. According to the view type, you'll need to inflate the correct layout resource and create your view holder accordingly. The RecyclerView will handle recycling different view types in a way which avoids clashing of different view types.
If you're planning on using a default LayoutManager, such as LinearLayoutManager
, you should be good to go. If you're planning on making your own LayoutManager implementation, you'll need to work a bit harder. The only API you really have to work with is findViewByPosition(int position)
which gives a given view at a certain position. Since you'll probably want to lay it out differently depending on what type this view is, you have a few options:
Usually when using the ViewHolder pattern, you set the view's tag with the view holder. You could use this during runtime in the layout manager to find out what type the view is by adding a field in the view holder which expresses this.
Since you'll need a function which determines which position correlates to which view type, you might as well make this method globally accessible somehow (maybe a singleton class which manages the data?), and then you can simply query the same method according to the position.
Here's a code sample:
// in this sample, I use an object array to simulate the data of the list.
// I assume that if the object is a String, it means I should display a header with a basic title.
// If not, I assume it's a custom model object I created which I will use to bind my normal rows.
private Object[] myData;
public static final int ITEM_TYPE_NORMAL = 0;
public static final int ITEM_TYPE_HEADER = 1;
public class MyAdapter extends Adapter<ViewHolder> {
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == ITEM_TYPE_NORMAL) {
View normalView = LayoutInflater.from(getContext()).inflate(R.layout.my_normal_row, null);
return new MyNormalViewHolder(normalView); // view holder for normal items
} else if (viewType == ITEM_TYPE_HEADER) {
View headerRow = LayoutInflater.from(getContext()).inflate(R.layout.my_header_row, null);
return new MyHeaderViewHolder(headerRow); // view holder for header items
}
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final int itemType = getItemViewType(position);
if (itemType == ITEM_TYPE_NORMAL) {
((MyNormalViewHolder)holder).bindData((MyModel)myData[position]);
} else if (itemType == ITEM_TYPE_HEADER) {
((MyHeaderViewHolder)holder).setHeaderText((String)myData[position]);
}
}
@Override
public int getItemViewType(int position) {
if (myData[position] instanceof String) {
return ITEM_TYPE_HEADER;
} else {
return ITEM_TYPE_NORMAL;
}
}
@Override
public int getItemCount() {
return myData.length;
}
}
Here's a sample of how these view holders should look like:
public MyHeaderViewHolder extends ViewHolder {
private TextView headerLabel;
public MyHeaderViewHolder(View view) {
super(view);
headerLabel = (TextView)view.findViewById(R.id.headerLabel);
}
public void setHeaderText(String text) {
headerLabel.setText(text);
}
}
public MyNormalViewHolder extends ViewHolder {
private TextView titleLabel;
private TextView descriptionLabel;
public MyNormalViewHolder(View view) {
super(view);
titleLabel = (TextView)view.findViewById(R.id.titleLabel);
descriptionLabel = (TextView)view.findViewById(R.id.descriptionLabel);
}
public void bindData(MyModel model) {
titleLabel.setText(model.getTitle());
descriptionLabel.setText(model.getDescription());
}
}
Of course, this sample assumes you've constructed your data source (myData) in a way that makes it easy to implement an adapter in this way. As an example, I'll show you how I'd construct a data source which shows a list of names, and a header for every time the 1st letter of the name changes (assume the list is alphabetized) - similar to how a contacts list would look like:
// Assume names & descriptions are non-null and have the same length.
// Assume names are alphabetized
private void processDataSource(String[] names, String[] descriptions) {
String nextFirstLetter = "";
String currentFirstLetter;
List<Object> data = new ArrayList<Object>();
for (int i = 0; i < names.length; i++) {
currentFirstLetter = names[i].substring(0, 1); // get the 1st letter of the name
// if the first letter of this name is different from the last one, add a header row
if (!currentFirstLetter.equals(nextFirstLetter)) {
nextFirstLetter = currentFirstLetter;
data.add(nextFirstLetter);
}
data.add(new MyModel(names[i], descriptions[i]));
}
myData = data.toArray();
}
This example comes to solve a fairly specific issue, but I hope this gives you a good overview on how to handle different row types in a recycler, and allows you make the necessary adaptations in your own code to fit your needs.
This should be more efficient both for the application and also for the developer.
Add the following class to your web project:
/// <summary>
/// This holds all of the session variables for the site.
/// </summary>
public class SessionCentralized
{
protected internal static void Save<T>(string sessionName, T value)
{
HttpContext.Current.Session[sessionName] = value;
}
protected internal static T Get<T>(string sessionName)
{
return (T)HttpContext.Current.Session[sessionName];
}
public static int? WhatEverSessionVariableYouWantToHold
{
get
{
return Get<int?>(nameof(WhatEverSessionVariableYouWantToHold));
}
set
{
Save(nameof(WhatEverSessionVariableYouWantToHold), value);
}
}
}
Here is the implementation:
SessionCentralized.WhatEverSessionVariableYouWantToHold = id;
In Jackson 2.4, you can convert as follows:
MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);
where jsonObjectMapper
is a Jackson ObjectMapper
.
In older versions of Jackson, it would be
MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);
Here is the script I use:
@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION
mode con:cols=210 lines=50
ECHO Starting 1-way backup of MEDIA(M:) to BACKUP(G:)...
robocopy.exe M:\ G:\ *.* /E /PURGE /SEC /NP /NJH /NJS /XD "$RECYCLE.BIN" "System Volume Information" /TEE /R:5 /COPYALL /LOG:from_M_to_G.log
ECHO Finished with backup.
pause
A file ending in .o is an object file. The compiler creates an object file for each source file, before linking them together, into the final executable.
if you are using eclipse and modifying server.xml doesn't work for you then try following article.. they have steps to modify port if you are using IDE like eclipse.
Here's a possible partial answer, because it only allows selecting the test scripts, not individual tests within those scripts.
And it also limited by my using legacy compatibility mode vs unittest
scripts, so not guaranteeing it would work with native pytest.
Here goes:
subset_tests_directory
.ln -s tests_directory/foo.py
ln -s tests_directory/bar.py
be careful about imports which implicitly assume files are in test_directory
. I had to fix several of those by running python foo.py
, from within subset_tests_directory
and correcting as needed.
Once the test scripts execute correctly, just cd subset_tests_directory
and pytest
there. Pytest will only pick up the scripts it sees.
Another possibility is symlinking within your current test directory, say as ln -s foo.py subset_foo.py
then pytest subset*.py
. That would avoid needing to adjust your imports, but it would clutter things up until you removed the symlinks. Worked for me as well.
Using the -I
(that's a capital i) option on the file
command seems to show the file encoding.
file -I {filename}
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
The context object allows you to manipulate the canvas; you can draw rectangles for example and a lot more.
If you want to get the width and height, you can just use the standard HTML attributes width
and height
:
var canvas = document.getElementById( 'yourCanvasID' );
var ctx = canvas.getContext( '2d' );
alert( canvas.width );
alert( canvas.height );
If you are using a JetBrains IDE (anything IntelliJ based), you can recover even your uncommited changes via their "Local History" feature.
Right-click on your top-level directory in your file tree, find "Local History" in the context menu, and choose "Show History". This will open up a view where your recent edits can be found, and once you have found the revision you want to go back to, right click on it and click "Revert".
The class definition defines the API for your class. In other words, it is a blueprint that defines the contract that exists between the class and its clients--all the other code that uses this class. The contract indicates which methods are available, how to call them, and what to expect in return.
But the class definition is a spec. Until you have an actual object of this class, the contract is just "a piece of paper." This is where the constructor comes in.
A constructor is the means of creating an instance of your class by creating an object in memory and returning a reference to it. Something that should happen in the constructor is that the object is in a proper initial state for the subsequent operations on the object to make sense.
This object returned from the constructor will now honor the contract specified in the class definition, and you can use this object to do real work.
Think of it this way. If you ever look at the Porsche website, you will see what it can do--the horsepower, the torque, etc. But it isn't fun until you have an actual Porsche to drive.
Hope that helps.
To exit you application you can use the following:
getActivity().finish();
Process.killProcess(Process.myPid());
System.exit(1);
Also to stop the services too call the following method:
private void stopServices() {
final ActivityManager activityManager = SystemServices.getActivityManager(context);
final List<ActivityManager.RunningServiceInfo> runningServices = activityManager.getRunningServices(Integer.MAX_VALUE);
final int pid = Process.myPid();
for (ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
if (serviceInfo.pid == pid && !SenderService.class.getName().equals(serviceInfo.service.getClassName())) {
try {
final Intent intent = new Intent();
intent.setComponent(serviceInfo.service);
context.stopService(intent);
} catch (SecurityException e) {
// handle exception
}
}
}
}
Mac OSX Users
If your phone and laptop are on the same wifi:
Go to System Preferences > Networ
k to obtain your IP address
On your mobile browser, type [your IP address]:3000
to access localhost:3000
e.g. 12.45.123.456:3000
Here's a Swift version:
func durationsBySecond(seconds s: Int) -> (days:Int,hours:Int,minutes:Int,seconds:Int) {
return (s / (24 * 3600),(s % (24 * 3600)) / 3600, s % 3600 / 60, s % 60)
}
Can be used like this:
let (d,h,m,s) = durationsBySecond(seconds: duration)
println("time left: \(d) days \(h) hours \(m) minutes \(s) seconds")
via Reflection
var property = object.GetType().GetProperty("YourProperty")
property.SetValue(object,some_value,null);
Similar is for methods
I encountered this error working in Talend. I was able to store S3 CSV files created from Redshift without a problem. The error occurred when I was trying to load the same S3 CSV files into an Amazon RDS MySQL database. I tried the default timestamp Talend timestamp formats but they were throwing exception:unparseable date when loading into MySQL.
This from the accepted answer helped me solve this problem:
By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern
The key to my solution was changing the Talend schema. Talend set the timestamp field to "date" so I changed it to "timestamp" then I inserted "yyyy-MM-dd HH:mm:ss z" into the format string column view a screenshot here talend schema
I had other issues with 12 hour and 24 hour timestamp translations until I added the "z" at the end of the timestamp string.
After search a lot, it was my best shot:
If you have a lot of data and needs a compact and elegant script, try it: SSMS Tools Pack
It generates a union all select statements to insert items into target tables and handle transactions pretty well.
I just had this issue because I used 0.0.0.0
as my server, changed it to localhost
and it works.
RabbitMQ is a solid, general-purpose message broker that supports several protocols such as AMQP, MQTT, STOMP, etc. It can handle high throughput. A common use case for RabbitMQ is to handle background jobs or long-running task, such as file scanning, image scaling or PDF conversion. RabbitMQ is also used between microservices, where it serves as a means of communicating between applications, avoiding bottlenecks passing messages.
Kafka is a message bus optimized for high-throughput ingestion data streams and replay. Use Kafka when you have the need to move a large amount of data, process data in real-time or analyze data over a time period. In other words, where data need to be collected, stored, and handled. An example is when you want to track user activity on a webshop and generate suggested items to buy. Another example is data analysis for tracking, ingestion, logging or security.
Kafka can be seen as a durable message broker where applications can process and re-process streamed data on disk. Kafka has a very simple routing approach. RabbitMQ has better options if you need to route your messages in complex ways to your consumers. Use Kafka if you need to support batch consumers that could be offline or consumers that want messages at low latency.
In order to understand how to read data from Kafka, we first need to understand its consumers and consumer groups. Partitions allow you to parallelize a topic by splitting the data across multiple nodes. Each record in a partition is assigned and identified by its unique offset. This offset points to the record in a partition. In the latest version of Kafka, Kafka maintains a numerical offset for each record in a partition. A consumer in Kafka can either automatically commit offsets periodically, or it can choose to control this committed position manually. RabbitMQ will keep all states about consumed/acknowledged/unacknowledged messages. I find Kafka more complex to understand than the case of RabbitMQ, where the message is simply removed from the queue once it's acked.
RabbitMQ's queues are fastest when they're empty, while Kafka retains large amounts of data with very little overhead - Kafka is designed for holding and distributing large volumes of messages. (If you plan to have very long queues in RabbitMQ you could have a look at lazy queues.)
Kafka is built from the ground up with horizontal scaling (scale by adding more machines) in mind, while RabbitMQ is mostly designed for vertical scaling (scale by adding more power).
RabbitMQ has a built-in user-friendly interface that lets you monitor and handle your RabbitMQ server from a web browser. Among other things, queues, connections, channels, exchanges, users and user permissions can be handled - created, deleted and listed in the browser and you can monitor message rates and send/receive messages manually. Kafka has a number of open-source tools, and also some commercial once, offering the administration and monitoring functionalities. I would say that it's easier/gets faster to get a good understanding of RabbitMQ.
In general, if you want a simple/traditional pub-sub message broker, the obvious choice is RabbitMQ, as it will most probably scale more than you will ever need it to scale. I would have chosen RabbitMQ if my requirements were simple enough to deal with system communication through channels/queues, and where retention and streaming is not a requirement.
There are two main situations where I would choose RabbitMQ; For long-running tasks, when I need to run reliable background jobs. And for communication and integration within, and between applications, i.e as middleman between microservices; where a system simply needs to notify another part of the system to start to work on a task, like ordering handling in a webshop (order placed, update order status, send order, payment, etc.).
In general, if you want a framework for storing, reading (re-reading), and analyzing streaming data, use Apache Kafka. It’s ideal for systems that are audited or those that need to store messages permanently. These can also be broken down into two main use cases for analyzing data (tracking, ingestion, logging, security etc.) or real-time processing.
More reading, use cases and some comparison data can be found here: https://www.cloudamqp.com/blog/2019-12-12-when-to-use-rabbitmq-or-apache-kafka.html
Also recommending the industry paper: "Kafka versus RabbitMQ: A comparative study of two industry reference publish/subscribe implementations": http://dl.acm.org/citation.cfm?id=3093908
I do work at a company providing both Apache Kafka and RabbitMQ as a Service.
From Android 11 (API level 30) you can take screen shot with the accessibility service:
takeScreenshot - Takes a screenshot of the specified display and returns it via an AccessibilityService.ScreenshotResult.
use join()
, don't rely on the ,
for formatting, and also print
automatically puts the cursor on a newline every time, so no need of adding another '\n'
in your print
.
In [24]: for x in board:
print " ".join(map(str,x))
....:
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 3 2 1 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
You use css to change the opacity. To cope with IE you'd need something like:
.opaque {
opacity : 0.3;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";
filter: alpha(opacity=30);
}
But the only problem with this is that it means anything inside the container will also be 0.3 opacity. Thus you'll have to change your HTML to have another container, not inside the transparent one, that holds your content.
Otherwise the png technique, would work. Except you'd need a fix for IE6, which in itself could cause problems.
There's also some good discussion about this here: Is this the proper use of a mutex?
You need to create own PCH file
Add New file -> Other-> PCH file
Then add the path of this PCH file to your build setting->prefix header->path
($(SRCROOT)/filename.pch)
The best way to answer your question is to see it in action.
<a id="test" onclick="alert('test')"> test </a> ?
In the js
var test = document.getElementById('test');
console.log( test.onclick );
As you see in the console
, if you're using chrome it prints an anonymous function with the event object passed in, although it's a little different in IE.
function onclick(event) {
alert('test')
}
I agree with some of your points about inline event handlers. Yes they are easy to write, but i don't agree with your point about having to change code in multiple places, if you structure your code well, you shouldn't need to do this.
For inside some directory, this will be use full as it copy all contents from "folder1" to new directory "folder2" inside some directory.
$(pwd) will get path for current directory.
Notice the dot (.) after folder1 to get all contents inside folder1
cp -r $(pwd)/folder1/. $(pwd)/folder2
the solution lies in creating a new key when generating the signed apk. this worked for me without a fuss.
when you install, the warning will not come.
Not sure if this is helpful but here's an example of Handlebars template with dynamic parameters passed to an inline RadioButtons partial and the client(browser) rendering the radio buttons in the container.
For my use it's rendered with Handlebars on the server and lets the client finish it up. With it a forms tool can provide inline data within Handlebars without helpers.
Note : This example requires jQuery
{{#*inline "RadioButtons"}}
{{name}} Buttons<hr>
<div id="key-{{{name}}}"></div>
<script>
{{{buttons}}}.map((o)=>{
$("#key-{{name}}").append($(''
+'<button class="checkbox">'
+'<input name="{{{name}}}" type="radio" value="'+o.value+'" />'+o.text
+'</button>'
));
});
// A little test script
$("#key-{{{name}}} .checkbox").on("click",function(){
alert($("input",this).val());
});
</script>
{{/inline}}
{{>RadioButtons name="Radio" buttons='[
{value:1,text:"One"},
{value:2,text:"Two"},
{value:3,text:"Three"}]'
}}
file_get_contents()
is not fetching the data from url,then i tried curl
and it's working fine.
Depending on which OS you're using, if you are flexible, then CHOICE
can be used to wait on almost any key EXCEPT
enter
If you are really referring to what Microsoft insists on calling "Command Prompt" which is simply an MS-DOS emulator, then perhaps TIMEOUT
may suit your purpose (timeout /t -1
waits on any key, not just ENTER
) and of course CHOICE
is available again in recent WIN editions.
And a warning on SET /P
- whereas set /p DUMMY=Hit ENTER to continue...
will work,
set "dummy="
set /p DUMMY=Hit ENTER to continue...
if defined dummy (echo not just ENTER was pressed) else (echo just ENTER was pressed)
will detect whether just ENTER or something else, ending in ENTER was keyed in.
First of all, be sure that you have downloaded it or not. Open up your terminal application, and enter $ gcc
if you have not installed it you will get an alert. You can verify that you have installed it by
$ xcode-select -p
/Library/Developer/CommandLineTools
And to be sure then enter $ gcc --version
You can read more about the process here: Xcode command line tools for Mavericks
Does it work if you escape the quoted commas with \ ?
Name, Age, Sex
"Cantor\, Georg", 163,M
Most delimited formats require that their delimiter be escaped in order to properly parse.
A rough Java example:
import java.util.Iterator;
public class CsvTest {
public static void main(String[] args) {
String[] lines = { "Name, Age, Sex", "\"Cantor, Georg\", 163, M" };
StringBuilder result = new StringBuilder();
for (String head : iterator(lines[0])) {
result.append(String.format("<tr>%s</tr>\n", head));
}
for (int i=1; i < lines.length; i++) {
for (String row : iterator(lines[i])) {
result.append(String.format("<td>%s</td>\n", row));
}
}
System.out.println(String.format("<table>\n%s</table>", result.toString()));
}
public static Iterable<String> iterator(final String line) {
return new Iterable<String>() {
public Iterator<String> iterator() {
return new Iterator<String>() {
private int position = 0;
public boolean hasNext() {
return position < line.length();
}
public String next() {
boolean inquote = false;
StringBuilder buffer = new StringBuilder();
for (; position < line.length(); position++) {
char c = line.charAt(position);
if (c == '"') {
inquote = !inquote;
}
if (c == ',' && !inquote) {
position++;
break;
} else {
buffer.append(c);
}
}
return buffer.toString().trim();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}
You can make an Embedded class
, which contains your two keys, and then have a reference to that class as EmbeddedId
in your Entity
.
You would need the @EmbeddedId
and @Embeddable
annotations.
@Entity
public class YourEntity {
@EmbeddedId
private MyKey myKey;
@Column(name = "ColumnA")
private String columnA;
/** Your getters and setters **/
}
@Embeddable
public class MyKey implements Serializable {
@Column(name = "Id", nullable = false)
private int id;
@Column(name = "Version", nullable = false)
private int version;
/** getters and setters **/
}
Another way to achieve this task is to use @IdClass
annotation, and place both your id
in that IdClass
. Now you can use normal @Id
annotation on both the attributes
@Entity
@IdClass(MyKey.class)
public class YourEntity {
@Id
private int id;
@Id
private int version;
}
public class MyKey implements Serializable {
private int id;
private int version;
}
I got it to work in phpAdmin , but only when I removed the "Number of records " phrase.
In my version of phpAdmin I could see the box for changing the delimiters.
Also to see the procedure in the database i went to the phpAdmin home, then information_schema database and then the routines table.
Use this:
android:scrollbarAlwaysDrawHorizontalTrack="true"
Example:
<Gallery android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbarAlwaysDrawHorizontalTrack="true" />
What does the UDF EntityHasProfile() do?
Typically you could do something like this with a LEFT JOIN:
SELECT EntityId, EntityName, CASE WHEN EntityProfileIs IS NULL THEN 0 ELSE 1 END AS Has Profile
FROM Entities
LEFT JOIN EntityProfiles
ON EntityProfiles.EntityId = Entities.EntityId
This should eliminate a need for a costly scalar UDF call - in my experience, scalar UDFs should be a last resort for most database design problems in SQL Server - they are simply not good performers.
Mine were located here on Ubuntu 18.04 when I installed JavaFX using apt install openjfx
(as noted already by @jewelsea above)
/usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
If someone like me want to do it with query builder in Laravel 5.2.23 it can be done like ->
$searchResultQuery = Users::query();
$searchResultQuery->where('status_message', '<>', '', 'and'); // is not null
$searchResultQuery->where('is_deleted', 'IS NULL', null, 'and'); // is null
Or with scope in model :
public function scopeNotNullOnly($query){
return $query->where('status_message', '<>', '');
}
First of all open applicationhost.config file in visual studio.
address>>C:\Users\Your User Name\Documents\IISExpress\config\applicationhost.config
Then find this codes:
<site name="Your Site_Name" id="24">
<application path="/" applicationPool="Clr4IntegratedAppPool"
<virtualDirectory path="/" physicalPath="C:\Users\Your User Name\Documents\Visual Studio 2013\Projects\Your Site Name" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:Port_Number:*" />
</bindings>
</site>
*)Port_Number:While your site running in IIS express on your computer, port number will visible in address bar of your browser like this: localhost:port_number/... When edit this file save it.
In the Second step you must run cmd as administrator and type this code:
netsh http add urlacl url=http://*:port_Number/ user=everyone
and press enter
In Third step you must Enable port on firewall
Go to the “Control Panel\System and Security\Windows Firewall”
Click “Advanced settings”
Select “Inbound Rules”
Click on “New Rule …” button
Select “Port”, click “Next”
Fill your IIS Express listening port number, click “Next”
Select “Allow the connection”, click “Next”
Check where you would like allow connection to IIS Express (Domain,Private, Public), click “Next”
Fill rule name (e.g “IIS Express), click “Finish”
I hopeful this answer be useful for you
Update for Visual Studio 2015 in this link: https://johan.driessen.se/posts/Accessing-an-IIS-Express-site-from-a-remote-computer
It is so simple. You do it like this.
print(type(variable_name))
We call it the "ant" menu. Guess it was a good time to change since everyone had just gotten used to the hamburger.
git branch copyOfMyBranch MyBranch
This avoids the potentially time-consuming and unnecessary act of checking out a branch. Recall that a checkout modifies the "working tree", which could take a long time if it is large or contains large files (images or videos, for example).
I was not even concentrating, here is how to do it
$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
New-Item -ItemType directory -Path $TARGETDIR
}
int i = 65;
char c = Convert.ToChar(i);
What do you mean by converting?
(int) $float
or intval($float)
floor($float)
(down) or ceil($float)
(up)round($float)
- has additional modes, see PHP_ROUND_HALF_...
constants*: casting has some chance, that float values cannot be represented in int (too big, or too small), f.ex. in your case.
PHP_INT_MAX
: The largest integer supported in this build of PHP. Usually int(2147483647).
But, you could use the BCMath, or the GMP extensions for handling these large numbers. (Both are boundled, you only need to enable these extensions)
You mean Bloodshed's Dev-C++? It's a nice visual IDE for C++ which uses MinGW's gcc for Windows as the back-the-scenes compiler. The project's been abandoned for a while (in my opinion, using Delphi to develop a C++ IDE is a very stupid thing to do to draw developers' attention), however there's nothing that stops you from using it and updating the version of MinGW's gcc it uses to the latest one - besides it's GPL-licensed.
val parser = new scopt.OptionParser[Config]("scopt") {
head("scopt", "3.x")
opt[Int]('f', "foo") action { (x, c) =>
c.copy(foo = x) } text("foo is an integer property")
opt[File]('o', "out") required() valueName("<file>") action { (x, c) =>
c.copy(out = x) } text("out is a required file property")
opt[(String, Int)]("max") action { case ((k, v), c) =>
c.copy(libName = k, maxCount = v) } validate { x =>
if (x._2 > 0) success
else failure("Value <max> must be >0")
} keyValueName("<libname>", "<max>") text("maximum count for <libname>")
opt[Unit]("verbose") action { (_, c) =>
c.copy(verbose = true) } text("verbose is a flag")
note("some notes.\n")
help("help") text("prints this usage text")
arg[File]("<file>...") unbounded() optional() action { (x, c) =>
c.copy(files = c.files :+ x) } text("optional unbounded args")
cmd("update") action { (_, c) =>
c.copy(mode = "update") } text("update is a command.") children(
opt[Unit]("not-keepalive") abbr("nk") action { (_, c) =>
c.copy(keepalive = false) } text("disable keepalive"),
opt[Boolean]("xyz") action { (x, c) =>
c.copy(xyz = x) } text("xyz is a boolean property")
)
}
// parser.parse returns Option[C]
parser.parse(args, Config()) map { config =>
// do stuff
} getOrElse {
// arguments are bad, usage message will have been displayed
}
The above generates the following usage text:
scopt 3.x
Usage: scopt [update] [options] [<file>...]
-f <value> | --foo <value>
foo is an integer property
-o <file> | --out <file>
out is a required file property
--max:<libname>=<max>
maximum count for <libname>
--verbose
verbose is a flag
some notes.
--help
prints this usage text
<file>...
optional unbounded args
Command: update
update is a command.
-nk | --not-keepalive
disable keepalive
--xyz <value>
xyz is a boolean property
This is what I currently use. Clean usage without too much baggage. (Disclaimer: I now maintain this project)
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
I've simply added
jQuery.browser = {
msie: false,
version: 0
};
after jquery script, because I don't care about IE anymore.
First to set group_concat_max_len
, otherwise it will not give you all the result:
SET GLOBAL group_concat_max_len = 999999;
SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 group by parent_id;
This will return the matching word or an error if no match is found. For this example I used the following.
List of words to search for: G1:G7
Cell to search in: A1
=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))
Enter as an array formula by pressing Ctrl+Shift+Enter.
This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX()
function, throwing an error.
To return the row number of a matching word, you can use the following:
=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))
This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1
if no match is found.
It sounds like you're trying to SELECT
a column that doesn't exist.
Perhaps you're trying to ORDER BY
a column that doesn't exist?
Any typos in your SQL statement?
The >>
will append the log file, rather than overwriting it each time. The 2>&1
will also send errors to your log file.
cmd /c YourProgram.exe >> log.txt 2>&1
Make sure you click the properties on the file and set it to "copy always" or it will not be in the Debug\ folder with your happy lil dll's to configure where it needs to be and add more cowbell
To answer your question, you can explore the contents of the model's output by saving the model as a variable and clicking on it in the environment window. You can then click around to see what it contains and what is stored where.
Another way is to type yourmodelname$
and select the components of the model one by one to see what each contains. When you get to yourmodelname$coefficients
, you will see all of beta-, p, and t- values you desire.
If your backend uses a secure connection ant you get using NSURLSession
CFNetwork SSLHandshake failed (-9801)
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9801)
you need to check your server configuration especially to get ATS version and SSL certificate Info:
Instead of just Allowing Insecure Connection by setting NSExceptionAllowsInsecureHTTPLoads = YES
, instead you need to Allow Lowered Security in case your server do not meet the min requirement (v1.2) for ATS (or better to fix server side).
Allowing Lowered Security to a Single Server
<key>NSExceptionDomains</key>
<dict>
<key>api.yourDomaine.com</key>
<dict>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
use openssl client to investigate certificate and get your server configuration using openssl client :
openssl s_client -connect api.yourDomaine.com:port //(you may need to specify port or to try with https://... or www.)
..find at the end
SSL-Session:
Protocol : TLSv1
Cipher : AES256-SHA
Session-ID: //
Session-ID-ctx:
Master-Key: //
Key-Arg : None
Start Time: 1449693038
Timeout : 300 (sec)
Verify return code: 0 (ok)
App Transport Security (ATS) require Transport Layer Security (TLS) protocol version 1.2.
Requirements for Connecting Using ATS:
The requirements for a web service connection to use App Transport Security (ATS) involve the server, connection ciphers, and certificates, as follows:
Certificates must be signed with one of the following types of keys:
Secure Hash Algorithm 2 (SHA-2) key with a digest length of at least 256 (that is, SHA-256 or greater)
Elliptic-Curve Cryptography (ECC) key with a size of at least 256 bits
Rivest-Shamir-Adleman (RSA) key with a length of at least 2048 bits An invalid certificate results in a hard failure and no connection.
The following connection ciphers support forward secrecy (FS) and work with ATS:
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
Update: it turns out that openssl only provide the minimal protocol version Protocol : TLSv1 links
If you have applied border and/or fill on a cell, you need to clear both to go back to the default borders.
You may apply 'None' as the border option and expect the default borders to show, but it will not when the cell fill is white. It's not immediately obvious that it has a white fill, as unfilled cells are also white.
In this case, apply a 'No Fill' on the cells, and you will get the default borders back.
That's it. No messy format painting, no 'Clear Formats', none of those destructive methods. Easy, quick and painless.
Atomic collections are accessible by $
Recursive collections are not. Rather the [[ ]]
is used
Browse[1]> is.atomic(list())
[1] FALSE
Browse[1]> is.atomic(data.frame())
[1] FALSE
Browse[1]> is.atomic(class(list(foo="bar")))
[1] TRUE
Browse[1]> is.atomic(c(" lang "))
[1] TRUE
R can be funny sometimes
a = list(1,2,3)
b = data.frame(a)
d = rbind("?",c(b))
e = exp(1)
f = list(d)
print(data.frame(c(list(f,e))))
X1 X2 X3 X2.71828182845905
1 ? ? ? 2.718282
2 1 2 3 2.718282
The YourKit Java profiler is an excellent commercial solution. You can find further information in the docs on CPU profiling and memory profiling.
I moved my Database First DataModel to a different project midway through development. Poor planning (or lack there of) on my part.
Initially I had a solution with one project. Then I added another project to the solution and recreated my Database First DataModel from the Sql Server Dataase.
To fix the problem - MetadataException when using Entity Framework Entity Connection. I copied my the ConnectionString from the new Project Web.Config to the original project Web.Config. However, this occurred after I updated my all the references in the original project to new DataModel project.
isn't the problem the following line is incorrect as the statement for background-repeat
isn't closed before the next statement for display
...
background-repeat:no-repeatdisplay: compact;
Shouldn't this be
background-repeat:no-repeat;
display: compact;
adding or removing quotes (in my experience) makes no difference if the URL is correct. Is the path to the image correct? If you give a relative path to a resource in a CSS it's relative to the CSS file, not the file including the CSS.
Saving to Hive is just a matter of using write()
method of your SQLContext:
df.write.saveAsTable(tableName)
From Spark 2.2: use DataSet instead DataFrame.
You can't style a disabled checkbox directly because it's controlled by the browser / OS.
However you can be clever and replace the checkbox with a label that simulates a checkbox using pure CSS. You need to have an adjacent label that you can use to style a new "pseudo checkbox". Essentially you're completely redrawing the thing but it gives you complete control over how it looks in any state.
I've thrown up a basic example so that you can see it in action: http://jsfiddle.net/JohnSReid/pr9Lx5th/3/
Here's the sample:
input[type="checkbox"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
label:before {_x000D_
background: linear-gradient(to bottom, #fff 0px, #e6e6e6 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
border: 1px solid #035f8f;_x000D_
height: 36px;_x000D_
width: 36px;_x000D_
display: block;_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
content: '';_x000D_
background: linear-gradient(to bottom, #e6e6e6 0px, #fff 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
border-color: #3d9000;_x000D_
color: #96be0a;_x000D_
font-size: 38px;_x000D_
line-height: 35px;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:disabled + label:before {_x000D_
border-color: #eee;_x000D_
color: #ccc;_x000D_
background: linear-gradient(to top, #e6e6e6 0px, #fff 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
content: '?';_x000D_
}
_x000D_
<div><input id="cb1" type="checkbox" disabled checked /><label for="cb1"></label></div>_x000D_
<div><input id="cb2" type="checkbox" disabled /><label for="cb2"></label></div>_x000D_
<div><input id="cb3" type="checkbox" checked /><label for="cb3"></label></div>_x000D_
<div><input id="cb4" type="checkbox" /><label for="cb4"></label></div>
_x000D_
Depending on your level of browser compatibility and accessibility, some additional tweaks will need to be made.
Apache Http Client APIs are very commonly used for calling HTTP Rest services.
Here is one of example of consuming HTTP GET call.
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
public class CallHTTPGetService {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpUriRequest httpUriRequest = new HttpGet("URL");
HttpResponse response = client.execute(httpUriRequest);
System.out.println(response);
}
}
Use following maven dependency if using Maven project.
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.1</version>
</dependency>
It's something that "appears to the rest of the system to occur instantaneously", and falls under categorisation of Linearizability in computing processes. To quote that linked article further:
Atomicity is a guarantee of isolation from concurrent processes. Additionally, atomic operations commonly have a succeed-or-fail definition — they either successfully change the state of the system, or have no apparent effect.
So, for instance, in the context of a database system, one can have 'atomic commits', meaning that you can push a changeset of updates to a relational database and those changes will either all be submitted, or none of them at all in the event of failure, in this way data does not become corrupt, and consequential of locks and/or queues, the next operation will be a different write or a read, but only after the fact. In the context of variables and threading this is much the same, applied to memory.
Your quote highlights that this need not be expected behaviour in all instances.
ulimit -s unlimited
lets the stack grow unlimited.
This may prevent your program from crashing if you write programs by recursion, especially if your programs are not tail recursive (compilers can "optimize" those), and the depth of recursion is large.
I see what you are trying to ask and I think this is the simplest answer to what you are looking for, given you might not know how many key pairs your are being sent.
Simple Key Pair JSON structure
var data = {
'XXXXXX' : '100.0',
'YYYYYYY' : '200.0',
'ZZZZZZZ' : '500.0',
}
Usage JavaScript code to access the key pairs
for (var key in data)
{ if (!data.hasOwnProperty(key))
{ continue; }
console.log(key + ' -> ' + data[key]);
};
Console output should look like this
XXXXXX -> 100.0
YYYYYYY -> 200.0
ZZZZZZZ -> 500.0
Here is a JSFiddle to show how it works.
I don't see any answer with nmcli
yet which is a command-line tool for controlling NetworkManager.
So here you go :)
wolf@linux:~$ nmcli device
DEVICE TYPE STATE CONNECTION
eth1 ethernet unavailable --
eth0 ethernet unmanaged --
lo loopback unmanaged --
wolf@linux:~$
If you want to get the information from specific network interface (let say lo
for this example)
wolf@linux:~$ nmcli device show lo
GENERAL.DEVICE: lo
GENERAL.TYPE: loopback
GENERAL.HWADDR: 00:00:00:00:00:00
GENERAL.MTU: 65536
GENERAL.STATE: 10 (unmanaged)
GENERAL.CONNECTION: --
GENERAL.CON-PATH: --
IP4.ADDRESS[1]: 127.0.0.1/8
IP4.GATEWAY: --
IP4.ROUTE[1]: dst = 127.0.0.0/8, nh = 0.0.0.0,>
IP4.ROUTE[2]: dst = 127.0.0.1/32, nh = 0.0.0.0>
IP6.ADDRESS[1]: ::1/128
IP6.GATEWAY: --
IP6.ROUTE[1]: dst = ::1/128, nh = ::, mt = 256
IP6.ROUTE[2]: dst = ::1/128, nh = ::, mt = 0, >
wolf@linux:~$
But since you just want to get the IP address, just send the output to grep
, cut
or awk
.
Let's do it step by step. (Not sure what's wrong, the code sample format just didn't work for these 3 example.)
Get the IPv4 line
wolf@linux:~$ nmcli device show lo | grep 4.A IP4.ADDRESS[1]: 127.0.0.1/8 wolf@linux:~$
Use awk
to get the IP
wolf@linux:~$ nmcli device show lo | awk '/4.A/ {print $2}' 127.0.0.1/8 wolf@linux:~$
Use cut
to remove the CIDR notation (/8)
wolf@linux:~$ nmcli device show lo | awk '/4.A/ {print $2}' | cut -d / -f1 127.0.0.1 wolf@linux:~$
There your answer.
Please take note that there are tons of ways to do it using the tools that I demonstrated just now.
Let's recap the commands that I used.
nmcli device show lo | grep 4.A
nmcli device show lo | awk '/4.A/ {print $2}'
nmcli device show lo | awk '/4.A/ {print $2}' | cut -d / -f1
Sample output for these 3 commands
Command 1 output
IP4.ADDRESS[1]: 127.0.0.1/8
Command 2 output
127.0.0.1/8
Command 3 output
127.0.0.1
An easy way without using collections
public void findHighestNoInArray() {
int[] a = {1,2,6,8,9};
int large = a[0];
for(int num : a) {
if(large < num) {
large = num;
}
}
System.out.println("Large number is "+large+"");
}
Static memory allocation. Memory allocated will be in stack.
int a[10];
Dynamic memory allocation. Memory allocated will be in heap.
int *a = malloc(sizeof(int) * 10);
and the latter should be freed since there is no Garbage Collector(GC) in C.
free(a);
Just for completeness - in SQL 2008 you would use the plus +
operator to perform string concatenation.
Take a look at the MSDN reference with sample code. Starting with SQL 2012, you may wish to use the new CONCAT function.
You can use WhereNotIn
in the following way:
$category=DB::table('category')
->whereNotIn('category_id',[14 ,15])
->get();`enter code here`
"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."
http://www.sightspecific.com/~mosh/www_faq/multrec.html
For a quick fix to your problem, change your ;
to a comma ,
and eliminate the spaces between email addresses
<a href='mailto:[email protected],[email protected]'>Email Us</a>
Change the code where you load the partial view to:
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable
jQuery might be missing.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
I'm using a kendo grid and therefore can't change the implementation to a getter method but I want to test around this (mocking the grid) and not test the grid itself. I was using a spy object but this doesn't support property mocking so I do this:
this.$scope.ticketsGrid = {
showColumn: jasmine.createSpy('showColumn'),
hideColumn: jasmine.createSpy('hideColumn'),
select: jasmine.createSpy('select'),
dataItem: jasmine.createSpy('dataItem'),
_data: []
}
It's a bit long winded but it works a treat
put ur js code under the form html or use $(document).ready(function(){}) and try this.
$('#inline_content input[type="radio"]').click(function(){
if($(this).val() == "walk_in"){
alert('ok');
}
});
Try BufferedReader.readLine()
instead of all this complication. It will recognize all possible line terminators.
In my case, I wanted the opposite. I wanted to strip off the last 2 characters in my string. This was pretty simple:
String myString = someString.substring(0, someString.length() - 2);
[What you need for interviews] A Node class is the sufficient data structure to represent a binary tree.
(While other answers are mostly correct, they are not required for a binary tree: no need to extend object class, no need to be a BST, no need to import deque).
class Node:
def __init__(self, value = None):
self.left = None
self.right = None
self.value = value
Here is an example of a tree:
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n1.left = n2
n1.right = n3
In this example n1 is the root of the tree having n2, n3 as its children.
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.
this works well for me even though the XML structure is complex.
And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.
The main problem might not come from the attributes.
What about trying the which
command?
If you were to run which psql
and Postgres is not installed there appears to be no output. You just get the terminal prompt ready to accept another command:
> which psql
>
But if Postgres is installed you'll get a response with the path to the location of the Postgres install:
> which psql
/opt/boxen/homebrew/bin/psql
Looking at man which
there also appears to be an option that could help you out:
-s No output, just return 0 if any of the executables are found, or
1 if none are found.
So it seems like as long as whatever scripting language you're using can can execute a terminal command you could send which -s psql
and use the return value to determine if Postgres is installed. From there you can print that result however you like.
I do have postgres installed on my machine so I run the following
> which -s psql
> echo $?
0
which tells me that the command returned 0, indicating that the Postgres executable was found on my machine.
ASP.NET Web Forms and MVC are two web frameworks developed by Microsoft - they are both good choices. Neither of the web frameworks are to be replaced by the other nor are there plans to have them 'merged' into a single framework. Continued support and development are done in parallel by Microsoft and neither will be 'going away'.
Each of these web frameworks offers advantages/disadvantages - some of which need to be considered when developing a web application. A web application can be developed using either technology - it might make development for a particular application easier selecting one technology versus the other and vice versa.
ASP.NET Web Forms:
ASP.NET MVC:
Authentication, authorization, configuration, compilation and deployment are all features that are shared between the two web frameworks.
Here is something I have:
# recursively remove empty keys (hashes), values (array), hashes and arrays from hash or array
def sanitize data
case data
when Array
data.delete_if { |value| res = sanitize(value); res.blank? }
when Hash
data.delete_if { |_, value| res = sanitize(value); res.blank? }
end
data.blank? ? nil : data
end
You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.
'use strict'
var fs = require("fs");
/***
* implementation of readFileSync
*/
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
/***
* implementation of readFile
*/
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
For better understanding run the above code and compare the results..
Use following code to check if iCheck is checked or not using single method.
$('Selector').on('ifChanged', function(event){
//Check if checkbox is checked or not
var checkboxChecked = $(this).is(':checked');
if(checkboxChecked) {
alert("checked");
}else{
alert("un-checked");
}
});
Maybe slightly off-topic, but you can recursively pretty-print all keys/fields of an object:
function _printFields(item, level) {
if ((typeof item) != "object") {
return
}
for (var index in item) {
print(" ".repeat(level * 4) + index)
if ((typeof item[index]) == "object") {
_printFields(item[index], level + 1)
}
}
}
function printFields(item) {
_printFields(item, 0)
}
Useful when all objects in a collection has the same structure.
As noticed in comments start with sent_tokenize(), because word_tokenize() works only on a single sentence. You can filter out punctuation with filter(). And if you have an unicode strings make sure that is a unicode object (not a 'str' encoded with some encoding like 'utf-8').
from nltk.tokenize import word_tokenize, sent_tokenize
text = '''It is a blue, small, and extraordinary ball. Like no other'''
tokens = [word for sent in sent_tokenize(text) for word in word_tokenize(sent)]
print filter(lambda word: word not in ',-', tokens)
Set the name in the form to check_list[]
and you will be able to access all the checkboxes as an array($_POST['check_list'][]
).
Here's a little sample as requested:
<form action="test.php" method="post">
<input type="checkbox" name="check_list[]" value="value 1">
<input type="checkbox" name="check_list[]" value="value 2">
<input type="checkbox" name="check_list[]" value="value 3">
<input type="checkbox" name="check_list[]" value="value 4">
<input type="checkbox" name="check_list[]" value="value 5">
<input type="submit" />
</form>
<?php
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
echo $check; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
?>
I don't have enough rep yet to comment or vote his solution up, but sme's answer worked extremely well for me. The only issue I ran into was that the arguments end up wrapped in single-quotes (so I have an strip them out).
I also added some example usages and HELP text. I'll included my slightly extended version here:
#!/bin/bash
# getopt example
# from: https://stackoverflow.com/questions/402377/using-getopts-in-bash-shell-script-to-get-long-and-short-command-line-options
HELP_TEXT=\
" USAGE:\n
Accepts - and -- flags, can specify options that require a value, and can be in any order. A double-hyphen (--) will stop processing options.\n\n
Accepts the following forms:\n\n
getopt-example.sh -a -b -c value-for-c some-arg\n
getopt-example.sh -c value-for-c -a -b some-arg\n
getopt-example.sh -abc some-arg\n
getopt-example.sh --along --blong --clong value-for-c -a -b -c some-arg\n
getopt-example.sh some-arg --clong value-for-c\n
getopt-example.sh
"
aflag=false
bflag=false
cargument=""
# options may be followed by one colon to indicate they have a required argument
if ! options=$(getopt -o abc:h\? -l along,blong,help,clong: -- "$@")
then
# something went wrong, getopt will put out an error message for us
exit 1
fi
set -- $options
while [ $# -gt 0 ]
do
case $1 in
-a|--along) aflag=true ;;
-b|--blong) bflag=true ;;
# for options with required arguments, an additional shift is required
-c|--clong) cargument="$2" ; shift;;
-h|--help|-\?) echo -e $HELP_TEXT; exit;;
(--) shift; break;;
(-*) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
(*) break;;
esac
shift
done
# to remove the single quotes around arguments, pipe the output into:
# | sed -e "s/^'\\|'$//g" (just leading/trailing) or | sed -e "s/'//g" (all)
echo aflag=${aflag}
echo bflag=${bflag}
echo cargument=${cargument}
while [ $# -gt 0 ]
do
echo arg=$1
shift
if [[ $aflag == true ]]; then
echo a is true
fi
done
The default value for bool is false
. See this table for a great reference on default values. The only reason it would not be false when you check it is if you initialize/set it to true.
I used the following and it worked for me. I used a boolean validation function where if any Radio Button in a Radio Group is checked, the validation function returns true and a submission is made. if returned false, no submission is made and a toast to "Select Gender" is shown:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private RadioGroup genderRadioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize Radio Group And Submit Button
genderRadioGroup=findViewById(R.id.gender_radiogroup);
AppCompatButton submit = findViewById(R.id.btnSubmit);
//Submit Radio Group using Submit Button
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Check Gender radio Group For Selected Radio Button
if(genderRadioGroup.getCheckedRadioButtonId()==-1){//No Radio Button Is Checked
Toast.makeText(getApplicationContext(), "Please Select Gender", Toast.LENGTH_LONG).show();
}else{//Radio Button Is Checked
RadioButton selectedRadioButton = findViewById(genderRadioGroup.getCheckedRadioButtonId());
gender = selectedRadioButton == null ? "" : selectedRadioButton.getText().toString().trim();
}
//Validate
if (validateInputs()) {
//code to proceed when Radio button is checked
}
}
}
//Validation - No process is initialized if no Radio button is checked
private boolean validateInputs() {
if (genderRadioGroup.getCheckedRadioButtonId()==-1) {
return false;
}
return true;
}
}
In activity_main.xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/gender"/>
<RadioGroup
android:id="@+id/gender_radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/male"/>
<RadioButton
android:id="@+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/female""/>
</RadioGroup>
<android.support.v7.widget.AppCompatButton
android:id="@+id/btnSubmit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/submit"/>
</LinearLayout>
If no gender radio button is selected, then the code to proceed will not run.
I hope this helps.
You could convert the dataframe to be a single column with stack
(this changes the shape from 5x3 to 15x1) and then take the standard deviation:
df.stack().std() # pandas default degrees of freedom is one
Alternatively, you can use values
to convert from a pandas dataframe to a numpy array before taking the standard deviation:
df.values.std(ddof=1) # numpy default degrees of freedom is zero
Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.
A couple of additional notes:
The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).
The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.
Here is another quick way, just using the key as an index into the hash table to get the value:
$hash = @{
'a' = 1;
'b' = 2;
'c' = 3
};
foreach($key in $hash.keys) {
Write-Host ("Key = " + $key + " and Value = " + $hash[$key]);
}
I'd say that the main rule of thumb is not to roll your own. Try to use something that has been thoroughly tested, e.g., SHA-1 or something along those lines.
Basically its this: You have three files: Your long running PHP script, a progress bar controlled by Javascript (@SapphireSun gives an option), and a progress script. The hard part is the Progress Script; your long script must be able to report its progress without direct communication to your progress script. This can be in the form of session id's mapped to progress meters, a database, or check of whats not finished.
The process is simple:
For me only revert --depth infinity option fixed Svn's directory remains in confict problem:
svn revert --depth infinity "<directory name>"
svn update "<directory name>"
Assuming you are trying to find if a div exists
$('div').length ? alert('div found') : alert('Div not found')
A double asterisk means to the power of. A single asterisk means multiplied by. 22 is the same as 2x2 which is why both answers came out as 4.
You can use this as well:
String uri = "tel:" + posted_by.replaceAll("[^0-9|\\+]", "");
The package @angular/router
has the Resolve
property for routes. So you can easily resolve data before rendering a route view.
See: https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html
Example from docs as of today, August 28, 2017:
class Backend {
fetchTeam(id: string) {
return 'someTeam';
}
}
@Injectable()
class TeamResolver implements Resolve<Team> {
constructor(private backend: Backend) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<any>|Promise<any>|any {
return this.backend.fetchTeam(route.params.id);
}
}
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamCmp,
resolve: {
team: TeamResolver
}
}
])
],
providers: [TeamResolver]
})
class AppModule {}
Now your route will not be activated until the data has been resolved and returned.
Accessing Resolved Data In Your Component
To access the resolved data from within your component at runtime, there are two methods. So depending on your needs, you can use either:
route.snapshot.paramMap
which returns a string, or the route.paramMap
which returns an Observable you can .subscribe()
to. Example:
// the no-observable method
this.dataYouResolved= this.route.snapshot.paramMap.get('id');
// console.debug(this.licenseNumber);
// or the observable method
this.route.paramMap
.subscribe((params: ParamMap) => {
// console.log(params);
this.dataYouResolved= params.get('id');
return params.get('dataYouResolved');
// return null
});
console.debug(this.dataYouResolved);
I hope that helps.
Need for using --dryRun when using custom directory
You can pass your custom directory path along with ng
command.
ng g c myfolder\mycomponent
But there are chances that you miss spell the path and either new folder gets created or target directory changes. For this reason dryRun
is very helpful. It displays an output of how the changes is going to be affected.
After verifying the result you can run the same command without -d
to make the changes.
--dryRun=true|false
When true, runs through and reports activity without writing out results.
Default: false
Aliases: -d
Official Doc :- https://angular.io/cli/generate
You should use ToList() method. (Don't forget about System.Linq namespace)
ex.:
IList<Model> models = Builder<Model>.CreateListOfSize(10).Build();
List<Model> lstMOdels = models.ToList();
If you have the SQL Server 2008 Installation media, you can install just the Client/Workstation Components. You don't have to install the database engine to install the workstation tools, but if you plan to do Integration Services development, you do need to install the Integration Services Engine on the workstation for BIDS to be able to be used for development. Keep in mind that Visual Studio 2010 does not have BI development support currently, so you have to install BIDS from the SQL Installation media and use the Visual Studio 2008 BI Development Studio that installs under the SQL Server 2008 folder in Program Files if you need to do any SSIS, SSRS, or SSAS development from the workstation.
As mentioned in the comments you can download Management Studio Express free from Microsoft, but if you already have the installation media for SQL Server Standard/Enterprise/Developer edition, you'd be better off using what you have.
/* 1 */ Foo* foo1 = new Foo ();
Creates an object of type Foo
in dynamic memory. foo1
points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If Foo
was a POD-type, this would perform value-initialization (it doesn't apply here).
/* 2 */ Foo* foo2 = new Foo;
Identical to before, because Foo
is not a POD type.
/* 3 */ Foo foo3;
Creates a Foo
object called foo3
in automatic storage.
/* 4 */ Foo foo4 = Foo::Foo();
Uses copy-initialization to create a Foo
object called foo4
in automatic storage.
/* 5 */ Bar* bar1 = new Bar ( *new Foo() );
Uses Bar
's conversion constructor to create an object of type Bar
in dynamic storage. bar1
is a pointer to it.
/* 6 */ Bar* bar2 = new Bar ( *new Foo );
Same as before.
/* 7 */ Bar* bar3 = new Bar ( Foo foo5 );
This is just invalid syntax. You can't declare a variable there.
/* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );
Would work and work by the same principle to 5 and 6 if bar3
wasn't declared on in 7.
5 & 6 contain memory leaks.
Syntax like new Bar ( Foo::Foo() );
is not usual. It's usually new Bar ( (Foo()) );
- extra parenthesis account for most-vexing parse. (corrected)
1) To redirect to the login page / from the login page, don't use the Redirect() methods. Use FormsAuthentication.RedirectToLoginPage()
and FormsAuthentication.RedirectFromLoginPage()
!
2) You should just use RedirectToAction("action", "controller") in regular scenarios..
You want to redirect in side the Initialize method? Why? I don't see why would you ever want to do this, and in most cases you should review your approach imo.. If you want to do this for authentication this is DEFINITELY the wrong way (with very little chances foe an exception)
Use the [Authorize]
attribute on your controller or method instead :)
UPD: if you have some security checks in the Initialise method, and the user doesn't have access to this method, you can do a couple of things: a)
Response.StatusCode = 403;
Response.End();
This will send the user back to the login page. If you want to send him to a custom location, you can do something like this (cautios: pseudocode)
Response.Redirect(Url.Action("action", "controller"));
No need to specify the full url. This should be enough. If you completely insist on the full url:
Response.Redirect(new Uri(Request.Url, Url.Action("action", "controller")).ToString());
ActionBar actionBar;
actionBar = getActionBar();
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#93E9FA"));
actionBar.setBackgroundDrawable(colorDrawable);
I had this issue, this is how i have solved it. The problem mostly is that your Angular version is not supporting your Node.js version for the build. So the best solution is to upgrade your Node.js to the most current stable one.
For a clean upgrade of Node.js, i advise using n. if you are using Mac.
npm install -g n
npm cache clean -f
sudo n stable
npm update -g
and now check that you are updated:
node -v
npm -v
For more details, check this link: here
I like both @Qiao first answer and @Or's addition. For a sake of a little less processing I would like to add to Or's answer.
In @Or's answer keeping track of visited node is great. We can also allow the program to exit sooner that it currently is. At some point in the for loop the current_neighbour
will have to be the end
, and once that happens the shortest path is found and program can return.
I would modify the the method as follow, pay close attention to the for loop
graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13]
}
def bfs(graph_to_search, start, end):
queue = [[start]]
visited = set()
while queue:
# Gets the first path in the queue
path = queue.pop(0)
# Gets the last node in the path
vertex = path[-1]
# Checks if we got to the end
if vertex == end:
return path
# We check if the current node is already in the visited nodes set in order not to recheck it
elif vertex not in visited:
# enumerate all adjacent nodes, construct a new path and push it into the queue
for current_neighbour in graph_to_search.get(vertex, []):
new_path = list(path)
new_path.append(current_neighbour)
queue.append(new_path)
#No need to visit other neighbour. Return at once
if current_neighbour == end
return new_path;
# Mark the vertex as visited
visited.add(vertex)
print bfs(graph, 1, 13)
The output and everything else will be the same. However, the code will take less time to process. This is especially useful on larger graphs. I hope this helps someone in the future.
Options>Advanced>connections
Uncheck the option :
Use port 80 and 443 as alternative....
This answer uses bits of other answers, but hopefully it'll be a bit clearer as to the circumstances. You never specified what you were rsyncing - a single directory entry or multiple files.
So let's assume you are moving a source directory entry across, and not just moving the files contained in it.
Let's say you have a directory locally called data/myappdata/
and you have a load of subdirectories underneath this.
You have data/
on your target machine but no data/myappdata/
- this is easy enough:
rsync -rvv /path/to/data/myappdata/ user@host:/remote/path/to/data/myappdata
You can even use a different name for the remote directory:
rsync -rvv --recursive /path/to/data/myappdata user@host:/remote/path/to/data/newdirname
If you're just moving some files and not moving the directory entry that contains them then you would do:
rsync -rvv /path/to/data/myappdata/*.txt user@host:/remote/path/to/data/myappdata/
and it will create the myappdata
directory for you on the remote machine to place your files in. Again, the data/
directory must exist on the remote machine.
Incidentally, my use of -rvv
flag is to get doubly verbose output so it is clear about what it does, as well as the necessary recursive behaviour.
Just to show you what I get when using rsync (3.0.9 on Ubuntu 12.04)
$ rsync -rvv *.txt [email protected]:/tmp/newdir/
opening connection using: ssh -l user remote.machine rsync --server -vvre.iLsf . /tmp/newdir/
[email protected]'s password:
sending incremental file list
created directory /tmp/newdir
delta-transmission enabled
bar.txt
foo.txt
total: matches=0 hash_hits=0 false_alarms=0 data=0
Hope this clears this up a little bit.
The project npm-install-peers
will detect peers and install them.
As of v1.0.1
it doesn't support writing back to the package.json
automatically, which would essentially solve our need here.
Please add your support to issue in flight: https://github.com/spatie/npm-install-peers/issues/4
I will second madExcept and similar tools, like Eurekalog, but I think you can come a good way with FastMM also. With full debugmode enabled, it should give you some clues of whats wrong.
Anyway, even though Delphi uses FastMM as default, it's worth getting the full FastMM for it's additional control over logging.
try:
r = requests.post(url, data=data, verify='/path/to/public_key.pem')
If you were using Solr's default or Lucene query parser, you can pretty much always put it into a query string query:
POST test/_search
{
"query": {
"query_string": {
"query": "(( name:(+foo +bar) OR info:(+foo +bar) )) AND state:(1) AND (has_image:(0) OR has_image:(1)^100)"
}
}
}
That said, you may want to use a boolean query, like the one you already posted, or even a combination of the two.
If you couldn't find http.conf
and followed Nick's way.
Restart Apache using sudo service apache2 restart
.
The excellent (free trial) IcoFX allows you to create and edit icons, including multiple sizes up to 256x256, PNG compression, and transparency. I highly recommend it over most of the alternates.
Get your copy here: http://icofx.ro/ . It supports Windows XP onwards.
Windows automatically chooses the proper icon from the file, depending on where it is to be displayed.
For more information on icon design and the sizes/bit depths you should include, see these references:
pandas.DataFrame.append
DataFrame.append(self, other, ignore_index=False, verify_integrity=False, sort=False) ? 'DataFrame'
df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
df.append(df2)
With ignore_index set to True:
df.append(df2, ignore_index=True)
Try Below Simple Ruby Magics :)
(1..x).each { |n| puts n }
x.times { |n| puts n }
1.upto(x) { |n| print n }
Why do you need to state both 'x' and 'y' before the ':'?
Because a lambda is (conceptually) the same as a function, just written inline. Your example is equivalent to
def f(x, y) : return x + y
just without binding it to a name like f
.
Also how do you make it return multiple arguments?
The same way like with a function. Preferably, you return a tuple:
lambda x, y: (x+y, x-y)
Or a list, or a class, or whatever.
The thing with self.entry_1.bind
should be answered by Demosthenex.
Encrypt something with the public key, and see which private key decrypts it.
This Code Project article by none other than Jeff Atwood implements a simplified wrapper around the .NET cryptography classes. Assuming these keys were created for use with RSA, use the asymmetric class with your public key to encrypt, and the same with your private key to decrypt.
I believe it is best to use CharSequence. The reason is that String implements CharSequence, therefore you can pass a String into a CharSequence, HOWEVER you cannot pass a CharSequence into a String, as CharSequence doesn't not implement String. ALSO, in Android the EditText.getText()
method returns an Editable, which also implements CharSequence and can be passed easily into one, while not easily into a String. CharSequence handles all!
If you're using Bootstrap Sass, here's another way that avoids having to add extra classes to your element markup:
@import "bootstrap/mixins/_border-radius";
@import "bootstrap/_variables";
.your-class {
$r: $border-radius-base; // or $border-radius-large, $border-radius-small, ...
@include border-top-radius($r);
@include border-bottom-radius($r);
}
Yes, the 3rd template parameter on map
specifies the comparator, which is a binary predicate. Example:
struct ByLength : public std::binary_function<string, string, bool>
{
bool operator()(const string& lhs, const string& rhs) const
{
return lhs.length() < rhs.length();
}
};
int main()
{
typedef map<string, string, ByLength> lenmap;
lenmap mymap;
mymap["one"] = "one";
mymap["a"] = "a";
mymap["fewbahr"] = "foobar";
for( lenmap::const_iterator it = mymap.begin(), end = mymap.end(); it != end; ++it )
cout << it->first << "\n";
}
Not tried it with combo boxes but this has worked for me with other controls...
He uses the adorner layer here to display a watermark.
Today I needed to accomplish a similar task so I wrote up a gist to accomplish the task based on some research I did. I hope that someone will find this useful!
import os
os.system('cls' if os.name == 'nt' else 'clear')
oldfile = raw_input('{*} Enter the file (with extension) you would like to strip domains from: ')
newfile = raw_input('{*} Enter the name of the file (with extension) you would like me to save: ')
emailDomains = ['windstream.net', 'mail.com', 'google.com', 'web.de', 'email', 'yandex.ru', 'ymail', 'mail.eu', 'mail.bg', 'comcast.net', 'yahoo', 'Yahoo', 'gmail', 'Gmail', 'GMAIL', 'hotmail', 'comcast', 'bellsouth.net', 'verizon.net', 'att.net', 'roadrunner.com', 'charter.net', 'mail.ru', '@live', 'icloud', '@aol', 'facebook', 'outlook', 'myspace', 'rocketmail']
print "\n[*] This script will remove records that contain the following strings: \n\n", emailDomains
raw_input("\n[!] Press any key to start...\n")
linecounter = 0
with open(oldfile) as oFile, open(newfile, 'w') as nFile:
for line in oFile:
if not any(domain in line for domain in emailDomains):
nFile.write(line)
linecounter = linecounter + 1
print '[*] - {%s} Writing verified record to %s ---{ %s' % (linecounter, newfile, line)
print '[*] === COMPLETE === [*]'
print '[*] %s was saved' % newfile
print '[*] There are %s records in your saved file.' % linecounter
Link to Gist: emailStripper.py
Best, Az
The following works for me:
function decodeHtml(html) {
let areaElement = document.createElement("textarea");
areaElement.innerHTML = html;
return areaElement.value;
}
I also encountered that problem.Check if database name already exist in Mysql,and rename the old one.
Wrap the modal into a connected container and perform the async operation in here. This way you can reach both the dispatch to trigger actions and the onClose prop too. To reach dispatch
from props, do not pass mapDispatchToProps
function to connect
.
class ModalContainer extends React.Component {
handleDelete = () => {
const { dispatch, onClose } = this.props;
dispatch({type: 'DELETE_POST'});
someAsyncOperation().then(() => {
dispatch({type: 'DELETE_POST_SUCCESS'});
onClose();
})
}
render() {
const { onClose } = this.props;
return <Modal onClose={onClose} onSubmit={this.handleDelete} />
}
}
export default connect(/* no map dispatch to props here! */)(ModalContainer);
The App where the modal is rendered and its visibility state is set:
class App extends React.Component {
state = {
isModalOpen: false
}
handleModalClose = () => this.setState({ isModalOpen: false });
...
render(){
return (
...
<ModalContainer onClose={this.handleModalClose} />
...
)
}
}
LIB.EXE is the librarian for VS
http://msdn.microsoft.com/en-us/library/7ykb2k5f(VS.80).aspx
(like libtool on Unix)
Our team's fix for this was removing a registry path from our .npmrc. We had two path aliases in the rc file, and one was pointing to an Artifactory instance that had been deprecated.
The error had nothing to do with our App's actual code but everything to do with our development environment.
In my case, I was already logged-in and I just executed git push
.
Although it was designed for .NET web-testing, I've been using the WatiN framework for this purpose. Since it is DOM-based, it is pretty easy to capture HTML, text, or images. Recentely, I used it to dump a list of links from a MediaWiki All Pages namespace query into an Excel spreadsheet. The following VB.NET code fragement is pretty crude, but it works.
Sub GetLinks(ByVal PagesIE As IE, ByVal MyWorkSheet As Excel.Worksheet)
Dim PagesLink As Link
For Each PagesLink In PagesIE.TableBodies(2).Links
With MyWorkSheet
.Cells(XLRowCounterInt, 1) = PagesLink.Text
.Cells(XLRowCounterInt, 2) = PagesLink.Url
End With
XLRowCounterInt = XLRowCounterInt + 1
Next
End Sub
If you mean "Can I use the stylistic presentation of Bootstrap in an email?" then you can, though I don't know anybody that has done it yet. You'll need to recode everything in tables though.
If you are after functionality, it depends on where your emails are viewed. If a significant proportion of your users are on Outlook, Gmail, Yahoo or Hotmail (and these typically add up to around 75% of email clients) then a lot of Bootstrap's goodness is not possible. Mac Mail, iOS Mail and Gmail on Android are much better at rendering CSS, so if you are targeting mostly mobile devices it's not quite so bad.
font-face
- you can only use external images. All other external resources (CSS files, fonts) are excluded. :hover
, :active
states cannot be styled separatelyThere are loads of answers on SO, and lots of other links on the internet at large.
Just FYI, as of today (22 October 2019) official Nginx docker images all have line:
CMD ["nginx", "-g", "daemon off;"]
Some browser may block popup created by window.open(url, "_blank");
.
An alternative is to create a link and click on it.
...
constructor(@Inject(DOCUMENT) private document: Document) {}
...
openNewWindow(): void {
const link = this.document.createElement('a');
link.target = '_blank';
link.href = 'http://www.your-url.com';
link.click();
link.remove();
}
I actually just found this today for something I'm working on. This will return file paths for all files in a folder and its subfolders.
Dim colFiles As New Collection
RecursiveDir colFiles, "C:\Users\Marek\Desktop\Makro\", "*.*", True
Dim vFile As Variant
For Each vFile In colFiles
'file operation here or store file name/path in a string array for use later in the script
filepath(n) = vFile
filename = fso.GetFileName(vFile) 'If you want the filename without full path
n=n+1
Next vFile
'These two functions are required
Public Function RecursiveDir(colFiles As Collection, strFolder As String, strFileSpec As String, bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
colFiles.Add strFolder & strTemp
strTemp = Dir
Loop
If bIncludeSubfolders Then
strTemp = Dir(strFolder, vbDirectory)
Do While strTemp <> vbNullString
If (strTemp <> ".") And (strTemp <> "..") Then
If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
colFolders.Add strTemp
End If
End If
strTemp = Dir
Loop
'Call RecursiveDir for each subfolder in colFolders
For Each vFolderName In colFolders
Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
Next vFolderName
End If
End Function
Public Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
If Right(strFolder, 1) = "\" Then
TrailingSlash = strFolder
Else
TrailingSlash = strFolder & "\"
End If
End If
End Function
This is adapted from a post by Ammara Digital Image Solutions.(http://www.ammara.com/access_image_faq/recursive_folder_search.html).
Try Catch exists via workaround in VBScript:
Class CFunc1
Private Sub Class_Initialize
WScript.Echo "Starting"
Dim i : i = 65535 ^ 65535
MsgBox "Should not see this"
End Sub
Private Sub CatchErr
If Err.Number = 0 Then Exit Sub
Select Case Err.Number
Case 6 WScript.Echo "Overflow handled!"
Case Else WScript.Echo "Unhandled error " & Err.Number & " occurred."
End Select
Err.Clear
End Sub
Private Sub Class_Terminate
CatchErr
WScript.Echo "Exiting"
End Sub
End Class
Dim Func1 : Set Func1 = New CFunc1 : Set Func1 = Nothing
Here are the timing results using Python 3.6.8. Keep in mind these times are relative to one another, not absolute.
I stuck to only doing shallow copies, and also added some new methods that weren't possible in Python2, such as list.copy()
(the Python3 slice equivalent) and two forms of list unpacking (*new_list, = list
and new_list = [*list]
):
METHOD TIME TAKEN
b = [*a] 2.75180600000021
b = a * 1 3.50215399999990
b = a[:] 3.78278899999986 # Python2 winner (see above)
b = a.copy() 4.20556500000020 # Python3 "slice equivalent" (see above)
b = []; b.extend(a) 4.68069800000012
b = a[0:len(a)] 6.84498999999959
*b, = a 7.54031799999984
b = list(a) 7.75815899999997
b = [i for i in a] 18.4886440000000
b = copy.copy(a) 18.8254879999999
b = []
for item in a:
b.append(item) 35.4729199999997
We can see the Python2 winner still does well, but doesn't edge out Python3 list.copy()
by much, especially considering the superior readability of the latter.
The dark horse is the unpacking and repacking method (b = [*a]
), which is ~25% faster than raw slicing, and more than twice as fast as the other unpacking method (*b, = a
).
b = a * 1
also does surprisingly well.
Note that these methods do not output equivalent results for any input other than lists. They all work for sliceable objects, a few work for any iterable, but only copy.copy()
works for more general Python objects.
Here is the testing code for interested parties (Template from here):
import timeit
COUNT = 50000000
print("Array duplicating. Tests run", COUNT, "times")
setup = 'a = [0,1,2,3,4,5,6,7,8,9]; import copy'
print("b = list(a)\t\t", timeit.timeit(stmt='b = list(a)', setup=setup, number=COUNT))
print("b = copy.copy(a)\t", timeit.timeit(stmt='b = copy.copy(a)', setup=setup, number=COUNT))
print("b = a.copy()\t\t", timeit.timeit(stmt='b = a.copy()', setup=setup, number=COUNT))
print("b = a[:]\t\t", timeit.timeit(stmt='b = a[:]', setup=setup, number=COUNT))
print("b = a[0:len(a)]\t\t", timeit.timeit(stmt='b = a[0:len(a)]', setup=setup, number=COUNT))
print("*b, = a\t\t\t", timeit.timeit(stmt='*b, = a', setup=setup, number=COUNT))
print("b = []; b.extend(a)\t", timeit.timeit(stmt='b = []; b.extend(a)', setup=setup, number=COUNT))
print("b = []; for item in a: b.append(item)\t", timeit.timeit(stmt='b = []\nfor item in a: b.append(item)', setup=setup, number=COUNT))
print("b = [i for i in a]\t", timeit.timeit(stmt='b = [i for i in a]', setup=setup, number=COUNT))
print("b = [*a]\t\t", timeit.timeit(stmt='b = [*a]', setup=setup, number=COUNT))
print("b = a * 1\t\t", timeit.timeit(stmt='b = a * 1', setup=setup, number=COUNT))