That is very odd.
I went through ItemNotFoundException
's base classes and tested the following multiple catch
es to see what would catch it:
try {
remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
write-host 'RuntimeException'
}
catch [System.SystemException] {
write-host 'SystemException'
}
catch [System.Exception] {
write-host 'Exception'
}
catch {
write-host 'well, darn'
}
As it turns out, the output was 'RuntimeException'
. I also tried it with a different exception CommandNotFoundException
:
try {
do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
write-host 'CommandNotFoundException'
}
catch {
write-host 'well, darn'
}
That output 'CommandNotFoundException'
correctly.
I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type
they could and then use a switch
. The following just catches Exception
instead of RuntimeException
, but is the switch
equivalent of my first example that checks all base types of ItemNotFoundException
:
try {
Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
switch($_.Exception.GetType().FullName) {
'System.Management.Automation.ItemNotFoundException' {
write-host 'ItemNotFound'
}
'System.Management.Automation.SessionStateException' {
write-host 'SessionState'
}
'System.Management.Automation.RuntimeException' {
write-host 'RuntimeException'
}
'System.SystemException' {
write-host 'SystemException'
}
'System.Exception' {
write-host 'Exception'
}
default {'well, darn'}
}
}
This writes 'ItemNotFound'
, as it should.
Polling like this is definitely the least preferred solution.
I assume that you have another thread that will do something to make the condition true. There are several ways to synchronize threads. The easiest one in your case would be a notification via an Object:
Main thread:
synchronized(syncObject) {
try {
// Calling wait() will block this thread until another thread
// calls notify() on the object.
syncObject.wait();
} catch (InterruptedException e) {
// Happens if someone interrupts your thread.
}
}
Other thread:
// Do something
// If the condition is true, do the following:
synchronized(syncObject) {
syncObject.notify();
}
syncObject
itself can be a simple Object
.
There are many other ways of inter-thread communication, but which one to use depends on what precisely you're doing.
try using .animate instead of .css or even just on the opacity one and leave .css on the display?? may b
jQuery(document).ready(function(){
if (jQuery('#nav .drop').animate('display') === 'block') {
jQuery('#main').animate('opacity') = '0.6';
Yes, it is a bit puzzling at first.
In Ruby, methods may receive a code block in order to perform arbitrary segments of code.
When a method expects a block, it invokes it by calling the yield
function.
This is very handy, for instance, to iterate over a list or to provide a custom algorithm.
Take the following example:
I'm going to define a Person
class initialized with a name, and provide a do_with_name
method that when invoked, would just pass the name
attribute, to the block received.
class Person
def initialize( name )
@name = name
end
def do_with_name
yield( @name )
end
end
This would allow us to call that method and pass an arbitrary code block.
For instance, to print the name we would do:
person = Person.new("Oscar")
#invoking the method passing a block
person.do_with_name do |name|
puts "Hey, his name is #{name}"
end
Would print:
Hey, his name is Oscar
Notice, the block receives, as a parameter, a variable called name
(N.B. you can call this variable anything you like, but it makes sense to call it name
). When the code invokes yield
it fills this parameter with the value of @name
.
yield( @name )
We could provide another block to perform a different action. For example, reverse the name:
#variable to hold the name reversed
reversed_name = ""
#invoke the method passing a different block
person.do_with_name do |name|
reversed_name = name.reverse
end
puts reversed_name
=> "racsO"
We used exactly the same method (do_with_name
) - it is just a different block.
This example is trivial. More interesting usages are to filter all the elements in an array:
days = ["monday", "tuesday", "wednesday", "thursday", "friday"]
# select those which start with 't'
days.select do | item |
item.match /^t/
end
=> ["tuesday", "thursday"]
Or, we can also provide a custom sort algorithm, for instance based on the string size:
days.sort do |x,y|
x.size <=> y.size
end
=> ["monday", "friday", "tuesday", "thursday", "wednesday"]
I hope this helps you to understand it better.
BTW, if the block is optional you should call it like:
yield(value) if block_given?
If is not optional, just invoke it.
EDIT
@hmak created a repl.it for these examples: https://repl.it/@makstaks/blocksandyieldsrubyexample
Another thing to check is whether you have Windows Firewall enabled, since that might be blocking port 42424.
I use such method to do this
public class HttpReqRespUtils {
private static final String[] IP_HEADER_CANDIDATES = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR"
};
public static String getClientIpAddressIfServletRequestExist() {
if (RequestContextHolder.getRequestAttributes() == null) {
return "0.0.0.0";
}
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
for (String header: IP_HEADER_CANDIDATES) {
String ipList = request.getHeader(header);
if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
String ip = ipList.split(",")[0];
return ip;
}
}
return request.getRemoteAddr();
}
}
POSIXly (also valid in sed), Only one regex used, need memory only for one line (as usual):
sed '/\(#include\).*/!b;//{h;s//\1 "newfile.h"/;G};:1;n;b1'
Explained:
sed '
/\(#include\).*/!b # Only one regex used. On lines not matching
# the text `#include` **yet**,
# branch to end, cause the default print. Re-start.
//{ # On first line matching previous regex.
h # hold the line.
s//\1 "newfile.h"/ # append ` "newfile.h"` to the `#include` matched.
G # append a newline.
} # end of replacement.
:1 # Once **one** replacement got done (the first match)
n # Loop continually reading a line each time
b1 # and printing it by default.
' # end of sed script.
I also like to build locators from up to bottom like:
//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']
It's pretty simple, as we just search btn-group
with button[contains(.,'Arcade Reader')]
and get it's button[@name='settings']
That's just another option to build xPath locators
What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:
getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");
or even simplify more
getGroupButton("Arcade Reader", "delete").click();
The problem is that you mapped your servlet to /register.html
and it expects POST method, because you implemented only doPost()
method. So when you open register.html
page, it will not open html page with the form but servlet that handles the form data.
Alternatively when you submit POST form to non-existing URL, web container will display 405 error (method not allowed) instead of 404 (not found).
To fix:
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.
ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.
The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).
A better option
Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE
). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses
(and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.
redirect 301 /contact.php /contact-us.php
There is no point using the redirectmatch rule and then have to write your links so they are exact match. If you don't include you don't have to exclude! Just use redirect without match and then use links normally
Python's eager in its evaluation, so eval(input(...))
(Python 3) will evaluate the user's input as soon as it hits the eval
, regardless of what you do with the data afterwards. Therefore, this is not safe, especially when you eval
user input.
Use ast.literal_eval
.
As an example, entering this at the prompt could be very bad for you:
__import__('os').system('rm -rf /a-path-you-really-care-about')
All methods that are accessible are inherited by subclasses.
From the Sun Java Tutorials:
A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members
The only difference with inherited static (class) methods and inherited non-static (instance) methods is that when you write a new static method with the same signature, the old static method is just hidden, not overridden.
From the page on the difference between overriding and hiding.
The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass
I'm not certain on what it is you're trying to achieve. But maybe you can use this:
$var =~ s/^start/foo/;
$var =~ s/end$/bar/;
I.e. just leave the middle alone and replace the start and end.
The general methodology would be to iterate through the ArrayList
, and insert the values into the HashMap
. An example is as follows:
HashMap<String, Product> productMap = new HashMap<String, Product>();
for (Product product : productList) {
productMap.put(product.getProductCode(), product);
}
The recommended approach is:
window.greeting = "Hello World!"
You can then access it within any function:
function foo() {
alert(greeting); // Hello World!
alert(window["greeting"]); // Hello World!
alert(window.greeting); // Hello World! (recommended)
}
This approach is preferred for two reasons.
The intent is explicit. The use of the var
keyword can easily lead to declaring global vars
that were intended to be local or vice versa. This sort of variable scoping is a point of confusion for a lot of Javascript developers. So as a general rule, I make sure all variable declarations are preceded with the keyword var
or the prefix window
.
You standardize this syntax for reading the variables this way as well which means that a locally scoped var
doesn't clobber the global var
or vice versa. For example what happens here is ambiguous:
greeting = "Aloha";
function foo() {
greeting = "Hello"; // overrides global!
}
function bar(greeting) {
alert(greeting);
}
foo();
bar("Howdy"); // does it alert "Hello" or "Howdy" ?
However, this is much cleaner and less error prone (you don't really need to remember all the variable scoping rules):
function foo() {
window.greeting = "Hello";
}
function bar(greeting) {
alert(greeting);
}
foo();
bar("Howdy"); // alerts "Howdy"
You can go to AdoptOpenJDK to download your binaries for all platforms provided by a great community.
# first this
> npm config rm proxy
> npm config rm https-proxy
# then this
> npm config set registry https://registry.npmjs.org/
solved my problem.
Again: Be sure to check whether you have internet connected properly.
are you writing java code for android? in that case you should write maybe
if (90 >= angle && angle <= 180) {
updating the code to a nicer style (like some suggested) you would get:
if (angle <= 90 && angle <= 180) {
now you see that the second check is unnecessary or maybe you mixed up <
and >
signs in the first check and wanted actually to have
if (angle >= 90 && angle <= 180) {
Just create a template;
From your project choose: Project - Export Template
The wizard will let you define
Then it zips up your project into 'My Exported Templates' directory. You also have the option to make your template available when you create a new project.
When you use your template to create a new project, the namespace will be correct for 'your_new_project_name' throughout every file, all references correct, everything perfecto :)
You can send the .zip file to anybody, and they must copy (not unzip) the .zip file into Templates\ProjectTemplates directory for them to use too.
I made an ASP.NET MVC template with folders, layout page, viewmodels etc arranged just how I like them.
NOTE:
If you have an empty folder in your project, it WON'T be added to the template, so I just added an empty class appropriate to each folder, and a sample picture for images folder.
I solve such queries using this pattern:
SELECT *
FROM t
WHERE t.field=(
SELECT MAX(t.field)
FROM t AS t0
WHERE t.group_column1=t0.group_column1
AND t.group_column2=t0.group_column2 ...)
That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:
WITH site_history AS (
SELECT sites.siteName, sites.siteIP, history.date
FROM sites
JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
SELECT MAX(date)
FROM site_history h0
WHERE h.siteName=h0.siteName)
ORDER BY siteName
It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date
field should be unique for each siteName
, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history
table has an unique index for (site, date)
, this query is also very fast, index range scan on the history
table scanning just the first item can be used.
you can try like this:
var request = require('request');
request.post({ headers: {'content-type' : 'application/json'}
, url: <your URL>, body: <req_body in json> }
, function(error, response, body){
console.log(body);
});
Just add an app setting bundle and implement a toggle to reset the keychain on app restart or something based on the value selected through settings (available through userDefaults)
The easiest approach which I have used is
var found = arr.find(function(element) {
return element.name === "k1";
});
//If you print the found :
console.log(found);
=> Object { name: "k1", value: "abc" }
//If you need the value
console.log(found.value)
=> "abc"
The similar approach can be used to find the values from the JSON Array based on any input data from the JSON.
I though the perfect solution would be to have a timer handle the delayed action. FxCop doesn't like when you have an interval less then one second. I need to delay my actions until AFTER my DataGrid has completed sorting by column. I figured a one-shot timer (AutoReset = false) would be the solution, and it works perfectly. AND, FxCop will not let me suppress the warning!
Actually I wanted same alike thing, To get one year backward date, for a given date! :-)
With the hint of above answer from @mohammad mohsenipur I got to the following link, via his given link!
Luckily, there is a method same as date_add method, named date_sub method! :-) I do the following to get done what I wanted!
$date = date_create('2000-01-01');
date_sub($date, date_interval_create_from_date_string('1 years'));
echo date_format($date, 'Y-m-d');
Hopes this answer will help somebody too! :-)
Good luck guys!
Sorry to drag this up after so long but I used the below. Any disadvantages? See the open function...
$("#popup").dialog(
{
height: 670,
width: 680,
modal: true,
autoOpen: false,
close: function(event, ui) { $('#wrap').show(); },
open: function(event, ui)
{
$('.ui-widget-overlay').bind('click', function()
{
$("#popup").dialog('close');
});
}
});
I think you need this ..
Dim n as Integer
For n = 5 to 17
msgbox cells(n,3) '--> sched waste
msgbox cells(n,4) '--> type of treatm
msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
msgbox cells(n,6) '--> email col
Next
You need to wrap button click handler to match the pattern
public void klik(object sender, EventArgs e)
You may be interested in the Unicode categories "Other, Control" and possibly "Other, Format" (unfortunately the latter seems to contain both unprintable and printable characters).
In Java regular expressions you can check for them using \p{Cc}
and \p{Cf}
respectively.
InnoDB allows you to add a new foreign key constraint to a table by using ALTER TABLE:
ALTER TABLE tbl_name
ADD [CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
On the other hand, if MyISAM has advantages over InnoDB in your context, why would you want to create foreign key constraints at all. You can handle this on the model level of your application. Just make sure the columns which you want to use as foreign keys are indexed!
I also had this issue and ended up using Andy's code to create a function to clean things up when multiple commands need to be run.
It'll return stderr, stdout, and exit codes as objects. One thing to note: the function won't accept .\
in the path; full paths must be used.
Function Execute-Command ($commandTitle, $commandPath, $commandArguments)
{
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $commandPath
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = $commandArguments
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
[pscustomobject]@{
commandTitle = $commandTitle
stdout = $p.StandardOutput.ReadToEnd()
stderr = $p.StandardError.ReadToEnd()
ExitCode = $p.ExitCode
}
}
Here's how to use it:
$DisableACMonitorTimeOut = Execute-Command -commandTitle "Disable Monitor Timeout" -commandPath "C:\Windows\System32\powercfg.exe" -commandArguments " -x monitor-timeout-ac 0"
The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system.
You simply want to pass the actual path to the UriSource:
logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");
WunderBart's answer was the best for me. Note that you can speed it up a lot if your images are often the right way around, simply by testing the orientation first and bypassing the rest of the code if no rotation is required.
Putting all of the info from wunderbart together, something like this;
var handleTakePhoto = function () {
let fileInput: HTMLInputElement = <HTMLInputElement>document.getElementById('photoInput');
fileInput.addEventListener('change', (e: any) => handleInputUpdated(fileInput, e.target.files));
fileInput.click();
}
var handleInputUpdated = function (fileInput: HTMLInputElement, fileList) {
let file = null;
if (fileList.length > 0 && fileList[0].type.match(/^image\//)) {
isLoading(true);
file = fileList[0];
getOrientation(file, function (orientation) {
if (orientation == 1) {
imageBinary(URL.createObjectURL(file));
isLoading(false);
}
else
{
resetOrientation(URL.createObjectURL(file), orientation, function (resetBase64Image) {
imageBinary(resetBase64Image);
isLoading(false);
});
}
});
}
fileInput.removeEventListener('change');
}
// from http://stackoverflow.com/a/32490603
export function getOrientation(file, callback) {
var reader = new FileReader();
reader.onload = function (event: any) {
var view = new DataView(event.target.result);
if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
var length = view.byteLength,
offset = 2;
while (offset < length) {
var marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1) {
if (view.getUint32(offset += 2, false) != 0x45786966) {
return callback(-1);
}
var little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
if (view.getUint16(offset + (i * 12), little) == 0x0112)
return callback(view.getUint16(offset + (i * 12) + 8, little));
}
else if ((marker & 0xFF00) != 0xFF00) break;
else offset += view.getUint16(offset, false);
}
return callback(-1);
};
reader.readAsArrayBuffer(file.slice(0, 64 * 1024));
};
export function resetOrientation(srcBase64, srcOrientation, callback) {
var img = new Image();
img.onload = function () {
var width = img.width,
height = img.height,
canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d");
// set proper canvas dimensions before transform & export
if (4 < srcOrientation && srcOrientation < 9) {
canvas.width = height;
canvas.height = width;
} else {
canvas.width = width;
canvas.height = height;
}
// transform context before drawing image
switch (srcOrientation) {
case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
case 7: ctx.transform(0, -1, -1, 0, height, width); break;
case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
default: break;
}
// draw image
ctx.drawImage(img, 0, 0);
// export base64
callback(canvas.toDataURL());
};
img.src = srcBase64;
}
Clipboard.SetText("hello");
You'll need to use the System.Windows.Forms
or System.Windows
namespaces for that.
The short answer is there's no great way to do this given the design you have. Here's a related question on the topic: Sum values of a single row?
If you normalized your schema and created a separate table called "Marks" which had a subject_id and a mark column this would allow you to take advantage of the SUM function as intended by a relational model.
Then your query would be
SELECT subject, SUM(mark) total
FROM Subjects s
INNER JOIN Marks m ON m.subject_id = s.id
GROUP BY s.id
new Date().toString();
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
Dateformatter can make it to any string you want
Use
It is the entity used to represent a non-breaking space. It is essentially a standard space, the primary difference being that a browser should not break (or wrap) a line of text at the point that this occupies.
var a = 'something' + '         ' + 'something'
A common character entity used in HTML is the non-breaking space ( ).
Remember that browsers will always truncate spaces in HTML pages. If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text, you can use the character entity.
http://www.w3schools.com/html/html_entities.asp
Demo
var a = 'something' + '         ' + 'something';_x000D_
_x000D_
document.body.innerHTML = a;
_x000D_
class testme(object):
''' A test object '''
def __init__(self):
self.y = 0
def f(aTestMe1, aTestMe2):
return aTestMe1.y + aTestMe2.y
c = testme #get a variable to the class
c.x = 10 #add an attribute x inital value 10
c.y = 4 #change the default attribute value of y to 4
t = testme() # declare t to be an instance object of testme
r = testme() # declare r to be an instance object of testme
t.y = 6 # set t.y to a number
r.y = 7 # set r.y to a number
print(f(r,t)) # call function designed to operate on testme objects
r.y = "I am r.y" # redefine r.y to be a string
print(f(r,t)) #POW!!!! not good....
The above would create a nightmare of unmaintainable code in a large system over a long period time. Call it what you want, but the ability to "dynamically" change a variables type is just a bad idea...
Old question but this is missing. I'm new to python so please tell me if this is a "bad" solution. This solution is supported for Windows and MacOS only and it works just for the main screen - but the os is not mentioned in the question.
Measure the size by taking a screenshot. As the screensize should not change this has to be done only once. There are more elegant solutions if you have a gui toolkit like GTK, wx, ... installed.
see Pillow
pip install Pillow
from PIL import ImageGrab
img = ImageGrab.grab()
print (img.size)
No need for any Java or Kotlin code to make it a clickable link, now you just need to follow given below code. And you can also link text color change by using textColorLink.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:textColorLink="@color/white"/>
it seems that you should set your command as an String[]
,for example:
String[] command = new String[]{"rmiregistry","2020"};
Runtime.getRuntime().exec(command);
it just like the style of main(String[] args)
.
git diff master > branch.diff
git apply --reverse branch.diff
You have to specify any one of the above phase to resolve the above error. In most of the situations, this would have occurred due to running the build from the eclipse environment.
instead of mvn clean package or mvn package you can try only package its work fine for me
I created a solution in SQL Server 2005 for this, and posted it on my website: http://www.jessemclain.com/downloads/code/sql/fn_GetMChooseNCombos.sql.htm
Here is an example to show usage:
SELECT * FROM dbo.fn_GetMChooseNCombos('ABCD', 2, '')
results:
Word
----
AB
AC
AD
BC
BD
CD
(6 row(s) affected)
In case you have a library that relies on requests
and you cannot modify the verify path (like with pyvmomi
) then you'll have to find the cacert.pem
bundled with requests and append your CA there. Here's a generic approach to find the cacert.pem
location:
windows
C:\>python -c "import requests; print requests.certs.where()"
c:\Python27\lib\site-packages\requests-2.8.1-py2.7.egg\requests\cacert.pem
linux
# (py2.7.5,requests 2.7.0, verify not enforced)
root@host:~/# python -c "import requests; print requests.certs.where()"
/usr/lib/python2.7/dist-packages/certifi/cacert.pem
# (py2.7.10, verify enforced)
root@host:~/# python -c "import requests; print requests.certs.where()"
/usr/local/lib/python2.7/dist-packages/requests/cacert.pem
btw. @requests-devs, bundling your own cacerts with request is really, really annoying... especially the fact that you do not seem to use the system ca store first and this is not documented anywhere.
update
in situations, where you're using a library and have no control over the ca-bundle location you could also explicitly set the ca-bundle location to be your host-wide ca-bundle:
REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-bundle.crt python -c "import requests; requests.get('https://somesite.com';)"
Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values
Whilst this an old question, I ran into this problem myself recently and some of the answers here are now deprecated (as the comments point out). So for the benefit of others who may have stumbled here:
A term
query can be used to find the exact term specified in the reverse index:
{
"query": {
"term" : { "tags" : "a" }
}
From the documenation https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html
Alternatively you can use a terms
query, which will match all documents with any of the items specified in the given array:
{
"query": {
"terms" : { "tags" : ["a", "c"]}
}
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html
One gotcha to be aware of (which caught me out) - how you define the document also makes a difference. If the field you're searching in has been indexed as a text
type then Elasticsearch will perform a full text search (i.e using an analyzed
string).
If you've indexed the field as a keyword
then a keyword search using a 'non-analyzed' string is performed. This can have a massive practical impact as Analyzed strings are pre-processed (lowercased, punctuation dropped etc.) See (https://www.elastic.co/guide/en/elasticsearch/guide/master/term-vs-full-text.html)
To avoid these issues, the string field has split into two new types: text, which should be used for full-text search, and keyword, which should be used for keyword search. (https://www.elastic.co/blog/strings-are-dead-long-live-strings)
I was receiving this error message, even though I had the max
settings set within the binding of my WCF service config file:
<basicHttpBinding>
<binding name="NewBinding1"
receiveTimeout="01:00:00"
sendTimeout="01:00:00"
maxBufferSize="2000000000"
maxReceivedMessageSize="2000000000">
<readerQuotas maxDepth="2000000000"
maxStringContentLength="2000000000"
maxArrayLength="2000000000"
maxBytesPerRead="2000000000"
maxNameTableCharCount="2000000000" />
</binding>
</basicHttpBinding>
It seemed as though these binding settings weren't being applied, thus the following error message:
IIS7 - (413) Request Entity Too Large when connecting to the service.
I realised that the name=""
attribute within the <service>
tag of the web.config
is not a free text field, as I thought it was. It is the fully qualified name of an implementation of a service contract as mentioned within this documentation page.
If that doesn't match, then the binding settings won't be applied!
<services>
<!-- The namespace appears in the 'name' attribute -->
<service name="Your.Namespace.ConcreteClassName">
<endpoint address="http://localhost/YourService.svc"
binding="basicHttpBinding" bindingConfiguration="NewBinding1"
contract="Your.Namespace.IConcreteClassName" />
</service>
</services>
I hope that saves someone some pain...
This might be not 100% related to the question, but on my search for an example of using multiprocessing with a queue this shows up first on google.
This is a basic example class that you can instantiate and put items in a queue and can wait until queue is finished. That's all I needed.
from multiprocessing import JoinableQueue
from multiprocessing.context import Process
class Renderer:
queue = None
def __init__(self, nb_workers=2):
self.queue = JoinableQueue()
self.processes = [Process(target=self.upload) for i in range(nb_workers)]
for p in self.processes:
p.start()
def render(self, item):
self.queue.put(item)
def upload(self):
while True:
item = self.queue.get()
if item is None:
break
# process your item here
self.queue.task_done()
def terminate(self):
""" wait until queue is empty and terminate processes """
self.queue.join()
for p in self.processes:
p.terminate()
r = Renderer()
r.render(item1)
r.render(item2)
r.terminate()
Return ABDeadlineType
from repository:
public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
List<ABDeadlineType> findAllSummarizedBy();
}
and then convert to DeadlineType. Manually or use mapstruct.
Or call constructor from @Query
annotation:
public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
@Query("select new package.DeadlineType(a.id, a.code) from ABDeadlineType a ")
List<DeadlineType> findAllSummarizedBy();
}
Or use @Projection
:
@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {
@Value("#{target.id}")
String getId();
@Value("#{target.code}")
String getText();
}
Update:
Spring can work without @Projection
annotation:
public interface DeadlineType {
String getId();
String getText();
}
How to get append input field value as json like
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
Here's a javascript example from mozilla:
var o = { a:0 } // `o` is now a basic object
Object.defineProperty(o, "b", {
get: function () {
return this.a + 1;
}
});
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number
which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.
Example from sof
<?php
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
?>
citings:
You can't do this with CSS alone. Using jQuery you can do
HTML
<label id="lab">Checkbox</label>
<input id="check" type="checkbox" />
CSS
.highlight{
background:yellow;
}
jQuery
$('#check').click(function(){
$('#lab').toggleClass('highlight')
})
This will work in all browsers
Try this
$("#globalsearchstr").focus(function(){
$(this).parent().css("background", "url('../images/r-srchbg_white.png') no-repeat");
});
The ===
is not for checking string equalit , to do so you can use the Regxp functions for example
if (x.match(y) === null) {
// x and y are not equal
}
there is also the test
function
System.Diagnostics.Debug.WriteLine()
will work, but you have to be looking in the right place for the output. In Visual Studio 2010, on the menu bar, click Debug -> Windows -> Output. Now, at the bottom of the screen docked next to your error list, there should be an output tab. Click it and double check it's showing output from the debug stream on the dropdown list.
P.S.: I think the output window shows on a fresh install, but I can't remember. If it doesn't, or if you closed it by accident, follow these instructions.
I found a solution.
This turns off the filtering, it's working, but not a good idea...
config.allowedContent = true;
To play with a content string works fine for id, etc, but not for the class and style attributes, because you have () and {} for class and style filtering.
So my bet is for allowing any class in the editor is:
config.extraAllowedContent = '*(*)';
This allows any class and any inline style.
config.extraAllowedContent = '*(*);*{*}';
To allow only class="asdf1" and class="asdf2" for any tag:
config.extraAllowedContent = '*(asdf1,asdf2)';
(so you have to specify the classnames)
To allow only class="asdf" only for p tag:
config.extraAllowedContent = 'p(asdf)';
To allow id attribute for any tag:
config.extraAllowedContent = '*[id]';
etc etc
To allow style tag (<style type="text/css">...</style>):
config.extraAllowedContent = 'style';
To be a bit more complex:
config.extraAllowedContent = 'span;ul;li;table;td;style;*[id];*(*);*{*}';
Hope it's a better solution...
If anyone has the same problem, one possible solution is to set the bindto
stream context configuration parameter (assuming you're connecting from 11.22.33.44 to 55.66.77.88):
$context = [
'socket' => [
'bindto' => '55.66.77.88'
]
];
$options = [
'soapVersion' => SOAP_1_1,
'stream_context' => stream_context_create($context)
];
$client = new Client('11.22.33.44', $options);
arr = [9,4,2,93,6,2,4,61,1];
ArrMax = Math.max.apply(Math, arr);
You are giving multiple Content-Type
headers. application/vnd.ms-excel
is enough.
And there are couple of syntax error too. To statement termination with ;
on the echo statement and wrong filename extension.
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=abc.xls"); //File name extension was wrong
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
echo "Some Text"; //no ending ; here
I wanted to support apps pre api 23 and instead of using checkSelfPermission
I used a try / catch
try {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} catch (SecurityException e) {
dialogGPS(this.getContext()); // lets the user know there is a problem with the gps
}
When you compile your program the reference variable of the base class gets memory and compiler checks all the methods in that class. So it checks all the base class methods but not the child class methods. Now at runtime when the object is created, only checked methods can run. In case a method is overridden in the child class that function runs. Child class other functions aren't run because the compiler hasn't recognized them at the compile time.
What's about similar approach, but without boxing to the Long objects:
File[] files = directory.listFiles();
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.compare(f1.lastModified(), f2.lastModified());
}
});
In at least in ubuntu 16.10, the default python3
is python3.5
. As such, all of the python3-X
packages will be installed for python3.5 and not for python3.6.
You can verify this by checking the shebang of pip3
:
$ head -n1 $(which pip3)
#!/usr/bin/python3
Fortunately, the pip installed by the python3-pip
package is installed into the "shared" /usr/lib/python3/dist-packages
such that python3.6 can also take advantage of it.
You can install packages for python3.6 by doing:
python3.6 -m pip install ...
For example:
$ python3.6 -m pip install requests
$ python3.6 -c 'import requests; print(requests.__file__)'
/usr/local/lib/python3.6/dist-packages/requests/__init__.py
you can use the download attribute on an a tag ...
<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>
see more: https://developer.mozilla.org/en/HTML/element/a#attr-download
I would use a change event not a click like this:
$('input[name="name-of-radio-group"]').change( function() {
alert($(this).val())
})
i just delete the error package from package.json and run again gradlew clean and its works for me For React Native
Available since Javascript 1.8/ECMAScript 5 and available in most older browsers:
var longest = arr.reduce(
function (a, b) {
return a.length > b.length ? a : b;
}
);
Otherwise, a safe alternative:
var longest = arr.sort(
function (a, b) {
return b.length - a.length;
}
)[0];
My understanding is that HEAD points the current branch, while ORIG_HEAD is used to store the previous HEAD before doing "dangerous" operations.
For example git-rebase and git-am record the original tip of branch before they apply any changes.
I found that you don't necessarily need the text vertically centred, it also looks good near the bottom of the row, it's only when it's at the top (or above centre?) that it looks wrong. So I went with this to push the links to the bottom of the row:
.navbar-brand {
min-height: 80px;
}
@media (min-width: 768px) {
#navbar-collapse {
position: absolute;
bottom: 0px;
left: 250px;
}
}
My brand image is SVG and I used height: 50px; width: auto
which makes it about 216px wide. It spilled out of its container vertically so I added the min-height: 80px;
to make room for it plus bootstrap's 15px margins. Then I tweaked the navbar-collapse
's left
setting until it looked right.
The point seems to be that sometimes, you need a property that has automatic storage and some behavior, for instance to notify other objects that the property just changed. When all you have is get
/set
, you need another field to hold the value. With willSet
and didSet
, you can take action when the value is modified without needing another field. For instance, in that example:
class Foo {
var myProperty: Int = 0 {
didSet {
print("The value of myProperty changed from \(oldValue) to \(myProperty)")
}
}
}
myProperty
prints its old and new value every time it is modified. With just getters and setters, I would need this instead:
class Foo {
var myPropertyValue: Int = 0
var myProperty: Int {
get { return myPropertyValue }
set {
print("The value of myProperty changed from \(myPropertyValue) to \(newValue)")
myPropertyValue = newValue
}
}
}
So willSet
and didSet
represent an economy of a couple of lines, and less noise in the field list.
Ok after having sunk way to much time into this problem this is the way I managed to get the appearance I was hoping for. I'm making it a separate answer so I can get everything in one place.
It's a combination of factors.
Firstly, don't try to get the toolbars to play nice through just themes. It seems to be impossible.
So apply themes explicitly to your Toolbars like in oRRs answer
layout/toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:theme="@style/Dark.Overlay"
app:popupTheme="@style/Dark.Overlay.LightPopup" />
However this is the magic sauce. In order to actually get the background colors I was hoping for you have to override the background
attribute in your Toolbar themes
values/styles.xml:
<!--
I expected android:colorBackground to be what I was looking for but
it seems you have to override android:background
-->
<style name="Dark.Overlay" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:background">?attr/colorPrimary</item>
</style>
<style name="Dark.Overlay.LightPopup" parent="ThemeOverlay.AppCompat.Light">
<item name="android:background">@color/material_grey_200</item>
</style>
then just include your toolbar layout in your other layouts
<include android:id="@+id/mytoolbar" layout="@layout/toolbar" />
and you're good to go.
Hope this helps someone else so you don't have to spend as much time on this as I have.
(if anyone can figure out how to make this work using just themes, ie not having to apply the themes explicitly in the layout files I'll gladly support their answer instead)
EDIT:
So apparently posting a more complete answer was a downvote magnet so I'll just accept the imcomplete answer above but leave this answer here in case someone actually needs it. Feel free to keep downvoting if it makes you happy though.
This was inspired by using Sets as indexers in Delphi, way back when:
/// Example of using a Boolean indexed property
/// to manipulate a [Flags] enum:
public class BindingFlagsIndexer
{
BindingFlags flags = BindingFlags.Default;
public BindingFlagsIndexer()
{
}
public BindingFlagsIndexer( BindingFlags value )
{
this.flags = value;
}
public bool this[BindingFlags index]
{
get
{
return (this.flags & index) == index;
}
set( bool value )
{
if( value )
this.flags |= index;
else
this.flags &= ~index;
}
}
public BindingFlags Value
{
get
{
return flags;
}
set( BindingFlags value )
{
this.flags = value;
}
}
public static implicit operator BindingFlags( BindingFlagsIndexer src )
{
return src != null ? src.Value : BindingFlags.Default;
}
public static implicit operator BindingFlagsIndexer( BindingFlags src )
{
return new BindingFlagsIndexer( src );
}
}
public static class Class1
{
public static void Example()
{
BindingFlagsIndexer myFlags = new BindingFlagsIndexer();
// Sets the flag(s) passed as the indexer:
myFlags[BindingFlags.ExactBinding] = true;
// Indexer can specify multiple flags at once:
myFlags[BindingFlags.Instance | BindingFlags.Static] = true;
// Get boolean indicating if specified flag(s) are set:
bool flatten = myFlags[BindingFlags.FlattenHierarchy];
// use | to test if multiple flags are set:
bool isProtected = ! myFlags[BindingFlags.Public | BindingFlags.NonPublic];
}
}
For your question as asked
Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))
If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA
you can also quote string
''+document.location+''.substring(2,3);
To sure, you should use function to check is null and empty as below:
string str = ...
if (!String.IsNullOrEmpty(str))
{
...
}
For a simple use of slice
, use my extension to Array Class:
Array.prototype.subarray = function(start, end) {
if (!end) { end = -1; }
return this.slice(start, this.length + 1 - (end * -1));
};
Then:
var bigArr = ["a", "b", "c", "fd", "ze"];
Test1:
bigArr.subarray(1, -1);
< ["b", "c", "fd", "ze"]
Test2:
bigArr.subarray(2, -2);
< ["c", "fd"]
Test3:
bigArr.subarray(2);
< ["c", "fd","ze"]
Might be easier for developers coming from another language (i.e. Groovy).
Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:
IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations
The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.
I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.
I will soon released a new version of my app to support to galaxy ace.
You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree
In order to solve your problem you should do this:
this._camera = Camera.open();
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);
params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);
don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true
to turn off the led just release the camera
Using the examples from Sohnee and karim79. I tested this and it worked in both FF3.6 and IE6.
<script type="text/javascript">
$(document).ready(function(){
$("#logo").bind("load", function () { $(this).fadeIn('slow'); });
});
</script>
<img src="http://www.gimp.org/tutorials/Lite_Quickies/quintet_hst_big.jpg" id="logo" style="display:none"/>
Since one div is initially hidden, you can simply call toggle for both divs:
<a href="javascript:void(0);" id="forgot-password">forgot password?</a>
<div id="login-form">login form</div>
<div id="recover-password" style="display:none;">recover password</div>
<script type="text/javascript">
$(function(){
$('#forgot-password').click(function(){
$('#login-form').toggle();
$('#recover-password').toggle();
});
});
</script>
DF[ ! ( ( DF$sub ==1 & DF$day==2) | ( DF$sub ==3 & DF$day==4) ) , ] # note the ! (negation)
Or if sub is a factor as suggested by your use of quotes:
DF[ ! paste(sub,day,sep="_") %in% c("1_2", "3_4"), ]
Could also use subset:
subset(DF, ! paste(sub,day,sep="_") %in% c("1_2", "3_4") )
(And I endorse the use of which
in Dirk's answer when using "[" even though some claim it is not needed.)
Use a HashSet
along with your List
:
List<string> myList = new List<string>();
HashSet<string> myHashSet = new HashSet<string>();
public void addToList(string s) {
if (myHashSet.Add(s)) {
myList.Add(s);
}
}
myHashSet.Add(s)
will return true
if s
is not exist in it.
How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:
Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.
Trying http://0.0.0.0:3000/routes
on a Rails 5 API app (i.e.: JSON-only oriented) will (as of Rails beta 3) return
{"status":404,"error":"Not Found","exception":"#>
<ActionController::RoutingError:...
However, http://0.0.0.0:3000/rails/info/routes
will render a nice, simple HTML page with routes.
Defining array with multiple types in TypeScript
Use a union type (string|number)[]
demo:
const foo: (string|number)[] = [ 1, "message" ];
I have an array of the form: [ 1, "message" ].
If you are sure that there are always only two elements [number, string]
then you can declare it as a tuple:
const foo: [number, string] = [ 1, "message" ];
I was surprised to learn, and so I had to come back here and report, that the excellent and well maintained Interconnect/it SAFE SEARCH AND REPLACE ON DATABASE script has some options for converting tables to utf8 / unicode, and even to convert to innodb. It's a script commonly used to migrate a database driven website (Wordpress, Drupal, Joomla, etc) from one domain to another.
For Apache 2.4.2: I was getting 403: Forbidden continuously when I was trying to access WAMP on my Windows 7 desktop from my iPhone on WiFi. On one blog, I found the solution - add Require all granted after Allow all in the <Directory> section. So this is how my <Directory> section looks like inside <VirtualHost>
<Directory "C:/wamp/www">
Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted
</Directory>
For completeness, also look into the local storage capabilities & sessionStorage of HTML5. These are supported in the latest versions of all modern browsers, and are much easier to use and less fiddly than cookies.
http://www.w3.org/TR/2009/WD-webstorage-20091222/
https://www.w3.org/TR/webstorage/. (second edition)
Here are some sample code for setting and getting the values using sessionStorage and localStorage :
// HTML5 session Storage
sessionStorage.setItem("variableName","test");
sessionStorage.getItem("variableName");
//HTML5 local storage
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");
It is the ternary conditional operator.
If the condition in the parenthesis before the ?
is true, it returns the value to the left of the :
, otherwise the value to the right.
'ftl' stands for freemarker. It combines server side objects and view side (HTML/JQuery) contents into a single viewable template on the client browser.
Some documentation which might help:
Tutorials:
http://www.vogella.com/tutorials/FreeMarker/article.html
http://viralpatel.net/blogs/freemaker-template-hello-world-tutorial/
Old post but this is exactly what I needed, simple question, how to change it to count column rather than Row. Thankyou in advance. Novice to Excel.
=SUM(A1:INDIRECT(CONCATENATE("A",C5)))
I.e My data is A1 B1 C1 D1 etc rather then A1 A2 A3 A4.
You don't need a for loop in your code.
Here is how you can re implement your method
Edit:
Here is hint for you to proceed, Following code snippet gives int
values for char
s
System.out.println("a="+(int)'a');
System.out.println("z="+(int)'z');
System.out.println("A="+(int)'A');
System.out.println("Z="+(int)'Z');
Output
a=97
z=122
A=65
Z=90
Here is how you can check if a number x
exists between two numbers say a
and b
// x greater than or equal to a and x less than or equal to b
if ( x >= a && x <= b )
During comparisons char
s can be treated as numbers
If you can combine these hints, you should be able to find what you want ;)
Based on @YackY answer shorter recursion version:
function createFormData(formData, key, data) {
if (data === Object(data) || Array.isArray(data)) {
for (var i in data) {
createFormData(formData, key + '[' + i + ']', data[i]);
}
} else {
formData.append(key, data);
}
}
Usage example:
var data = {a: '1', b: 2, c: {d: '3'}};
var formData = new FormData();
createFormData(formData, 'data', data);
Sent data:
data[a]=1&
data[b]=2&
data[c][d]=3
This worked for me : http://tecadmin.net/fatal-ident-authentication-failed-for-user-postgres/#
local all postgres trust
local all myapp_usr trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
#host all all ::1/128 trust
Mates,
I stumbled upon this error today while testing a simple script. I am not using "class" function though so it take it with grain of salt. I was calling function before its definition & declaration ...something like this
try{
foo();
}
catch (exception $e)
{
echo "$e->getMessage()";
}
function foo(){
echo "blah blah blah";
}
so php was throwing me error "call to undefined function ".
This kinda seem classic programming error but may help someone in need of clue.
You want nohup. See http://nixcraft.com/linux-software/313-ssh-nohup-connection.html
To skip the first element in Python you can simply write
for car in cars[1:]:
# Do What Ever you want
or to skip the last elem
for car in cars[:-1]:
# Do What Ever you want
You can use this concept for any sequence.
Try this..
Download the Sqlite Manager jar file here.
Add it to your eclipse > dropins Directory.
Restart eclipse.
Launch the compatible emulator or device
Run your application.
Go to Window > Open Perspective > DDMS >
Choose the running device.
Go to File Explorer tab.
Select the directory called databases under your application's package.
Select the .db file under the database directory.
Then click Sqlite manager icon like this .
Now you're able to see the .db file.
Happy coding.....
I know it's late, but I take the original code and change some stuff to control easily the css. So I made a code with the addClass() and the removeClass()
Here the full code : http://jsfiddle.net/e5qaD/4837/
if( bottom_of_window > bottom_of_object ){
$(this).addClass('showme');
}
if( bottom_of_window < bottom_of_object ){
$(this).removeClass('showme');
WAMP [ Windows, Apache, Mysql, Php]
XAMPP [X-os, Apache, Mysql, Php , Perl ] (x-os : it can be used on any OS )
Both can be used to easily run and test websites and web applications locally. WAMP cannot be run parallel with XAMPP because with default installation XAMPP gets priority and it takes up ports.
WAMP easy to setup configuration in. WAMPServer has a graphical user interface to switch on or off individual component softwares while it is running. WAMPServer provide an option to switch among many versions of Apache, many versions of PHP and many versions of MySQL all installed which provide more flexibility towards developing while XAMPPServer doesn't have such an option. If you want to use Perl with WAMP you can configure Perl with WAMPServer http://phpflow.com/perl/how-to-configure-perl-on-wamp/ but it is better to go with XAMPP.
XAMPP is easy to use than WAMP. XAMPP is more powerful. XAMPP has a control panel from that you can start and stop individual components (such as MySQL,Apache etc.). XAMPP is more resource consuming than WAMP because of heavy amount of internal component softwares like Tomcat , FileZilla FTP server, Webalizer, Mercury Mail etc.So if you donot need high features better to go with WAMP. XAMPP also has SSL feature which WAMP doesn't.(Secure Sockets Layer (SSL) is a networking protocol that manages server authentication, client authentication and encrypted communication between servers and clients. )
IIS acronym for Internet Information Server also an extensible web server initiated as a research project for for Microsoft NT.IIS can be used for making Web applications, search engines, and Web-based applications that access databases such as SQL Server within Microsoft OSs. . IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.
According to the java.io.File
Java Docs
The default temporary-file directory is specified by the system property java.io.tmpdir. On UNIX systems the default value of this property is typically "/tmp" or "/var/tmp"; on Microsoft Windows systems it is typically "c:\temp". A different value may be given to this system property when the Java virtual machine is invoked, but programmatic changes to this property are not guaranteed to have any effect upon the the temporary directory used by this method.
To specify the java.io.tmpdir
System property, you can invoke the JVM as follows:
java -Djava.io.tmpdir=/path/to/tmpdir
By default this value should come from the TMP
environment variable on Windows systems
For instances where running a local webserver is not an option, you can allow Chrome access to file://
files via a browser switch. After some digging, I found this discussion, which mentions a browser switch in opening post. Run your Chrome instance with:
chrome.exe --allow-file-access-from-files
This may be acceptable for development environments, but little else. You certainly don't want this on all the time. This still appears to be an open issue (as of Jan 2011).
See also: Problems with jQuery getJSON using local files in Chrome
This is mine. http://jsfiddle.net/pd1vojsL/
3 draggable buttons in a div, dragging constrained by div.
<div id="parent" class="parent">
<button id="button1" class="button">Drag me</button>
<button id="button2" class="button">Drag me</button>
<button id="button3" class="button">Drag me</button>
</div>
<div id="log1"></div>
<div id="log2"></div>
Requires JQuery (only):
$(function() {
$('.button').mousedown(function(e) {
if(e.which===1) {
var button = $(this);
var parent_height = button.parent().innerHeight();
var top = parseInt(button.css('top')); //current top position
var original_ypos = button.css('top','').position().top; //original ypos (without top)
button.css({top:top+'px'}); //restore top pos
var drag_min_ypos = 0-original_ypos;
var drag_max_ypos = parent_height-original_ypos-button.outerHeight();
var drag_start_ypos = e.clientY;
$('#log1').text('mousedown top: '+top+', original_ypos: '+original_ypos);
$(window).on('mousemove',function(e) {
//Drag started
button.addClass('drag');
var new_top = top+(e.clientY-drag_start_ypos);
button.css({top:new_top+'px'});
if(new_top<drag_min_ypos) { button.css({top:drag_min_ypos+'px'}); }
if(new_top>drag_max_ypos) { button.css({top:drag_max_ypos+'px'}); }
$('#log2').text('mousemove min: '+drag_min_ypos+', max: '+drag_max_ypos+', new_top: '+new_top);
//Outdated code below (reason: drag contrained too early)
/*if(new_top>=drag_min_ypos&&new_top<=drag_max_ypos) {
button.css({top:new_top+'px'});
}*/
});
$(window).on('mouseup',function(e) {
if(e.which===1) {
//Drag finished
$('.button').removeClass('drag');
$(window).off('mouseup mousemove');
$('#log1').text('mouseup');
$('#log2').text('');
}
});
}
});
});
If [John Smith]
is in cell A1, then use this formula to do what you want:
=SUBSTITUTE(SUBSTITUTE(A1, "[", ""), "]", "")
The inner SUBSTITUTE replaces all instances of "[" with "" and returns a new string, then the other SUBSTITUTE replaces all instances of "]" with "" and returns the final result.
Here is what I have implemented.
function summaryMode($text, $limit, $link) {
if (str_word_count($text, 0) > $limit) {
$numwords = str_word_count($text, 2);
$pos = array_keys($numwords);
$text = substr($text, 0, $pos[$limit]).'... <a href="'.$link.'">Read More</a>';
}
return $text;
}
As you can see it is based off karim79's answer, all that needed changing was that the if statement also needed to check against words not characters.
I also added a link to main function for convenience. So far it hsa worked flawlessly. Thanks to the original solution provider.
Even though some of you may mark this as a duplicate and get upset that I am copying someone else's answer, I would REALLY like to highlight an aspect of Mr. Napik's response. Because I missed this, I caused nationwide website downtime (9min). If only someone shared this information, I could have prevented it!
Here is his code:
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='tiger',
host='127.0.0.1',
database='employees')
try:
cursor = cnx.cursor()
cursor.execute("""select 3 from your_table""")
result = cursor.fetchall()
print(result)
finally:
cnx.close()
The important thing here is the Try and Finally clause. This allows connections to ALWAYS be closed, regardless of what happens in the cursor/sqlstatement portion of the code. A lot of active connections cause DBLoadNoCPU to spike and could crash a db server.
I hope this warning helps to save servers and ultimately jobs! :D
It doesn't look like the Rails API exposes methods to do this generically. You could try accessing the underlying connection and using it's methods, e.g. for MySQL:
st = ActiveRecord::Base.connection.raw_connection.prepare("update table set f1=? where f2=? and f3=?")
st.execute(f1, f2, f3)
st.close
I'm not sure if there are other ramifications to doing this (connections left open, etc). I would trace the Rails code for a normal update to see what it's doing aside from the actual query.
Using prepared queries can save you a small amount of time in the database, but unless you're doing this a million times in a row, you'd probably be better off just building the update with normal Ruby substitution, e.g.
ActiveRecord::Base.connection.execute("update table set f1=#{ActiveRecord::Base.sanitize(f1)}")
or using ActiveRecord like the commenters said.
Get a substring after the last index of /
.
var url = 'http://www.site.com/234234234';
var id = url.substring(url.lastIndexOf('/') + 1);
alert(id); // 234234234
It's just basic JavaScript, no jQuery involved.
I presume you mean via SSMS?
For a SQL Server Instance:
SELECT SERVERPROPERTY('productversion'),
SERVERPROPERTY ('productlevel'),
SERVERPROPERTY ('edition')
For a SQL Server Installation:
Select @@Version
You can fetch the parent class by adding the line below. If you had an id, it would be easier with getElementById
. Nonetheless,
var parentNode = document.getElementsByClassName("progress__container")[0];
Then you can use querySelectorAll
on the parent <div>
to fetch all matching div
s with class .progress__marker
var progressNodes = progressContainer.querySelectorAll('.progress__marker');
querySelectorAll
will fetch every div
with the class of progress__marker
This has only been tested on Windows:
You can do the following:
import os
os.startfile("C:/Users/TestFile.txt", "print")
This will start the file, in its default opener, with the verb 'print', which will print to your default printer.Only requires the os
module which comes with the standard library
DROP EVENT IF EXISTS xxxEVENTxxx;
CREATE EVENT xxxEVENTxxx
ON SCHEDULE
EVERY 1 DAY
STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
DO
--process;
¡IMPORTANT!->
SET GLOBAL event_scheduler = ON;
Stop using (HTTP 1.0) | Replaced with (HTTP 1.1 since 1999) |
---|---|
Expires: [date] | Cache-Control: max-age=[seconds] |
Pragma: no-cache | Cache-Control: no-cache |
If it's after 1999, and you're still using Expires or Pragma, you're doing it wrong.
I'm looking at you Stackoverflow:
200 OK Pragma: no-cache Content-Type: application/json X-Frame-Options: SAMEORIGIN X-Request-Guid: a3433194-4a03-4206-91ea-6a40f9bfd824 Strict-Transport-Security: max-age=15552000 Content-Length: 54 Accept-Ranges: bytes Date: Tue, 03 Apr 2018 19:03:12 GMT Via: 1.1 varnish Connection: keep-alive X-Served-By: cache-yyz8333-YYZ X-Cache: MISS X-Cache-Hits: 0 X-Timer: S1522782193.766958,VS0,VE30 Vary: Fastly-SSL X-DNS-Prefetch-Control: off Cache-Control: private
tl;dr: Pragma
is a legacy of HTTP/1.0 and hasn't been needed since Internet Explorer 5, or Netscape 4.7. Unless you expect some of your users to be using IE5: it's safe to stop using it.
[date]
(deprecated - HTTP 1.0)[seconds]
And the conditional requests:
Etag: W/“1d2e7–1648e509289”
If-None-Match: W/“1d2e7–1648e509289”
304 Not Modified
last-modified: Thu, 09 May 2019 19:15:47 GMT
If-Modified-Since: Fri, 13 Jul 2018 10:49:23 GMT
304 Not Modified
last-modified: Thu, 09 May 2019 19:15:47 GMT
Recently I learned of the following syntax:
DELETE (SELECT *
FROM productfilters pf
INNER JOIN product pr
ON pf.productid = pr.id
WHERE pf.id >= 200
AND pr.NAME = 'MARK')
I think it looks much cleaner then other proposed code.
I had this problem in a DataFrame (df
) created from an Excel-sheet with several internal header rows.
After cleaning out the internal header rows from df
, the columns' values were of "non-null object" type (DataFrame.info()
).
This code converted all numerical values of multiple columns to int64 and float64 in one go:
for i in range(0, len(df.columns)):
df.iloc[:,i] = pd.to_numeric(df.iloc[:,i], errors='ignore')
# errors='ignore' lets strings remain as 'non-null objects'
Just echo your content after sending the header.
header('HTTP/1.0 403 Forbidden');
echo 'You are forbidden!';
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
I think you can create expression to show or hide
<div ng-app>
<div ng-controller="MyCtrl">
<div><button id="mybutton" ng-click="myvalue = myvalue == true ? false : true;">Click me</button></div>
<div>Value: {{myvalue}}</div>
<div><div ng-show="myvalue" class="hideByDefault">Here I am</div></div>
</div>
</div>
The passwords cannot be decrypted as will makes a vulnerability for users. So, you can simply use password_verify()
method to compare the passwords.
if(password_verify($upass, $userRow['user_pass'])){
//code for redirecting to login screen }
where, $upass
is password entered by user and $userRow['user_pass']
is user_pass field in database which is encrypted by password_hash()
function.
What Ruby has over Python are its scripting language capabilities. Scripting language in this context meaning to be used for "glue code" in shell scripts and general text manipulation.
These are mostly shared with Perl. First-class built-in regular expressions, $-Variables, useful command line options like Perl (-a, -e) etc.
Together with its terse yet epxressive syntax it is perfect for these kind of tasks.
Python to me is more of a dynamically typed business language that is very easy to learn and has a neat syntax. Not as "cool" as Ruby but neat. What Python has over Ruby to me is the vast number of bindings for other libs. Bindings to Qt and other GUI libs, many game support libraries and and and. Ruby has much less. While much used bindings e.g. to Databases are of good quality I found niche libs to be better supported in Python even if for the same library there is also a Ruby binding.
So, I'd say both languages have its use and it is the task that defines which one to use. Both are easy enough to learn. I use them side-by-side. Ruby for scripting and Python for stand-alone apps.
You can do it in two different ways.
Option 1: The -eq
operator
>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False
Option 2: The .Equals()
method of the string
object. Because strings in PowerShell are .Net System.String
objects, any method of that object can be called directly.
>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method
List of System.String
methods follows.
I’ve made a small gem that can alleviate the need to manually delete associated records in some circumstances.
This gem adds a new option for ActiveRecord associations:
dependent: :delete_recursively
When you destroy a record, all records that are associated using this option will be deleted recursively (i.e. across models), without instantiating any of them.
Note that, just like dependent: :delete or dependent: :delete_all, this new option does not trigger the around/before/after_destroy callbacks of the dependent records.
However, it is possible to have dependent: :destroy associations anywhere within a chain of models that are otherwise associated with dependent: :delete_recursively. The :destroy option will work normally anywhere up or down the line, instantiating and destroying all relevant records and thus also triggering their callbacks.
was implemented that in service-now platform. No need to use other library - makepdf have all you need!
that my html part (include preloder gif):
<div class="pdf-preview" ng-init="generatePDF(true)">
<object data="{{c.content}}" type="application/pdf" style="width:58vh;height:88vh;" ng-if="c.content" ></object>
<div ng-if="!c.content">
<img src="https://support.lenovo.com/esv4/images/loading.gif" width="50" height="50">
</div>
</div>
this is client script (js part)
$scope.generatePDF = function (preview) {
docDefinition = {} //you rootine to generate pdf content
//...
if (preview) {
pdfMake.createPdf(docDefinition).getDataUrl(function(dataURL) {
c.content = dataURL;
});
}
}
So on page load I fire init function that generate pdf content and if required preview (set as true) result will be assigned to c.content variable. On html side object will be not shown until c.content will got a value, so that will show loading gif.
I experienced this exact same issue. For me, the OPTIONS request would go through, but the POST request would say "aborted." This led me to believe that the browser was never making the POST request at all. Chrome said something like "Caution provisional headers are shown" in the request headers but no response headers were shown. In the end I turned to debugging on Firefox which led me to find out my server was responding with an error and no CORS headers were present on the response. Chrome was actually receiving the response, but not allowing the response to be shown in the network view.
This is a question with a simple answer and a long-winded answer.
The simple answer is the heap. Classes and all of the data applying to classes (not instance data) is stored in the Permanent Generation section of the heap.
The long answer is already on stack overflow:
There is a thorough description of memory and garbage collection in the JVM as well as an answer that talks more concisely about it.
Probably somewhere you have DBconnection->close();
and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close();
in __destruct()
(because __destruct
is event, after which there will be a need for execution of queries)
The command:
mvn install:install-file
Typically installs the artifact in your local repository, so you shouldn't need to download it. However, if you want to share your artifact with others, you will need to deploy the artifact to a central repository see the deploy plugin for more details.
Additionally adding a dependency to your POM will automatically fetch any third-party artifacts you need when you build your project. I.e. This will download the artifact from the central repository.
Choice one! But the first is very simple. The last maybe util for file manipulation:
//Method 1 (I like this)
File.AppendAllLines(
"FileAppendAllLines.txt",
new string[] { "line1", "line2", "line3" });
//Method 2
File.AppendAllText(
"FileAppendAllText.txt",
"line1" + Environment.NewLine +
"line2" + Environment.NewLine +
"line3" + Environment.NewLine);
//Method 3
using (StreamWriter stream = File.AppendText("FileAppendText.txt"))
{
stream.WriteLine("line1");
stream.WriteLine("line2");
stream.WriteLine("line3");
}
//Method 4
using (StreamWriter stream = new StreamWriter("StreamWriter.txt", true))
{
stream.WriteLine("line1");
stream.WriteLine("line2");
stream.WriteLine("line3");
}
//Method 5
using (StreamWriter stream = new FileInfo("FileInfo.txt").AppendText())
{
stream.WriteLine("line1");
stream.WriteLine("line2");
stream.WriteLine("line3");
}
This is not a matter of accuracy, nor is it a matter of precision. It is a matter of meeting the expectations of humans who use base 10 for calculations instead of base 2. For example, using doubles for financial calculations does not produce answers that are "wrong" in a mathematical sense, but it can produce answers that are not what is expected in a financial sense.
Even if you round off your results at the last minute before output, you can still occasionally get a result using doubles that does not match expectations.
Using a calculator, or calculating results by hand, 1.40 * 165 = 231 exactly. However, internally using doubles, on my compiler / operating system environment, it is stored as a binary number close to 230.99999... so if you truncate the number, you get 230 instead of 231. You may reason that rounding instead of truncating would have given the desired result of 231. That is true, but rounding always involves truncation. Whatever rounding technique you use, there are still boundary conditions like this one that will round down when you expect it to round up. They are rare enough that they often will not be found through casual testing or observation. You may have to write some code to search for examples that illustrate outcomes that do not behave as expected.
Assume you want to round something to the nearest penny. So you take your final result, multiply by 100, add 0.5, truncate, then divide the result by 100 to get back to pennies. If the internal number you stored was 3.46499999.... instead of 3.465, you are going to get 3.46 instead 3.47 when you round the number to the nearest penny. But your base 10 calculations may have indicated that the answer should be 3.465 exactly, which clearly should round up to 3.47, not down to 3.46. These kinds of things happen occasionally in real life when you use doubles for financial calculations. It is rare, so it often goes unnoticed as an issue, but it happens.
If you use base 10 for your internal calculations instead of doubles, the answers are always exactly what is expected by humans, assuming no other bugs in your code.
You can get the ID, or any other attribute, using jQuery's attrib function.
$('ul.art-vmenu li').attrib('id');
To get the menu text, which is in the t span, you can do this:
$('ul.art-vmenu li').children('span.t').html();
To change the HTML is just as easy:
$('ul.art-vmenu li').children('span.t').html("I'm different");
Of course, if you wanted to get all the span.t's in the first place, it would be simpler to do:
$('ul.art-vemnu li span.t').html();
But I'm assuming you've already got the li's, and want to use child() to find something within that element.
I think you want this syntax:
ALTER TABLE tb_TableName
add constraint cnt_Record_Status Default '' for Record_Status
Based on some of your comments, I am going to guess that you might already have null
values in your table which is causing the alter of the column to not null
to fail. If that is the case, then you should run an UPDATE
first. Your script will be:
update tb_TableName
set Record_Status = ''
where Record_Status is null
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL
ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status
So, what's wrong with checking each element iteratively?
function arraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length)
return false;
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}
return true;
}
if you want to use icons from any icon font library, you can try this in the option while calling the slider in your js file.
prevArrow: '<div class="class-to-style"><span class="fa fa-angle-left"></span><span class="sr-only">Prev</span></div>',
nextArrow: '<div class="class-to-style"><span class="fa fa-angle-right"></span><span class="sr-only">Next</span></div>'
Here "fa" comes from FontAwesome icon font library.
You want to use iteritems. This returns an iterator over the dictionary, which gives you a tuple(key, value)
>>> for field, values in fields.iteritems():
... print field, values
...
first_names ['foo', 'bar']
last_name ['gravy', 'snowman']
Your problem was that you were looping over fields, which returns the keys of the dictionary.
>>> for field in fields:
... print field
...
first_names
last_name
You're probably targeting the Client Profile, in which System.Web.dll
is not available.
You can target the full framework in project's Properties.
TL;DR:
No, don't subscribe manually to them, don't use them in services. Use them as is shown in the documentation only to emit events in components. Don't defeat angular's abstraction.
Answer:
EventEmitter is an angular2 abstraction and its only purpose is to emit events in components. Quoting a comment from Rob Wormald
[...] EventEmitter is really an Angular abstraction, and should be used pretty much only for emitting custom Events in components. Otherwise, just use Rx as if it was any other library.
This is stated really clear in EventEmitter's documentation.
Use by directives and components to emit custom Events.
Angular2 will never guarantee us that EventEmitter will continue being an Observable. So that means refactoring our code if it changes. The only API we must access is its emit()
method. We should never subscribe manually to an EventEmitter.
All the stated above is more clear in this Ward Bell's comment (recommended to read the article, and the answer to that comment). Quoting for reference
Do NOT count on EventEmitter continuing to be an Observable!
Do NOT count on those Observable operators being there in the future!
These will be deprecated soon and probably removed before release.
Use EventEmitter only for event binding between a child and parent component. Do not subscribe to it. Do not call any of those methods. Only call
eve.emit()
His comment is in line with Rob's comment long time ago.
Simply use it to emit events from your component. Take a look a the following example.
@Component({
selector : 'child',
template : `
<button (click)="sendNotification()">Notify my parent!</button>
`
})
class Child {
@Output() notifyParent: EventEmitter<any> = new EventEmitter();
sendNotification() {
this.notifyParent.emit('Some value to send to the parent');
}
}
@Component({
selector : 'parent',
template : `
<child (notifyParent)="getNotification($event)"></child>
`
})
class Parent {
getNotification(evt) {
// Do something with the notification (evt) sent by the child!
}
}
class MyService {
@Output() myServiceEvent : EventEmitter<any> = new EventEmitter();
}
Stop right there... you're already wrong...
Hopefully these two simple examples will clarify EventEmitter's proper usage.
That would be the item property: http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx
Maybe something like this would work:
public T Item[int index, int y]
{
//Then do whatever you need to return/set here.
get; set;
}
I believe you need to specify "Option Infer On" for this to work.
Option Infer allows the compiler to make a guess at what is being represented by your code, thus it will guess that {"stuff"} is an array of strings. With "Option Infer Off", {"stuff"} won't have any type assigned to it, ever, and so it will always fail, without a type specifier.
Option Infer is, I think On by default in new projects, but Off by default when you migrate from earlier frameworks up to 3.5.
Opinion incoming:
Also, you mention that you've got "Option Explicit Off". Please don't do this.
Setting "Option Explicit Off" means that you don't ever have to declare variables. This means that the following code will silently and invisibly create the variable "Y":
Dim X as Integer
Y = 3
This is horrible, mad, and wrong. It creates variables when you make typos. I keep hoping that they'll remove it from the language.
You might read up on FILESTREAM. Here is some info from the docs that should help you decide:
If the following conditions are true, you should consider using FILESTREAM:
- Objects that are being stored are, on average, larger than 1 MB.
- Fast read access is important.
- You are developing applications that use a middle tier for application logic.
For smaller objects, storing varbinary(max) BLOBs in the database often provides better streaming performance.
I thought I'd use an answer from this question but I couldn't, so here is my answer. It is using a modified version of an answer in Structure and Interpretation of Computer Programs. I think this is a better recursive solution and should please the purists more.
My answer is in Scala (and apologies if my Scala sucks, I've just started learning it). The findSumCombinations craziness is to sort and unique the original list for the recursion to prevent dupes.
def findSumCombinations(target: Int, numbers: List[Int]): Int = {
cc(target, numbers.distinct.sortWith(_ < _), List())
}
def cc(target: Int, numbers: List[Int], solution: List[Int]): Int = {
if (target == 0) {println(solution); 1 }
else if (target < 0 || numbers.length == 0) 0
else
cc(target, numbers.tail, solution)
+ cc(target - numbers.head, numbers, numbers.head :: solution)
}
To use it:
> findSumCombinations(12345, List(1,5,22,15,0,..))
* Prints a whole heap of lists that will sum to the target *
Depending on your version of postgresql you might run into a bug, that makes pg_stat_activity
to omit active connections from dropped users. These connections are also not shown inside pgAdminIII.
If you are doing automatic testing (in which you also create users) this might be a probable scenario.
In this case you need to revert to queries like:
SELECT pg_terminate_backend(procpid)
FROM pg_stat_get_activity(NULL::integer)
WHERE datid=(SELECT oid from pg_database where datname = 'your_database');
NOTE: In 9.2+ you'll have change procpid
to pid
.
Do this:
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/check" <!--check.xml-->
android:layout_margin="10dp"
android:textOn=""
android:textOff=""
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_centerVertical="true"/>
create check.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/unselected_image"
android:state_checked="false"/>
</selector>
The current cookie specification is RFC 6265, which replaces RFC 2109 and RFC 2965 (both RFCs are now marked as "Historic") and formalizes the syntax for real-world usages of cookies. It clearly states:
- Introduction
...
For historical reasons, cookies contain a number of security and privacy infelicities. For example, a server can indicate that a given cookie is intended for "secure" connections, but the Secure attribute does not provide integrity in the presence of an active network attacker. Similarly, cookies for a given host are shared across all the ports on that host, even though the usual "same-origin policy" used by web browsers isolates content retrieved via different ports.
And also:
8.5. Weak Confidentiality
Cookies do not provide isolation by port. If a cookie is readable by a service running on one port, the cookie is also readable by a service running on another port of the same server. If a cookie is writable by a service on one port, the cookie is also writable by a service running on another port of the same server. For this reason, servers SHOULD NOT both run mutually distrusting services on different ports of the same host and use cookies to store security sensitive information.
Series.apply(func, convert_dtype=True, args=(), **kwds)
args : tuple
x = my_series.apply(my_function, args = (arg1,))
Don't use tellg
to determine the exact size of the file. The length determined by tellg
will be larger than the number of characters can be read from the file.
From stackoverflow question tellg() function give wrong size of file? tellg
does not report the size of the file, nor the offset from the beginning in bytes. It reports a token value which can later be used to seek to the same place, and nothing more. (It's not even guaranteed that you can convert the type to an integral type.). For Windows (and most non-Unix systems), in text mode, there is no direct and immediate mapping between what tellg returns and the number of bytes you must read to get to that position.
If it is important to know exactly how many bytes you can read, the only way of reliably doing so is by reading. You should be able to do this with something like:
#include <fstream>
#include <limits>
ifstream file;
file.open(name,std::ios::in|std::ios::binary);
file.ignore( std::numeric_limits<std::streamsize>::max() );
std::streamsize length = file.gcount();
file.clear(); // Since ignore will have set eof.
file.seekg( 0, std::ios_base::beg );
You can also use file_put_contents()
:
file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);
michael's suggestions works like a charm for me :) If you replace $http.post with $http.get, remember that the .get method accepts 2 parameters instead of 3... this is where is wasted my time... ;)
controller:
$http.get('/getdoc/' + $stateParams.id,
{responseType:'arraybuffer'})
.success(function (response) {
var file = new Blob([(response)], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
view:
<object ng-show="content" data="{{content}}" type="application/pdf" style="width: 100%; height: 400px;"></object>
from rest_framework import status
from rest_framework.response import Response
class FileUpload(APIView):
def put(request):
try:
file = request.FILES['filename']
#now upload to s3 bucket or your media file
except Exception as e:
print e
return Response(status,
status.HTTP_500_INTERNAL_SERVER_ERROR)
return Response(status, status.HTTP_200_OK)
Using the reshape package you can do something like this.
library(ggplot2)
wide <- data.frame(x = rnorm(100), eps = rnorm(100, 0, .2))
wide$first <- with(wide, 3 * x + eps)
wide$second <- with(wide, 2 * x + eps)
long <- melt(wide, id.vars = c("x", "eps"))
ggplot(long, aes(x = x, y = value)) + geom_smooth() + geom_point() + facet_grid(.~ variable)
Adding .
before \r\n
makes it work if the original string before \r\n
has no .
Other characters may work. I didn't try.
With or without the three lines including IsBodyHtml, not a matter.
Thast should be easy enough
if( myList.Any( s => s.Contains(stringToCheck))){
//do your stuff here
}
Create a table with column as type json
CREATE TABLE friends ( id serial primary key, data jsonb);
Now let's insert json data
INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');
Now let's make some queries to fetch data
select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;
You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])
name | work
------------+----------------------------
"Arya" | ["Improvements", "Office"]
"Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)
Now to retrieve only the values just use ->>
select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';
MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");
or
obj.getClass().getDeclaredConstructor(String.class).newInstance("HERESMYARG");
If you are using Facebook SDK, you don't need to bother yourself to enter anything for redirect URI on the app management page of facebook. Just setup a URL scheme for your iOS app. The URL scheme of your app should be a value "fbxxxxxxxxxxx" where xxxxxxxxxxx is your app id as identified on facebook. To setup URL scheme for your iOS app, go to info tab of your app settings and add URL Type.
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();
The best way is to use an And
clause in your While
statement
Dim count as Integer
count =0
While True And count <= 10
count=count+1
Debug.Print(count)
Wend
<a class="c1 c2">aa</a>
From the MySQL-manual:
This is equivalent to the expression (min <= expr AND expr <= max)
A cleaner alternative would be to use a Dictionary
to handle parameters. They are key-value pairs after all.
private static readonly HttpClient httpclient;
static MyClassName()
{
// HttpClient is intended to be instantiated once and re-used throughout the life of an application.
// Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.
// This will result in SocketException errors.
// https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
httpclient = new HttpClient();
}
var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);
var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
// Do something with response. Example get content:
// var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}
Also dont forget to Dispose()
httpclient, if you dont use the keyword using
As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.
Edit:
You may want to look into response.EnsureSuccessStatusCode();
instead of if (response.StatusCode == HttpStatusCode.OK)
.
You may want to keep your httpclient and dont Dispose()
it. See: Do HttpClient and HttpClientHandler have to be disposed?
Edit:
Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html
I dug deeper into this and found the best solutions are here.
http://blog.notdot.net/2010/07/Getting-unicode-right-in-Python
In my case I solved "UnicodeEncodeError: 'charmap' codec can't encode character "
original code:
print("Process lines, file_name command_line %s\n"% command_line))
New code:
print("Process lines, file_name command_line %s\n"% command_line.encode('utf-8'))
You can simply use take
method and index of element (Last index can be -1).
arr = np.array([1,2,3])
last = arr.take(-1)
# 3
After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:
10
but you want it to return a String and not a Fixnum, write '10'
or "10"
.:
, {
, }
, [
, ]
, ,
, &
, *
, #
, ?
, |
, -
, <
, >
, =
, !
, %
, @
, \
).'\n'
would be returned as the string \n
."\n"
would be returned as a line feed character.!ruby/sym
to return a Ruby symbol.Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.
Update
"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:
en:
yesno:
'yes': 'Yes'
'no': 'No'
Had the same issue in Chrome and it did not go away after applying all the known remedies. For me the resolution was to uncheck "Enable phishing and malware protection" in Chrome settings (Settings -> Show advanced settings -> Privacy). After that localhost is lightningfast.
Use a regular expression with the g
modifier:
var replaced = str.replace(/ /g, '+');
From Using Regular Expressions with JavaScript and ActionScript:
/g enables "global" matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one.
While it may work on some platforms, be aware that platform.architecture
is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on some OS X multi-architecture builds, the same executable file may be capable of running in either mode, as the example below demonstrates. The quickest safe multi-platform approach is to test sys.maxsize
on Python 2.6, 2.7, Python 3.x.
$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)
SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
if (charCode > 47 && charCode < 58) {
document.getElementById("error").innerHTML = "*Please Enter Your Name Only";
document.getElementById("fullname").focus();
document.getElementById("fullname").style.borderColor = 'red';
return false;
} else {
document.getElementById("error").innerHTML = "";
document.getElementById("fullname").style.borderColor = '';
return true;
}
Send a ajax request to your server like this in your js and get your result in success function.
jQuery.ajax({
url: "/rest/abc",
type: "GET",
contentType: 'application/json; charset=utf-8',
success: function(resultData) {
//here is your json.
// process it
},
error : function(jqXHR, textStatus, errorThrown) {
},
timeout: 120000,
});
at server side send response as json type.
And you can use jQuery.getJSON for your application.
The logic for both algorithms is quite similar. They both have a partially sorted sub-array in the beginning of the array. The only difference is how they search for the next element to be put in the sorted array.
Insertion sort: inserts the next element at the correct position;
Selection sort: selects the smallest element and exchange it with the current item;
Also, Insertion Sort is stable, as opposed to Selection Sort.
I implemented both in python, and it's worth noting how similar they are:
def insertion(data):
data_size = len(data)
current = 1
while current < data_size:
for i in range(current):
if data[current] < data[i]:
temp = data[i]
data[i] = data[current]
data[current] = temp
current += 1
return data
With a small change it is possible to make the Selection Sort algorithm.
def selection(data):
data_size = len(data)
current = 0
while current < data_size:
for i in range(current, data_size):
if data[i] < data[current]:
temp = data[i]
data[i] = data[current]
data[current] = temp
current += 1
return data
plt.imshow
just finishes drawing a picture instead of printing it. If you want to print the picture, you just need to add plt.show
.
I ran into this error trying to run the profiler, even though my connection had Trust server certificate checked and I added TrustServerCertificate=True
in the Advanced Section. I changed to an instance of SSMS running as administrator and the profiler started with no problem. (I previously had found that when my connections even to local took a long time to connect, running as administrator helped).
echo f | xcopy /s/y J:\"My Name"\"FILES IN TRANSIT"\JOHN20101126\"Missing file"\Shapes.atc C:\"Documents and Settings"\"His name"\"Application Data"\Autodesk\"AutoCAD 2010"\"R18.0"\enu\Support\Shapes.atc
if you have cygwin installed in the Windows Box, or using UNIX Shell then
Issue bash#which java
This will tell you whether java is in your classpath or NOT.
I am using the following code to write vertical text in a page. Firefox 3.5+, webkit, opera 10.5+ and IE
.rot-neg-90 {
-moz-transform:rotate(-270deg);
-moz-transform-origin: bottom left;
-webkit-transform: rotate(-270deg);
-webkit-transform-origin: bottom left;
-o-transform: rotate(-270deg);
-o-transform-origin: bottom left;
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
You got the order of the arguments to mysqli_select_db()
backwards. And mysqli_error()
requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.
Note also that with mysqli you can specify the DB in mysqli_connect()
:
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
die("Database connection failed: " . mysqli_connect_error();
}
You must use mysqli_connect_error()
, not mysqli_error()
, to get the error from mysqli_connect()
, since the latter requires you to supply a valid connection.
Compare Names containing apostrophe in DB through Java code
String sql="select lastname from employee where FirstName like '%"+firstName.trim().toLowerCase().replaceAll("'", "''")+"%'"
statement = conn.createStatement();
rs=statement.executeQuery(Sql);
iterate the results.
I've created a tiny utility called super-array where you can access items in an array by a unique identifier with O(1) complexity. Example:
const SuperArray = require('super-array');
const myArray = new SuperArray([
{id: 'ab1', name: 'John'},
{id: 'ab2', name: 'Peter'},
]);
console.log(myArray.get('ab1')); // {id: 'ab1', name: 'John'}
console.log(myArray.get('ab2')); // {id: 'ab2', name: 'Peter'}
Go to "Manage Jenkins" > "Script Console" to run a script on your server to interrupt the hanging thread.
You can get all the live threads with Thread.getAllStackTraces()
and interrupt the one that's hanging.
Thread.getAllStackTraces().keySet().each() {
t -> if (t.getName()=="YOUR THREAD NAME" ) { t.interrupt(); }
}
UPDATE:
The above solution using threads may not work on more recent Jenkins versions. To interrupt frozen pipelines refer to this solution (by alexandru-bantiuc) instead and run:
Jenkins.instance.getItemByFullName("JobName")
.getBuildByNumber(JobNumber)
.finish(
hudson.model.Result.ABORTED,
new java.io.IOException("Aborting build")
);
This is how I do in a function to avoid breaking getopts run at the same time somewhere higher in stack:
function waitForWeb () {
local OPTIND=1 OPTARG OPTION
local host=localhost port=8080 proto=http
while getopts "h:p:r:" OPTION; do
case "$OPTION" in
h)
host="$OPTARG"
;;
p)
port="$OPTARG"
;;
r)
proto="$OPTARG"
;;
esac
done
...
}
To make things even more clearer,
The password + salt is encrypted with a key generated from the: cost, salt and the password. we call that encrypted value the cipher text
. then we attach the salt to this value and encoding it using base64. attaching the cost to it and this is the produced string from bcrypt
:
$2a$COST$BASE64
This value is stored eventually.
In case the attacker got control over the DB, the attacker will decode easily the base64 value, and then he will be able to see the salt. the salt is not secret. though it is random.
Then he will need to decrypt the cipher text
.
What is more important : There is no hashing in this process, rather CPU expensive encryption - decryption. thus rainbow tables are less relevant here.
Even I came across similar problem. I use KDE on ubuntu 12 and while playing around in my home folder I had accidently changed permissions for Group and Others as "can view and modify content" by right clicking in my home folder and then properties and forgot all about it.
My warning was:
warning: Insecure world writable dir /home/my_home_folder in PATH, mode 040777
So in my case it was the home folder. I did undid the modifications of permissions and I stopped getting those warnings when running the rails server or rake tasks to run my tests.
The source code for the Android mobile application open-gpstracker which you appreciated is available here.
You can checkout the code using SVN client application or via Git:
Debugging the source code will surely help you.
I had similar issue. To debug the problem, I've run Wireshark and capture request generated by my code. Then I used XML Spy trial to create a SOAP request (assuming you have WSDL) and compared those two.
This should give you a hint what goes wrong.
It does apply, but it only applies to certain elements within the DOM. for example, it won't work on a table, td, or some other elements, but it will work on a <DIV> tag.
eg:
<body>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
Only tested in iOS 4.3.
A minor edit: you may be better off using overflow:scroll so two finger-scrolling does work.
You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).
This is a good understanding of data-binding. I think you've got that down.
For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.
I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.
I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.
<div rotate-on-click="45"></div>
First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.
function rotate(deg, elem) {
$(elem).css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
}
function addRotateOnClick($elems) {
$elems.each(function(i, elem) {
var deg = 0;
$(elem).click(function() {
deg+= parseInt($(this).attr('rotate-on-click'), 10);
rotate(deg, this);
});
});
}
addRotateOnClick($('[rotate-on-click]'));
app.directive('rotateOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var deg = 0;
element.bind('click', function() {
deg+= parseInt(attrs.rotateOnClick, 10);
element.css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
});
}
};
});
Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link
function (or compile
function).
Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.
This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?
The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.
Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:
Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.
Here are some things that modern frameworks are providing:
Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.
If you need to destroy a planet and you have a Death Star, use the Death star.
Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.
In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:
<clock></clock>
Done.
Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.
Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.
THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.
Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.
@Annk you can make a variable in the __component.ts file
myImage : string = "http://example.com/path/image.png";
and inside the __.component.html file you can use one of those 3 methods :
1 .
<div> <img src="{{myImage}}"> </div>
2 .
<div> <img [src]="myImage"/> </div>
3 .
<div> <img bind-src="myImage"/> </div>
I just encountered this on an MVC5 application and nothing was working for me. This happened right after I had tried to do an SVN revert to an older version of the project.
I had to delete global.asax.cs and then added a new one by right clicking Project -> Add New Item -> Global.asax and THAT finally fixed it.
Just thought it might help someone.
lstr=[1, 2, 3]
lstr=map(str,lstr)
r=re.compile('^(3){1}')
results=list(filter(r.match,lstr))
print(results)
JavaScript is case-sensitive. The b
in getElementbyId
should be capitalized.
var content = document.getElementById("edit").innerHTML;
In additon to directly accessing the array, there is also
array_push
— Push one or more elements onto the end of array
Use -to instead of -t: -to specifies the end time, -t specifies the duration
I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.
Bootstrap requires a specific file structure to work. I see from your code you have this:
<link href="bootstrap.css" rel="stylesheet" media="screen">
Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.
But first, let me recommend you setup your folder structure like so:
/css <-- Bootstrap.css here
/fonts <-- Bootstrap fonts here
/img
/js <-- Bootstrap JavaScript here
index.html
If you notice, this is also how Bootstrap structures its files in its download ZIP.
You then include your Bootstrap file like so:
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">
Depending on your server structure or what you're going for.
The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).
The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.
So, why do this?
Bootstrap.css has this specific line for Glyphfonts:
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
What you can see is that that Glyphfonts are loaded by going up one directory ../
and then looking for a folder called /fonts
and THEN loading the font file.
The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:
/fonts
Bootstrap.css
index.html
The CSS file is going one level deeper than looking for a /fonts
folder.
So, let's say the actual location of these files are:
C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html
The CSS file would technically be looking for a folder at:
C:\fonts
but your folder is actually in:
C:\www\fonts
So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.
When you get that fixed, your HTML should simply be:
<span class="glyphicon glyphicon-comment"></span>
Note, you need both classes. The first class glyphicon
sets up the basic styles while glyphicon-comment
sets the specific image.
For image purpose you can do something like this
img {
width: calc(100% + 20px); // twice the value of the parent's padding
margin-left: -10px; // -1 * parent's padding
}
I had the same issue today.While searching here for solution,I have did silly mistake that is instead of importing
import org.springframework.transaction.annotation.Transactional;
unknowingly i have imported
import javax.transaction.Transactional;
Afer changing it everything worked fine.
So thought of sharing,If somebody does same mistake .
you must have record in table or array record in database.
example:
SELECT * FROM tabel_record
WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);
1. Go in xampp/apache/conf/httpd.conf
and open it.
In the httpd.conf
file at line 176
Replace
ServerName localhost:80
with
ServerName localhost:81
It will work.
Or 2. Even if the above procedure doesn't work. Then in the same file (httpd.conf
) at line 45 replace
#Listen 0.0.0.0:80
#Listen [::]:80
Listen 80
with
#Listen 0.0.0.0:81
#Listen [::]:81
Listen 81
There are few steps to overcome this problem:
The problem solved: The problem raised to me at the uninstallation on openfire server.
Your username shouldn't be an email address, but your GitHub user account: pete
.
And your password should be your GitHub account password.
You actually can set your username directly in the remote url, in order for Git to request only your password:
cd C:\Users\petey_000\rails_projects\first_app
git remote set-url origin https://[email protected]/pete/first_app
And you need to create the fist_app
repo on GitHub first: make sure to create it completely empty, or, if you create it with an initial commit (including a README.md
, a license file and a .gitignore
file), then do a git pull first, before making your git push
.
Cacerts are details of trusted signing authorities who can issue certs. This what most of the browsers have due to which certs determined to be authentic. Keystone has your service related certs to authenticate clients.
Try this:
let jsonArr = [
{
"_id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
},
{
"_id":"5078c3a803ff4197dc81fbfc",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 2"
}
]
let idModified = jsonArr.map(
obj => {
return {
"id" : obj._id,
"email":obj.email,
"image":obj.image,
"name":obj.name
}
}
);
console.log(idModified);