Alt+H, then type letters FC, then pick the color.
Unfortunately there is no way to initialize array members till C++0x.
You could use a std::vector and push_back the Foo instances in the constructor body.
You could give Foo a default constructor (might be private and making Baz a friend).
You could use an array object that is copyable (boost or std::tr1) and initialize from a static array:
#include <boost/array.hpp>
struct Baz {
boost::array<Foo, 3> foo;
static boost::array<Foo, 3> initFoo;
Baz() : foo(initFoo)
{
}
};
boost::array<Foo, 3> Baz::initFoo = { 4, 5, 6 };
First, we need to install the cryptography library:
pip3 install cryptography
From the cryptography library, we need to import Fernet
and start generating a key - this key is required for symmetric encryption/decryption.
To generate a key, we call the generate_key()
method.
You need to keep this key in a safe place. If you lose the key, you won't be able to decrypt the data that was encrypted with this key.
Once we have generated a key, we need to load the key with load_key()
This is a three step process:
encrypt()
methodfrom cryptography.fernet import Fernet
def generate_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("secret.key", "wb") as key_file:
key_file.write(key)
def load_key():
"""
Load the previously generated key
"""
return open("secret.key", "rb").read()
def encrypt_message(message):
"""
Encrypts a message
"""
key = load_key()
encoded_message = message.encode()
f = Fernet(key)
encrypted_message = f.encrypt(encoded_message)
print(encrypted_message)
if __name__ == "__main__":
# generate_key() # execute only once
encrypt_message("Hello stackoverflow!")
output:
b'gAAAAABgLX7Zj-kn-We2BI_c9NQhEtfJEnHUVhVqtiqjkDi5dgJafj-_8QUDyeNS2zsJTdBWg6SntRJOjOM1U5mIxxsGny7IEGqpVVdHwheTnwzSBlgpb80='
To decrypt the message, we just call the decrypt()
method from the Fernet
library. Remember, we also need to load the key as well, because the key is needed to decrypt the message.
from cryptography.fernet import Fernet
def load_key():
"""
Load the previously generated key
"""
return open("secret.key", "rb").read()
def decrypt_message(encrypted_message):
"""
Decrypts an encrypted message
"""
key = load_key()
f = Fernet(key)
decrypted_message = f.decrypt(encrypted_message)
print(decrypted_message.decode())
if __name__ == "__main__":
decrypt_message(b'gAAAAABgLX7Zj-kn-We2BI_c9NQhEtfJEnHUVhVqtiqjkDi5dgJafj-_8QUDyeNS2zsJTdBWg6SntRJOjOM1U5mIxxsGny7IEGqpVVdHwheTnwzSBlgpb80=')
output:
Hello stackoverflow!
Your password is in the secret.key
in a form similar to the password below:
B8wtXqwBA_zb2Iaz5pW8CIQIwGSYSFoBiLsVz-vTqzw=
you can use a combination of font-size and line-height to force it to go larger, but obviously only in the situations where you need the font larger too
edit:
Example -> http://www.bse.co.nz EDIT: (this link is no longer relevant)
the select next to the big search box has the following css rules:
#navigation #search .locationDrop {
font-size:2em;
line-height:27px;
display:block;
float:left;
height:27px;
width:200px;
}
The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.
I used it to change the value of two label controls - lblEditModifiedBy
and lblEditModifiedOn
- when I was editing a row, so that the correct ModifiedBy and ModifiedOn
would be saved to the db on 'Update'.
When I clicked the 'Update' button, in the RowUpdating
event it showed the new values I entered in the OldValues
list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource
attached to the GridView
.)
The fix to this is using balexandre's code, but in a modified form in the gv_DataBound
event:
protected void gv_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gv.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
}
}
}
Robustness diagrams are written after use cases and before class diagrams. They help to identify the roles of use case steps. You can use them to ensure your use cases are sufficiently robust to represent usage requirements for the system you're building.
They involve:
Whereas the Model-View-Controller pattern is used for user interfaces, the Entity-Control-Boundary Pattern (ECB) is used for systems. The following aspects of ECB can be likened to an abstract version of MVC, if that's helpful:
Entities (model)
Objects representing system data, often from the domain model.
Boundaries (view/service collaborator)
Objects that interface with system actors (e.g. a user or external service). Windows, screens and menus are examples of boundaries that interface with users.
Controls (controller)
Objects that mediate between boundaries and entities. These serve as the glue between boundary elements and entity elements, implementing the logic required to manage the various elements and their interactions. It is important to understand that you may decide to implement controllers within your design as something other than objects – many controllers are simple enough to be implemented as a method of an entity or boundary class for example.
Four rules apply to their communication:
Communication allowed:
Entity Boundary Control
Entity X X
Boundary X
Control X X X
In 2020, I use apply()
with argument result_type='expand'
>>> appiled_df = df.apply(lambda row: fn(row.text), axis='columns', result_type='expand')
>>> df = pd.concat([df, appiled_df], axis='columns')
Try this one..
// Browser with version Detection
navigator.sayswho= (function(){
var N= navigator.appName, ua= navigator.userAgent, tem;
var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
return M;
})();
var browser_version = navigator.sayswho;
alert("Welcome to " + browser_version);
check out the working fiddle ( here )
Very late answer, but you can simply use:
import time
today = time.strftime("%Y-%m-%d")
# 2021-02-18
Callback for whenever a TR element is created for the table's body.
$('#example').dataTable( {
"createdRow": function( row, data, dataIndex ) {
if ( data[4] == "A" ) {
$(row).addClass( 'important' );
}
}
} );
Interestingly enough, if the goal was to print to the command line console or perform some other minute python operation, you can pipe input into the python interpreter like so:
echo print("hi:)") | python
as well as pipe files..
python < foo.py
*Note that the extension does not have to be .py for the second to work. **Also note that for bash you may need to escape the characters
echo print\(\"hi:\)\"\) | python
I give the answer because I need to compare 2 files in notepad++ and there is no option available.
So first enable the plugin manager as asked by question here, Then follow this step to compare 2 files which is free in this software.
1.open notepad++, go to
Plugin -> Plugin Manager -> Show Plugin Manager
2.Show the available plugin list, choose Compare and Install
3.Restart Notepad++.
http://www.technicaloverload.com/compare-two-files-using-notepad/
Syntax:
class Sample
{
public:
int Sam_x;
int Sam_y;
Sample(): Sam_x(1), Sam_y(2) /* Classname: Initialization List */
{
// Constructor body
}
};
Need of Initialization list:
class Sample
{
public:
int Sam_x;
int Sam_y;
Sample() */* Object and variables are created - i.e.:declaration of variables */*
{ // Constructor body starts
Sam_x = 1; */* Defining a value to the variable */*
Sam_y = 2;
} // Constructor body ends
};
in the above program, When the class’s constructor is executed, Sam_x and Sam_y are created. Then in constructor body, those member data variables are defined.
Use cases:
In C, variables must be defined during creation. the same way in C++, we must initialize the Const and Reference variable during object creation by using Initialization list. if we do initialization after object creation (Inside constructor body), we will get compile time error.
Member objects of Sample1 (base) class which do not have default constructor
class Sample1
{
int i;
public:
Sample1 (int temp)
{
i = temp;
}
};
// Class Sample2 contains object of Sample1
class Sample2
{
Sample1 a;
public:
Sample2 (int x): a(x) /* Initializer list must be used */
{
}
};
While creating object for derived class which will internally calls derived class constructor and calls base class constructor (default). if base class does not have default constructor, user will get compile time error. To avoid, we must have either
1. Default constructor of Sample1 class
2. Initialization list in Sample2 class which will call the parametric constructor of Sample1 class (as per above program)
Class constructor’s parameter name and Data member of a Class are same:
class Sample3 {
int i; /* Member variable name : i */
public:
Sample3 (int i) /* Local variable name : i */
{
i = i;
print(i); /* Local variable: Prints the correct value which we passed in constructor */
}
int getI() const
{
print(i); /*global variable: Garbage value is assigned to i. the expected value should be which we passed in constructor*/
return i;
}
};
As we all know, local variable having highest priority then global variable if both variables are having same name. In this case, the program consider "i" value {both left and right side variable. i.e: i = i} as local variable in Sample3() constructor and Class member variable(i) got override. To avoid, we must use either
1. Initialization list
2. this operator.
Aside from @Verhás István answer (which I like), I was expecting a one-liner for the question:
${project.reporting.outputDirectory}
resolves to target/site
in your project.
T-SQL supports only AFTER and INSTEAD OF triggers, it does not feature a BEFORE trigger, as found in some other RDBMSs.
I believe you will want to use an INSTEAD OF trigger.
Social skills matter more than technical skills
Agreable but average programmers with good social skills will have a more successful carreer than outstanding programmers who are disagreable people.
Try, the following code..
@Override
public String toString() {
return this.name();
}
In java System.out.println()
prints something to console. In javascript same can be achieved using console.log()
.
You need to view browser console by pressing F12
key which opens developer tool and then switch to console
tab.
The behavior of host objects <object>
is due to ECMA262 implementation dependent and set attribute by setAttribute()
method may fail.
I see two solutions:
soft: element.data = "http://www.google.com";
hard: remove object from DOM tree and create new one with changed data attribute.
There is no forumula, as street names and cities are essentially handed out randomly. The address needs to be looked up in a database. Alternatively, you can look up a zip code in a database for the region that the zip code is for.
You didn't mention a country, so I'm going to assume you just want addresses in the USA. There are numerous databases you can use, some free, some not.
You can also use the Google Maps API to have them look up an address in their database for you. That is probably the easiest solution, but requires your application to have a working internet connection at all times.
$start = '2013-09-08';
$end = '2013-09-15';
$diff = (strtotime($end)- strtotime($start))/24/3600;
echo $diff;
JAVA Fax Api documentation
You could download the mac 2.2 preview release from here and unzip it.
http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html
The javadoc won't quite match 2.1, but it will be close and if you use the preview instead, it will match exactly.
I think this would help you :)
$query_string = "";
if ($_POST) {
$kv = array();
foreach ($_POST as $key => $value) {
$kv[] = stripslashes($key) . "=" . stripslashes($value);
}
$query_string = join("&", $kv);
}
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$url = 'https://www.abcd.com/servlet/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$result = curl_exec($ch);
curl_close($ch);
dictionary_name={key1:value1,key2:value2,key3:value3}
dictionary_name.values()
JAVA_HOME should point to jdk directory and not to jre directory. Also JAVA_HOME should point to the home jdk directory and not to jdk/bin directory.
Assuming that you have JDK installed in your program files directory then you need to set the JAVA_HOME like this:
JAVA_HOME="C:\Program Files\Java\jdkxxx"
xxx is the jdk version
Follow this link to learn more about setting JAVA_HOME:
http://docs.oracle.com/cd/E19182-01/820-7851/inst_cli_jdk_javahome_t/index.html
First, get the LocationManager. Then, call LocationManager.getLastKnownPosition
. Then create a GeoCoder and call GeoCoder.getFromLocation
. Do this is in a separate thread!! This will give you a list of Address
objects. Call Address.getCountryName
and you got it.
Keep in mind that the last known position can be a bit stale, so if the user just crossed the border, you may not know about it for a while.
Another implementation but without any overflow on tbody
and dynamic columns. Requires JavaScript though. A container div
is used to house the column headings. When the table is scrolled past the view port, a fixed header appears at the top. If table is scrolled horizontally, the fixed header scrolls as well.
Column headings are created using span
elements with display: inline-block
and a negative margin is used to scroll header horizontally. Also optimized using RequestAnimationFrame
to avoid any jank.
function rAF(scrollLeft) {
var offsetLeft = 0 - scrollLeft;
$('.hdr__inner span:first-child').css('margin-left', offsetLeft);
}
You need to look at upgrading your OS and Java. Java 5.0 is EOL but if you cannot update to Java 6, you could use the latest patch level 22!
32-bit Windows is limited to ~ 1.3 GB so you are doing well to se the maximum to 1.8. Note: this is a problem with continous memory, and as your system runs its memory space can get fragmented so it does not suprise me you have this problem.
A 64-bit OS, doesn't have this problem as it has much more virtual space, you don't even have to upgrade to a 64-bit version of java to take advantage of this.
BTW, in my experience, 32-bit Java 5.0 can be faster than 64-bit Java 5.0. It wasn't until many years later that Java 6 update 10 was faster for 64-bit.
An update
Turns out now brew cask install sublime-text
installs the most up to date version (e.g. 3) by default and brew cask
is now part of the standard brew
-installation.
/* for chrome */
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;}
/* for mozilla */
input[type=number] {-moz-appearance: textfield;}
The goal of this answer is to create a single place to find all the good ideas about how to tell if you are dealing with mutating/nonmutating (immutable/mutable), and where possible, what to do about it? There are times when mutation is undesirable and python's behavior in this regard can feel counter-intuitive to coders coming into it from other languages.
As per a useful post by @mina-gabriel:
Analyzing the above and combining w/ a post by @arrakëën:
What cannot change unexpectedly?
What can?
by "unexpectedly" I mean that programmers from other languages might not expect this behavior (with the exception or Ruby, and maybe a few other "Python like" languages).
Adding to this discussion:
This behavior is an advantage when it prevents you from accidentally populating your code with mutliple copies of memory-eating large data structures. But when this is undesirable, how do we get around it?
With lists, the simple solution is to build a new one like so:
list2 = list(list1)
with other structures ... the solution can be trickier. One way is to loop through the elements and add them to a new empty data structure (of the same type).
functions can mutate the original when you pass in mutable structures. How to tell?
Non-standard Approaches (in case helpful): Found this on github published under an MIT license:
For custom classes, @semicolon suggests checking if there is a __hash__
function because mutable objects should generally not have a __hash__()
function.
This is all I have amassed on this topic for now. Other ideas, corrections, etc. are welcome. Thanks.
About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :
Basically, flatMap
is the equivalent of Promise.then
.
For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay
operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)
You seem to look for the input attribute value
, "the initial value of the control"?
<input type="text" value="Morlodenhof 7" />
https://developer.mozilla.org/de/docs/Web/HTML/Element/Input#attr-value
I use a Mac, this worked for me:
Open System Preferences, then search for 'sharing'.
Choose Remote Login, make sure it is on and remember to add required users.
Try doing something like the following in main:
public static void main(String[] args) {
PropertyConfigurator.configure(args[0]);
//... your code
you need to tell log4j what its configuration should be.
In my opinion you should not load and use plugins you don't have to. This particular jQuery plugin doesn't give you anything since directly using the JavaScript sessionStorage
object is exactly the same level of complexity. Nor, does the plugin provide some easier way to interact with other jQuery functionality. In addition the practice of using a plugin discourages a deep understanding of how something works. sessionStorage should be used only if its understood. If its understood, then using the jQuery plugin is actually MORE effort.
Consider using sessionStorage
directly:
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage
I had the same problem. I fixed it by makinbg the following entry in org.eclipse.wst.common.project.facet.core.xml
<runtime name="Apache Tomcat v7.0" />
Now this complete file looks like -
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<runtime name="Apache Tomcat v7.0" />
<fixed facet="wst.jsdt.web" />
<installed facet="java" version="1.5" />
<installed facet="jst.web" version="2.3" />
<installed facet="wst.jsdt.web" version="1.0" />
</faceted-project>
ctrl+c and kill -INT <pid>
are not exactly the same, to emulate ctrl+c we need to first understand the difference.
kill -INT <pid>
will send the INT
signal to a given process (found with its pid
).
ctrl+c is mapped to the intr
special character which when received by the terminal should send INT
to the foreground process group of that terminal. You can emulate that by targetting the group of your given <pid>
. It can be done by prepending a -
before the signal in the kill command. Hence the command you want is:
kill -INT -<pid>
You can test it pretty easily with a script:
#!/usr/bin/env ruby
fork {
trap(:INT) {
puts 'signal received in child!'
exit
}
sleep 1_000
}
puts "run `kill -INT -#{Process.pid}` in any other terminal window."
Process.wait
Sources:
To redirect stderr to a file, display stdout to screen, and also save stdout to a file:
./aaa.sh 2>ccc.out | tee ./bbb.out
EDIT: To display both stderr and stdout to screen and also save both to a file, you can use bash's I/O redirection:
#!/bin/bash
# Create a new file descriptor 4, pointed at the file
# which will receive stderr.
exec 4<>ccc.out
# Also print the contents of this file to screen.
tail -f ccc.out &
# Run the command; tee stdout as normal, and send stderr
# to our file descriptor 4.
./aaa.sh 2>&4 | tee bbb.out
# Clean up: Close file descriptor 4 and kill tail -f.
exec 4>&-
kill %1
Call any of these
byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input)
From
If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library
Luckily, we now have a couple of convenience methods in the nio packages. For instance:
byte[] java.nio.file.Files.readAllBytes(Path path)
I'm writing an answer to increase visibility to the actual syntax that solves the problem. Unfortunately, what someone might see as trivial can become a very significant headache to someone looking for a simple answer to a reasonable question.
Put the following into the file "Makefile".
MY_VAR := $(shell python -c 'import sys; print int(sys.version_info >= (2,5))')
all:
@echo MY_VAR IS $(MY_VAR)
The behavior you would like to see is the following (assuming you have recent python installed).
make
MY_VAR IS 1
If you copy and paste the above text into the Makefile, will you get this? Probably not. You will probably get an error like what is reported here:
makefile:4: *** missing separator. Stop
Why: Because although I personally used a genuine tab, Stack Overflow (attempting to be helpful) converts my tab into a number of spaces. You, frustrated internet citizen, now copy this, thinking that you now have the same text that I used. The make command, now reads the spaces and finds that the "all" command is incorrectly formatted. So copy the above text, paste it, and then convert the whitespace before "@echo" to a tab, and this example should, at last, hopefully, work for you.
"Select your text, right click, then choose
Style Token
and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."
It should be default, but it might be hidden.
"It might be that something happened to your
contextMenu.xml
so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\
) if thecontextMenu.xml
is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at thecontextmenu.xml
itself - because you're allowed to change it to your own needs."
See this for more information
I consider delegates to be Anonymous Interfaces. In many cases you can use them whenever you need an interface with a single method, but you don't want the overhead of defining that interface.
Using the step
attribute will enable it. It not only determines how much it's supposed to cycle, but the allowable numbers, as well. Using step="0.01"
should do the trick but this may depend on how the browser adheres to the standard.
<input type='number' step='0.01' value='5.00'>
_x000D_
You can do as follows
ifconfig <Interface ex:eth0,eth1> | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'
Also you can get MAC for all interface as follows
cat /sys/class/net/*/address
For particular interface like for eth0
cat /sys/class/net/eth0/address
To debug php with vscode,you need these things:
you can gently walk through step 1 and 2,by following the vscode official guide.It is fully recommended to use XDebug installation wizard to verify your XDebug configuration.
If you want to debug without a standalone web server,the php built-in maybe a choice.Start the built-in server by php -S localhost:port -t path/to/your/project
command,setting your project dir as document root.You can refer to this post for more details.
The DOMContentLoaded
event will fire as soon as the DOM hierarchy has been fully constructed, the load
event will do it when all the images and sub-frames have finished loading.
DOMContentLoaded
will work on most modern browsers, but not on IE including IE9 and above. There are some workarounds to mimic this event on older versions of IE, like the used on the jQuery library, they attach the IE specific onreadystatechange
event.
Try this if it is "in transition" ...
http://learnmysql.blogspot.com/2012/05/database-is-in-transition-try-statement.html
USE master
GO
ALTER DATABASE <db_name>
SET OFFLINE WITH ROLLBACK IMMEDIATE
...
...
ALTER DATABASE <db_name> SET ONLINE
Looking from the perspective of the user: when sending a request to a proxy or reverse proxy server:
proxy - requires two arguments:
1) what to get and 2) which proxy server to use an intermediate
reverse proxy - requires one argument:
1) what to get
A reverse proxy fetches contents from another server unbeknownst to the user and returns the result as if it originated from the reverse proxy server.
Simple way to access the Url Try this Code
$.ajax({
type: "POST",
url: '/Controller/Search',
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
});
I apologise for replying to a super old question but after spending an hour wrestling with the above solutions I opted for simpler stuff.
<script src=".." one="1" two="2"></script>
Inside above script:
document.currentScript.getAttribute('one'); //1
document.currentScript.getAttribute('two'); //2
Much easier than jquery OR url parsing.
You might need the polyfil for doucment.currentScript from @Yared Rodriguez's answer for IE:
document.currentScript = document.currentScript || (function() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
anyway you have not a unlimited accuracy so C define a constant in this way:
#define PI 3.14159265358979323846
import math.h to use this
Try this instead:
print_r($sth->errorInfo());
Add this before your prepare:
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.
I opened the Properties window for the website project in question and changed Windows Authentication to "Enabled" and that resolved my issue in VS 2019.
CellSpacing as the name suggests it is the Space between the Adjacent cells and CellPadding on the other hand means the padding around the cell content.
An easy short hand way would be to use +x It keeps the sign intact as well as the decimal numbers. The other alternative is to use parseFloat(x). Difference between parseFloat(x) and +x is for a blank string +x returns 0 where as parseFloat(x) returns NaN.
A simple but relatively insecure way would be to use the --net=host
option to docker run
.
This option makes it so that the container uses the networking stack of the host. Then you can connect to services running on the host simply by using "localhost" as the hostname.
This is easier to configure because you won't have to configure the service to accept connections from the IP address of your docker container, and you won't have to tell the docker container a specific IP address or host name to connect to, just a port.
For example, you can test it out by running the following command, which assumes your image is called my_image
, your image includes the telnet
utility, and the service you want to connect to is on port 25:
docker run --rm -i -t --net=host my_image telnet localhost 25
If you consider doing it this way, please see the caution about security on this page:
https://docs.docker.com/articles/networking/
It says:
--net=host -- Tells Docker to skip placing the container inside of a separate network stack. In essence, this choice tells Docker to not containerize the container's networking! While container processes will still be confined to their own filesystem and process list and resource limits, a quick ip addr command will show you that, network-wise, they live “outside” in the main Docker host and have full access to its network interfaces. Note that this does not let the container reconfigure the host network stack — that would require --privileged=true — but it does let container processes open low-numbered ports like any other root process. It also allows the container to access local network services like D-bus. This can lead to processes in the container being able to do unexpected things like restart your computer. You should use this option with caution.
Isn't it just: System.out.println(Array.length);
? Because this is what it seems like you are looking for.
Here you can find some useful info about cURL & cookies http://docstore.mik.ua/orelly/webprog/pcook/ch11_04.htm .
You can also use this well done method https://github.com/alixaxel/phunction/blob/master/phunction/Net.php#L89 like a function:
function CURL($url, $data = null, $method = 'GET', $cookie = null, $options = null, $retries = 3)
{
$result = false;
if ((extension_loaded('curl') === true) && (is_resource($curl = curl_init()) === true))
{
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if (preg_match('~^(?:DELETE|GET|HEAD|OPTIONS|POST|PUT)$~i', $method) > 0)
{
if (preg_match('~^(?:HEAD|OPTIONS)$~i', $method) > 0)
{
curl_setopt_array($curl, array(CURLOPT_HEADER => true, CURLOPT_NOBODY => true));
}
else if (preg_match('~^(?:POST|PUT)$~i', $method) > 0)
{
if (is_array($data) === true)
{
foreach (preg_grep('~^@~', $data) as $key => $value)
{
$data[$key] = sprintf('@%s', rtrim(str_replace('\\', '/', realpath(ltrim($value, '@'))), '/') . (is_dir(ltrim($value, '@')) ? '/' : ''));
}
if (count($data) != count($data, COUNT_RECURSIVE))
{
$data = http_build_query($data, '', '&');
}
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
if (isset($cookie) === true)
{
curl_setopt_array($curl, array_fill_keys(array(CURLOPT_COOKIEJAR, CURLOPT_COOKIEFILE), strval($cookie)));
}
if ((intval(ini_get('safe_mode')) == 0) && (ini_set('open_basedir', null) !== false))
{
curl_setopt_array($curl, array(CURLOPT_MAXREDIRS => 5, CURLOPT_FOLLOWLOCATION => true));
}
if (is_array($options) === true)
{
curl_setopt_array($curl, $options);
}
for ($i = 1; $i <= $retries; ++$i)
{
$result = curl_exec($curl);
if (($i == $retries) || ($result !== false))
{
break;
}
usleep(pow(2, $i - 2) * 1000000);
}
}
curl_close($curl);
}
return $result;
}
And pass this as $cookie
parameter:
$cookie_jar = tempnam('/tmp','cookie');
You need to write following code on controller suppose test is model, and Name, Address are field of this model.
public ActionResult MyMethod()
{
Test test=new Test();
var test.Name="John";
return View(test);
}
now use like like this on your view to give set value of hidden variable.
@model YourApplicationName.Model.Test
@Html.HiddenFor(m=>m.Name,new{id="hdnFlag"})
This will automatically set hidden value=john.
You can do it in various ways.
The old conventional way is,
maxIndexList = list() #this list will store indices of maximum values
maximumValue = max(a) #get maximum value of the list
length = len(a) #calculate length of the array
for i in range(length): #loop through 0 to length-1 (because, 0 based indexing)
if a[i]==maximumValue: #if any value of list a is equal to maximum value then store its index to maxIndexList
maxIndexList.append(i)
print(maxIndexList) #finally print the list
Another way without calculating the length of the list and storing maximum value to any variable,
maxIndexList = list()
index = 0 #variable to store index
for i in a: #iterate through the list (actually iterating through the value of list, not index )
if i==max(a): #max(a) returns a maximum value of list.
maxIndexList.append(index) #store the index of maximum value
index = index+1 #increment the index
print(maxIndexList)
We can do it in Pythonic and smart way! Using list comprehension just in one line,
maxIndexList = [i for i,j in enumerate(a) if j==max(a)] #here,i=index and j = value of that index
All my codes are in Python 3.
Here is two different, simple ways to get content from URL:
1) the first method
Enable Allow_url_include from your hosting (php.ini or somewhere)
<?php
$variableee = readfile("http://example.com/");
echo $variableee;
?>
or
2)the second method
Enable php_curl, php_imap and php_openssl
<?php
// you can add anoother curl options too
// see here - http://php.net/manual/en/function.curl-setopt.php
function get_dataa($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$variableee = get_dataa('http://example.com');
echo $variableee;
?>
Web.Config file:
<configuration>
<system.net>
<mailSettings>
<smtp from="[email protected]">
<network host="smtp.gmail.com"
port="587"
userName="[email protected]"
password="yourpassword"
enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
yes, sql server doesn't allow to insert single quote in table field due to the sql injection attack. so we must replace single appostrophe by double while saving.
(he doesn't work for me) must be => (he doesn''t work for me)
Here is an example to config HTTP and HTTPS in same config block with ipv6 support. The config is tested in Ubuntu Server and NGINX/1.4.6 but this should work with all servers.
server {
# support http and ipv6
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
# support https and ipv6
listen 443 default_server ssl;
listen [::]:443 ipv6only=on default_server ssl;
# path to web directory
root /path/to/example.com;
index index.html index.htm;
# domain or subdomain
server_name example.com www.example.com;
# ssl certificate
ssl_certificate /path/to/certs/example_com-bundle.crt;
ssl_certificate_key /path/to/certs/example_com.key;
ssl_session_timeout 5m;
ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES";
ssl_prefer_server_ciphers on;
}
Don't include ssl on
which may cause 400
error. The config above should work for
Hope this helps!
This is designed for use when you have a shell script build step. Use only the first two lines to get the file name.
You can get the console log file (using bash magic) for the current build from a shell script this way and check it for some error string, failing the job if found:
logFilename=${JENKINS_HOME}/${JOB_URL:${#JENKINS_URL}}
logFilename=${logFilename//job\//jobs\/}builds/${BUILD_NUMBER}/log
grep "**Failure**" ${logFilename} ; exitCode=$?
[[ $exitCode -ne 1 ]] && exit 1
You have to build the file name by taking the JOB_URL, stripping off the leading host name part, adding in the path to JENKINS_HOME, replacing "/job/" to "/jobs/" to handle all nested folders, adding the current build number and the file name.
The grep returns 0 if the string is found and 2 if there is a file error. So a 1 means it found the error indication string. That makes the build fail.
no javascript or third party 'tools' necessary, use this:
<iframe src="https://www.google.com/maps/embed/v1/place?key=<YOUR API KEY>&q=71.0378379,-110.05995059999998"></iframe>
the place parameter provides the marker
there are a few options for the format of the 'q' parameter
make sure you have Google Maps Embed API and Static Maps API enabled in your APIs, or google will block the request
for more information check here
Suppose you want to hit https://yourwebsitedomain/app/getNames from http://localhost:3000 then just make the following changes:
packagae.json :
"name": "version-compare-app",
"proxy": "https://yourwebsitedomain/",
....
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
...
In your component use it as follows:
import axios from "axios";
componentDidMount() {
const getNameUrl =
"app/getNames";
axios.get(getChallenge).then(data => {
console.log(data);
});
}
Stop your local server and re run npm start. You should be able to see the data in browser's console logged
Off the top of my head, why don't you just Thread.Join(timeout) and remove the time it took to join from the total timeout?
// pseudo-c#:
TimeSpan timeout = timeoutPerThread * threads.Count();
foreach (Thread thread in threads)
{
DateTime start = DateTime.Now;
if (!thread.Join(timeout))
throw new TimeoutException();
timeout -= (DateTime.Now - start);
}
Edit: code is now less pseudo. don't understand why you would mod an answer -2 when the answer you modded +4 is exactly the same, only less detailed.
Not smarter but simpler:
select info->>'name' from rabbits WHERE info->>'food' LIKE '%"carrots"%';
Here's an application I wrote for reading xml sitemaps:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using System.Xml;
namespace SiteMapReader
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Enter the Location of the file");
// get the location we want to get the sitemaps from
string dirLoc = Console.ReadLine();
// get all the sitemaps
string[] sitemaps = Directory.GetFiles(dirLoc);
StreamWriter sw = new StreamWriter(Application.StartupPath + @"\locs.txt", true);
// loop through each file
foreach (string sitemap in sitemaps)
{
try
{
// new xdoc instance
XmlDocument xDoc = new XmlDocument();
//load up the xml from the location
xDoc.Load(sitemap);
// cycle through each child noed
foreach (XmlNode node in xDoc.DocumentElement.ChildNodes)
{
// first node is the url ... have to go to nexted loc node
foreach (XmlNode locNode in node)
{
// thereare a couple child nodes here so only take data from node named loc
if (locNode.Name == "loc")
{
// get the content of the loc node
string loc = locNode.InnerText;
// write it to the console so you can see its working
Console.WriteLine(loc + Environment.NewLine);
// write it to the file
sw.Write(loc + Environment.NewLine);
}
}
}
}
catch { }
}
Console.WriteLine("All Done :-)");
Console.ReadLine();
}
static void readSitemap()
{
}
}
}
Code on Paste Bin http://pastebin.com/yK7cSNeY
To avoid any potential confusion, I would like to contrast static variables and immutable objects.
Some primitive object types like integers, floats, strings, and touples are immutable in Python. This means that the object that is referred to by a given name cannot change if it is of one of the aforementioned object types. The name can be reassigned to a different object, but the object itself may not be changed.
Making a variable static takes this a step further by disallowing the variable name to point to any object but that to which it currently points. (Note: this is a general software concept and not specific to Python; please see others' posts for information about implementing statics in Python).
Just to add another set of answers:
You need to make use of Label Callback. A common example to round data values, the following example rounds the data to two decimal places.
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
label += Math.round(tooltipItem.yLabel * 100) / 100;
return label;
}
}
}
}
});
Now let me write the scenario where I used the label callback functionality.
Let's start with logging the arguments of Label Callback function, you will see structure similar to this here datasets, array comprises of different lines you want to plot in the chart. In my case it's 4, that's why length of datasets array is 4.
In my case, I had to perform some calculations on each dataset and have to identify the correct line, every-time I hover upon a line in a chart.
To differentiate different lines and manipulate the data of hovered tooltip based on the data of other lines I had to write this logic.
callbacks: {
label: function (tooltipItem, data) {
console.log('data', data);
console.log('tooltipItem', tooltipItem);
let updatedToolTip: number;
if (tooltipItem.datasetIndex == 0) {
updatedToolTip = tooltipItem.yLabel;
}
if (tooltipItem.datasetIndex == 1) {
updatedToolTip = tooltipItem.yLabel - data.datasets[0].data[tooltipItem.index];
}
if (tooltipItem.datasetIndex == 2) {
updatedToolTip = tooltipItem.yLabel - data.datasets[1].data[tooltipItem.index];
}
if (tooltipItem.datasetIndex == 3) {
updatedToolTip = tooltipItem.yLabel - data.datasets[2].data[tooltipItem.index]
}
return updatedToolTip;
}
}
Above mentioned scenario will come handy, when you have to plot different lines in line-chart and manipulate tooltip of the hovered point of a line, based on the data of other point belonging to different line in the chart at the same index.
if you are working in the java world - intelliJ idea has also extensive xml support, including xsd generation and samle xml from xsd generation, and with plugins you can get xslt debuggers. - especially nice if you plan to use tools such as jaxb afterwards.
In my case body didn't worked:
$('body').scrollTop(0);
But HTML worked:
$('html').scrollTop(0);
Why does it give me that error?
Because your first parameter you pass to the loop
function is None but your function is expecting an callable object, which None object isn't.
Therefore you have to pass the callable-object which is in your case the hi
function object.
def hi():
print 'hi'
def loop(f, n): #f repeats n times
if n<=0:
return
else:
f()
loop(f, n-1)
loop(hi, 5)
LEFT JOIN
and RIGHT JOIN
are types of OUTER JOIN
s.
INNER JOIN
is the default -- rows from both tables must match the join condition.
Adding on to the one mentioned by @abarnert
a better one is to catch the exception
import subprocess
try:
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)
#print('py2 said:', py2output)
print "here"
except subprocess.CalledProcessError as e:
print "Calledprocerr"
this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting
python: can't open file 'py2.py': [Errno 2] No such file or directory
Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script
I use GroovyShell in java to parse template with Groovy GString:
Binding binding = new Binding();
GroovyShell gs = new GroovyShell(binding);
// this JSONObject can also be replaced by any Java Object
JSONObject obj = new JSONObject();
obj.put("key", "value");
binding.setProperty("obj", obj)
String str = "${obj.key}";
String exp = String.format("\"%s\".toString()", str);
String res = (String) gs.evaluate(exp);
// value
System.out.println(str);
Building slightly off Ben's answer, I added attributes for the ID so I could use labels.
<%: Html.Label("isBlahYes", "Yes")%><%= Html.RadioButtonFor(model => model.blah, true, new { @id = "isBlahYes" })%>
<%: Html.Label("isBlahNo", "No")%><%= Html.RadioButtonFor(model => model.blah, false, new { @id = "isBlahNo" })%>
I hope this helps.
I was using github earlier for one of my php project. While using github, I was using ssh instead of https. I had my machine set up like that and every time I used to commit and push the code, it would ask me my rsa key password.
After some days, I stopped working on the php project and forgot my rsa password. Recently, I started working on a java project and moved to bitbucket. Since, I had forgotten the password and there is no way to recover it I guess, I decided to use the https(recommended) protocol for the new project and got the same error asked in the question.
How I solved it?
Ran this command to tell my git to use https instead of ssh:
git config --global url."https://".insteadOf git://
Remove any remote if any
git remote rm origin
Redo everything from git init to git push and it works!
PS: I also un-installed ssh from my machine during the debug process thinking that, removing it will fix the problem. Yes I know!! :)
You need to close the input element with a />
at the end.
<input id="icon_prefix" type="text" class="validate" />
Here are some more console logging "pro tips":
console.table
var animals = [
{ animal: 'Horse', name: 'Henry', age: 43 },
{ animal: 'Dog', name: 'Fred', age: 13 },
{ animal: 'Cat', name: 'Frodo', age: 18 }
];
console.table(animals);
console.trace
Shows you the call stack for leading up to the console.
You can even customise your consoles to make them stand out
console.todo = function(msg) {
console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}
console.important = function(msg) {
console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}
console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);
If you really want to level up don't limit your self to the console statement.
Here is a great post on how you can integrate a chrome debugger right into your code editor!
https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037
Using tidyverse
df %>% tidyr::gather("id", "value", 1:4) %>%
ggplot(., aes(Xax, value))+
geom_point()+
geom_smooth(method = "lm", se=FALSE, color="black")+
facet_wrap(~id)
DATA
df<- read.table(text =c("
A B C G Xax
0.451 0.333 0.034 0.173 0.22
0.491 0.270 0.033 0.207 0.34
0.389 0.249 0.084 0.271 0.54
0.425 0.819 0.077 0.281 0.34
0.457 0.429 0.053 0.386 0.53
0.436 0.524 0.049 0.249 0.12
0.423 0.270 0.093 0.279 0.61
0.463 0.315 0.019 0.204 0.23"), header = T)
The POSIX standard mandates that multiple /
are treated as a single /
in a file name. Thus
//dir///subdir////file
is the same as /dir/subdir/file
.
As such concatenating a two strings to build a complete path is a simple as:
full_path="$part1/$part2"
The best approach is Long.valueOf(str)
as it relies on Long.valueOf(long)
which uses an internal cache making it more efficient since it will reuse if needed the cached instances of Long
going from -128
to 127
included.
Returns a
Long
instance representing the specified long value. If a new Long instance is not required, this method should generally be used in preference to the constructorLong(long)
, as this method is likely to yield significantly better space and time performance by caching frequently requested values. Note that unlike the corresponding method in the Integer class, this method is not required to cache values within a particular range.
Thanks to auto-unboxing allowing to convert a wrapper class's instance into its corresponding primitive type, the code would then be:
long val = Long.valueOf(str);
Please note that the previous code can still throw a NumberFormatException
if the provided String
doesn't match with a signed long
.
Generally speaking, it is a good practice to use the static
factory method valueOf(str)
of a wrapper class like Integer
, Boolean
, Long
, ... since most of them reuse instances whenever it is possible making them potentially more efficient in term of memory footprint than the corresponding parse
methods or constructors.
Excerpt from Effective Java Item 1
written by Joshua Bloch:
You can often avoid creating unnecessary objects by using static factory methods (Item 1) in preference to constructors on immutable classes that provide both. For example, the static factory method
Boolean.valueOf(String)
is almost always preferable to the constructorBoolean(String)
. The constructor creates a new object each time it’s called, while the static factory method is never required to do so and won’t in practice.
It appears that the Internet Explorer driver does not interact with everything in the same way the other drivers do and checkboxes is one of those cases.
The trick with checkboxes is to send the Space key instead of using a click (only needed on Internet Explorer), like so in C#:
if (driver.Capabilities.BrowserName.Equals(“internet explorer"))
driver.findElement(By.id("idOfTheElement").SendKeys(Keys.Space);
else
driver.findElement(By.id("idOfTheElement").Click();
For Eclipse in Macbook it is just 2 click process:
Yet another perl WTDI:
perl -i -p0777we's/\n\z//' filename
There is a handy trick that works in some databases for ordering in database order,
SELECT * FROM TableName ORDER BY true
Apparently, this can work in conjunction with any of the other suggestions posted here to leave the results in "order they came out of the database" order, which in some databases, is the order they were last modified in.
You can escape the calc
arguments in order to prevent them from being evaluated on compilation.
Using your example, you would simply surround the arguments, like this:
calc(~'100% - 10px')
Demo : http://jsfiddle.net/c5aq20b6/
I find that I use this in one of the following three ways:
Everything inside the calc
arguments is defined as a string, and is totally static until it's evaluated by the client:
div {
> span {
width: calc(~'100% - 10px');
}
}
div > span {
width: calc(100% - 10px);
}
You can insert a LESS variable into the string:
div {
> span {
@pad: 10px;
width: calc(~'100% - @{pad}');
}
}
div > span {
width: calc(100% - 10px);
}
You may want to escape a percentage value, but go ahead and evaluate something on compilation:
@btnWidth: 40px;
div {
> span {
@pad: 10px;
width: calc(~'(100% - @{pad})' - (@btnWidth * 2));
}
}
div > span {
width: calc((100% - 10px) - 80px);
}
Source: http://lesscss.org/functions/#string-functions-escape.
The statement:
(my $newstring = $oldstring) =~ s/foo/bar/g;
Which is equivalent to:
my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;
Alternatively, as of Perl 5.13.2 you can use /r
to do a non destructive substitution:
use 5.013;
#...
my $newstring = $oldstring =~ s/foo/bar/gr;
I also came across the same problem, what I did was
1) Open your cmd
2) Navigate to C:\Program Files\MySQL\MySQL Server 8.0\bin> (where MySQL Server 8.0 may be different depending on the server you installed)
3) Then put the following command mysql -u root -p
4) I will prompt for the password... simply hit enter, as sometimes the password you entered while installing is changed by to blank.
now you can simply access the database
This solution worked for me on windows platform
style="position:absolute"
It's basic step notation, consider the functionality of:
a[2:4:2]
What happens is the index is sliced between position 2 and 4, what the third variable does is it sets the step size starting from the first value. In this case it would return a[2], since a[4] is an upper bounds only two values are return and no second step takes place. The (-) minus operator simply reverses the step output.
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
might be very simple
for example
<script src="js/myscript.js?id=123"></script>
<script>
var queryString = $("script[src*='js/myscript.js']").attr('src').split('?')[1];
</script>
You can then convert query string into json like below
var json = $.parseJSON('{"'
+ queryString.replace(/&/g, '","').replace(/=/g, '":"')
+ '"}');
and then can use like
console.log(json.id);
Seems that there's enough variation that people go out of their way to allow conversion from all conventions to others: http://www.cowtowncoder.com/blog/archives/cat_json.html
Notably, the mentioned Jackson JSON parser prefers bean_naming
.
I personally do not see any reason why one would like to use char* or char[] except for compatibility with old code. std::string's no slower than using a c-string, except that it will handle re-allocation for you. You can set it's size when you create it, and thus avoid re-allocation if you want. It's indexing operator ([]) provides constant time access (and is in every sense of the word the exact same thing as using a c-string indexer). Using the at method gives you bounds checked safety as well, something you don't get with c-strings, unless you write it. Your compiler will most often optimize out the indexer use in release mode. It is easy to mess around with c-strings; things such as delete vs delete[], exception safety, even how to reallocate a c-string.
And when you have to deal with advanced concepts like having COW strings, and non-COW for MT etc, you will need std::string.
If you are worried about copies, as long as you use references, and const references wherever you can, you will not have any overhead due to copies, and it's the same thing as you would be doing with the c-string.
Rename it to .zip, then extract it.
Add a temporary Objective-C file to your project. You may give it any name you like.
Select Yes to configure an Objective-C bridging header.
Delete the temporary Objective-C file you just created.
In the projectName-Bridging-Header.h file just created, add this line:
'#import < GoogleMaps/GoogleMaps.h >'
Edit the AppDelegate.swift file:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
GMSServices.provideAPIKey("AIza....") //iOS API key
return true
}
Follow the link for full sample
I struggled with this problem for a while myself. It turned out that cmake
was looking for Boost library files using Boost's naming convention, in which the library name is a function of the compiler version used to build it. Our Boost libraries were built using GCC 4.9.1
, and that compiler version was in fact present on our system; however, GCC 4.4.7
also happened to be installed. As it happens, cmake's FindBoost.cmake
script was auto-detecting the GCC 4.4.7
installation instead of the GCC 4.9.1
one, and thus was looking for Boost library files with "gcc44
" in the file names, rather than "gcc49
".
The simple fix was to force cmake to assume that GCC 4.9 was present, by setting Boost_COMPILER
to "-gcc49
" in CMakeLists.txt
. With this change, FindBoost.cmake
looked for, and found, my Boost library files.
The best source is probably Apple's official documentation. The specific variable you are looking for is CONFIGURATION.
Simply just append your fields and their values to the elements:
$user->roles()->sync([
1 => ['F1' => 'F1 Updated']
]);
So you want to change it WHEN it's clicked...let me go through the whole process. Let's assume that your "External DOM Object" is an input, like a select:
Let's start with this HTML:
<body>
<div>
<select id="test">
<option>Bob</option>
<option>Sam</option>
<option>Sue</option>
<option>Jen</option>
</select>
</div>
<table id="theTable">
<tr><td id="cellToChange">Bob</td><td>Sam</td></tr>
<tr><td>Sue</td><td>Jen</td></tr>
</table>
</body>
Some very basic CSS:
?#theTable td {
border:1px solid #555;
}
.activeCell {
background-color:#F00;
}
And set up a jQuery event:
function highlightCell(useVal){
$("#theTable td").removeClass("activeCell")
.filter(":contains('"+useVal+"')").addClass("activeCell");
}
$(document).ready(function(){
$("#test").change(function(e){highlightCell($(this).val())});
});
Now, whenever you pick something from the select, it will automatically find a cell with the matching text, allowing you to subvert the whole id-based process. Of course, if you wanted to do it that way, you could easily modify the script to use IDs rather than values by saying
.filter("#"+useVal)
and make sure to add the ids appropriately. Hope this helps!
You can use
<?php the_category(', '); ?>
which would output them in a comma separated list.
You can also do the same for tags as well:
<?php the_tags('<em>:</em>', ', ', ''); ?>
Another approach for a delayed component:
Delayed.jsx
:
import React from 'react';
import PropTypes from 'prop-types';
class Delayed extends React.Component {
constructor(props) {
super(props);
this.state = {hidden : true};
}
componentDidMount() {
setTimeout(() => {
this.setState({hidden: false});
}, this.props.waitBeforeShow);
}
render() {
return this.state.hidden ? '' : this.props.children;
}
}
Delayed.propTypes = {
waitBeforeShow: PropTypes.number.isRequired
};
export default Delayed;
Usage:
import Delayed from '../Time/Delayed';
import React from 'react';
const myComp = props => (
<Delayed waitBeforeShow={500}>
<div>Some child</div>
</Delayed>
)
What about data binding?
@JvmStatic
@BindingAdapter("textHtml")
fun setHtml(textView: TextView, resource: String) {
val html: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(resource, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(resource)
}
textView.movementMethod = LinkMovementMethod.getInstance()
textView.text = html
}
strings.xml
<string name="text_with_link"><a href=%2$s>%1$s</a> </string>
in your layout.xml
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:textHtml="@{@string/text_with_link(model.title, model.url)}"
tools:text="Some text" />
Where title and link in xml is a simple String
Also you can pass multiple arguments to data binding adapter
@JvmStatic
@BindingAdapter(value = ["textLink", "link"], requireAll = true)
fun setHtml(textView: TextView, textLink: String?, link: String?) {
val resource = String.format(textView.context.getString(R.string.text_with_link, textLink, link))
val html: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(resource, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(resource)
}
textView.movementMethod = LinkMovementMethod.getInstance()
textView.text = html
}
and in .xml pass arguments separately
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:link="@{model.url}"
app:textLink="@{model.title}"
tools:text="Some text" />
From "node_modules" in Git:
To recap.
- Only checkin node_modules for applications you deploy, not reusable packages you maintain.
- Any compiled dependencies should have their source checked in, not the compile targets, and should $ npm rebuild on deploy.
My favorite part:
All you people who added node_modules to your gitignore, remove that shit, today, it’s an artifact of an era we’re all too happy to leave behind. The era of global modules is dead.
(The original link was this one, but it is now dead. Thanks @Flavio for pointing it out.)*
In modern browsers, it should be like
try() {
if (!$("#element").size()) {
window.requestAnimationFrame(try);
} else {
// do your stuff
}
};
componentDidMount(){
this.try();
}
Ok got this as:
var query = (from t in Transactions
group t by new {t.MaterialID, t.ProductID}
into grp
select new
{
grp.Key.MaterialID,
grp.Key.ProductID,
Quantity = grp.Sum(t => t.Quantity)
}).ToList();
Wow, from all the framework-promotional answers you'd think this was something JavaScript made incredibly difficult. It isn't really.
var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return; // or whatever error handling you want
document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();
If you need IE<8 compatibility, do this first to bring those browsers up to speed:
if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
window.XMLHttpRequest= function() {
return new ActiveXObject('MSXML2.XMLHttp');
};
}
Note that loading content into the page with scripts will make that content invisible to clients without JavaScript available, such as search engines. Use with care, and consider server-side includes if all you want is to put data in a common shared file.
Always use
//Super Fast
$('#my_id').find('.my_class');
instead of
// Fast:
$('#my_id .my_class');
Have look at JQuery Performance Rules.
Also at Jquery Doc
According to this SO answer, it occurs due to an AWS SDK bug that appears to be solved in version 2.6.30 of the SDK, so updating the version to a newer, can help you fixing the problem.
You can also use defaultdict to address this situation. It goes something like this:
from collections import defaultdict
#initialises the dictionary with values as list
aTargetDictionary = defaultdict(list)
for aKey in aSourceDictionary:
aTargetDictionary[aKey].append(aSourceDictionary[aKey])
If I want to create JavaScript Object from string generated by for loop then I would JSON to Object approach. I would generate JSON string by iterating for loop and then use any popular JavaScript Framework to evaluate JSON to Object.
I have used Prototype JavaScript Framework. I have two array with keys and values. I iterate through for loop and generate valid JSON string. I use evalJSON() function to convert JSON string to JavaScript object.
Here is example code. Tryout on your FireBug Console
var key = ["color", "size", "fabric"];
var value = ["Black", "XL", "Cotton"];
var json = "{ ";
for(var i = 0; i < key.length; i++) {
(i + 1) == key.length ? json += "\"" + key[i] + "\" : \"" + value[i] + "\"" : json += "\"" + key[i] + "\" : \"" + value[i] + "\",";
}
json += " }";
var obj = json.evalJSON(true);
console.log(obj);
DECLARE @seconds AS int = 896434;
SELECT
CONVERT(varchar, (@seconds / 86400)) --Days
+ ':' +
CONVERT(varchar, DATEADD(ss, @seconds, 0), 108); --Hours, Minutes, Seconds
Outputs:
10:09:00:34
Although this question has already been adequately answered with solutions using the box-shadow
and outline
properties, I would like to slightly expand on this
for all those who have landed here (like myself) searching for a solution for an inner border with an offset
So let's say you have a black 100px x 100px div
and you need to inset it with a white border - which has an inner offset of 5px (say) - this can still be done with the above properties.
The trick here is to know that multiple box-shadows are allowed, where the first shadow is on top and subsequent shadows have lower z-ordering.
With that knowledge, the box-shadow declaration will be:
box-shadow: inset 0 0 0 5px black, inset 0 0 0 10px white;
div {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: black;_x000D_
box-shadow: inset 0 0 0 5px black, inset 0 0 0 10px white; _x000D_
}
_x000D_
<div></div>
_x000D_
Basically, what that declaration is saying is: render the last (10px white) shadow first, then render the previous 5px black shadow above it.
For the same effect as above the outline declarations would be:
outline: 5px solid white;
outline-offset: -10px;
div {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: black;_x000D_
outline: 5px solid white;_x000D_
outline-offset: -10px;_x000D_
}
_x000D_
<div></div>
_x000D_
NB: outline-offset
isn't supported by IE if that's important to you.
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
just close the eclipse and avd emulator and restart it. It works fine
val : must add or initialized value but can't change. var: it's variable can ba change in any line in code.
In addition to previous answers, if your menu items are Categories and you want to highlight them when navigating through posts, check also for current-post-ancestor
:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class ($classes, $item) {
if (in_array('current-post-ancestor', $classes) || in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}
Here is a simple class I coded for my web application. It allows for forking PHP scripts and other scripts. Works on UNIX and Windows.
class BackgroundProcess {
static function open($exec, $cwd = null) {
if (!is_string($cwd)) {
$cwd = @getcwd();
}
@chdir($cwd);
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$WshShell = new COM("WScript.Shell");
$WshShell->CurrentDirectory = str_replace('/', '\\', $cwd);
$WshShell->Run($exec, 0, false);
} else {
exec($exec . " > /dev/null 2>&1 &");
}
}
static function fork($phpScript, $phpExec = null) {
$cwd = dirname($phpScript);
@putenv("PHP_FORCECLI=true");
if (!is_string($phpExec) || !file_exists($phpExec)) {
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$phpExec = str_replace('/', '\\', dirname(ini_get('extension_dir'))) . '\php.exe';
if (@file_exists($phpExec)) {
BackgroundProcess::open(escapeshellarg($phpExec) . " " . escapeshellarg($phpScript), $cwd);
}
} else {
$phpExec = exec("which php-cli");
if ($phpExec[0] != '/') {
$phpExec = exec("which php");
}
if ($phpExec[0] == '/') {
BackgroundProcess::open(escapeshellarg($phpExec) . " " . escapeshellarg($phpScript), $cwd);
}
}
} else {
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$phpExec = str_replace('/', '\\', $phpExec);
}
BackgroundProcess::open(escapeshellarg($phpExec) . " " . escapeshellarg($phpScript), $cwd);
}
}
}
Do search with LEFT OUTER JOIN
. I don't know if MySQL allows inline VALUES
in join clauses but you can have predefined table for this purposes.
AND
between ORDER BY
and LIMIT
=
between ORDER BY
, LIMIT
keywords and conditionSo you query will look like:
SELECT post_datetime
FROM post
WHERE type = 'published'
ORDER BY post_datetime DESC
LIMIT 3
Exponential backoff is a good retry strategy than simply trying x number of times. You can use a library like Polly to implement it.
It is very simple, first, you need to be inside the virtualenv you created, then to install a specific version of python say 3.5, use Anaconda, conda install python=3.5
In general you can do this for any python package you want
conda install package_name=package_version
I know this is an old one, but I'd like to add to this discussion that There are at least 5 different methods for creating a triangle using HTML & CSS alone.
borders
linear-gradient
conic-gradient
transform
and overflow
clip-path
I think that all have been covered here except for method 3, using the conic-gradient
, so I will share it here:
.triangle{_x000D_
width: 40px;_x000D_
height: 40px;_x000D_
background: conic-gradient(at 50% 50%,transparent 135deg,green 0,green 225deg, transparent 0);_x000D_
}
_x000D_
<div class="triangle"></div>
_x000D_
On macOS, one option is to install FUSE for macOS and use sshfs
to mount a remote directory:
mkdir local_dir
sshfs remote_user@remote_host:remote_dir/ local_dir
Some caveats apply with mounting network volumes, so YMMV.
I created a workaround with directive:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}]);
And the input tag becomes:
<input type="file" fileread="vm.uploadme" />
Or if just the file definition is needed:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
scope.$apply(function () {
scope.fileread = changeEvent.target.files[0];
// or all selected files:
// scope.fileread = changeEvent.target.files;
});
});
}
}
}]);
To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump
, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:
with g as outfile:
json.dump(hostDict, outfile,indent=2)
Using indent = 2
helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.
Do you want to convert int
s to char
s?:
int yourInt = 33;
char ch = (char) yourInt;
System.out.println(yourInt);
System.out.println(ch);
// Output:
// 33
// !
Or do you want to convert int
s to String
s?
int yourInt = 33;
String str = String.valueOf(yourInt);
Or what is it that you mean?
var empty struct{}
var ok bool
var m map[string]struct{}
m = make(map[string]struct{})
m["somestring"] = empty
_, ok = m["somestring"]
fmt.Println("somestring exists?", ok)
_, ok = m["not"]
fmt.Println("not exists?", ok)
Then, go run maps.go somestring exists? true not exists? false
It's been more than 10 years and not sure if anyone still finding this question or answer relevant.
But a quick workaround is just to wrap the asp control
within a html container
<div id="myElement" style="display: inline-block">
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
</div>
Whenever the Javascript Event
is triggered, if it needs to be an event by the asp control
, just wrap the asp control
around the div
container.
<div id="testG">
<asp:Button ID="Button2" runat="server" CssClass="btn" Text="Activate" />
</div>
The jQuery Code is below:
$(document).ready(function () {
$("#testG").click(function () {
$("#myElement").css("display", "none");
});
});
As @EastOcean said, We can add it by choosing Run/Debug configurations option. In my case, I have to set configuration for junit. So on clicking Edit configurations option, a pop up window is displayed. Then followed the below steps:
Save and run.
Thank you.
If you'd like to truncate a file to zero bytes, useful for clearing logs, try this:
:> file.log
In SQL Server Management Studio 2016, perform the following:
Right click on database
Click delete
Check close existing connections
Perform delete operation
<EditText
android:id="@id/editText" //id of editText
android:gravity="start" // Where to start Typing
android:inputType="textMultiLine" // multiline
android:imeOptions="actionDone" // Keyboard done button
android:minLines="5" // Min Line of editText
android:hint="@string/Enter Data" // Hint in editText
android:layout_width="match_parent" //width editText
android:layout_height="wrap_content" //height editText
/>
You can do this by using the following xml
<RelativeLayout
style="@style/GenericProgressBackground"
android:id="@+id/loadingPanel"
>
<ProgressBar
style="@style/GenericProgressIndicator"/>
</RelativeLayout>
With this style
<style name="GenericProgressBackground" parent="android:Theme">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">fill_parent</item>
<item name="android:background">#DD111111</item>
<item name="android:gravity">center</item>
</style>
<style name="GenericProgressIndicator" parent="@android:style/Widget.ProgressBar.Small">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:indeterminate">true</item>
</style>
To use this, you must hide your UI elements by setting the visibility value to GONE and whenever the data is loaded, call setVisibility(View.VISIBLE)
on all your views to restore them. Don't forget to call findViewById(R.id.loadingPanel).setVisiblity(View.GONE)
to hide the loading animation.
If you dont have a loading event/function but just want the loading panel to disappear after x seconds use a Handle to trigger the hiding/showing.
I don't know how good that solution is but it is definitely THE EASY ONE i just used in my app and it is working fine
you load the image like that
public void loadImage (){
Picasso picasso = Picasso.get();
picasso.setIndicatorsEnabled(true);
picasso.load(quiz.getImageUrl()).into(quizImage);
}
You can get the bimap
like that
Bitmap bitmap = Picasso.get().load(quiz.getImageUrl()).get();
Now covert that Bitmap
into a JPG
file and store in the in the cache, below is complete code for getting the bimap and caching it
Thread thread = new Thread() {
public void run() {
File file = new File(getCacheDir() + "/" +member.getMemberId() + ".jpg");
try {
Bitmap bitmap = Picasso.get().load(uri).get();
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100,new FileOutputStream(file));
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
})
the get()
method of Piccasso
need to be called on separate thread , i am saving that image also on that same thread.
Once the image is saved you can get all the files like that
List<File> files = new LinkedList<>(Arrays.asList(context.getExternalCacheDir().listFiles()));
now you can find the file you are looking for like below
for(File file : files){
if(file.getName().equals("fileyouarelookingfor" + ".jpg")){ // you need the name of the file, for example you are storing user image and the his image name is same as his id , you can call getId() on user to get the file name
Picasso.get() // if file found then load it
.load(file)
.into(mThumbnailImage);
return; // return
}
// fetch it over the internet here because the file is not found
}
I've come up with solution using Binding.DoNothing
returned from converter which doesn't break two-way binding.
public class EnumToCheckedConverter : IValueConverter
{
public Type Type { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && value.GetType() == Type)
{
try
{
var parameterFlag = Enum.Parse(Type, parameter as string);
if (Equals(parameterFlag, value))
{
return true;
}
}
catch (ArgumentNullException)
{
return false;
}
catch (ArgumentException)
{
throw new NotSupportedException();
}
return false;
}
else if (value == null)
{
return false;
}
throw new NotSupportedException();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && value is bool check)
{
if (check)
{
try
{
return Enum.Parse(Type, parameter as string);
}
catch(ArgumentNullException)
{
return Binding.DoNothing;
}
catch(ArgumentException)
{
return Binding.DoNothing;
}
}
return Binding.DoNothing;
}
throw new NotSupportedException();
}
}
Usage:
<converters:EnumToCheckedConverter x:Key="SourceConverter" Type="{x:Type monitor:VariableValueSource}" />
Radio button bindings:
<RadioButton GroupName="ValueSource"
IsChecked="{Binding Source, Converter={StaticResource SourceConverter}, ConverterParameter=Function}">Function</RadioButton>
Just (temporarily) killed my Macbook with
killall -u pu -m .
where pu is my userid. Watch the dot at the end of the command.
Also try
pkill -u pu
or
ps -o pid -u pu | xargs kill -1
If the types of the parameters are all the same (varchar2
for example), you can have a package like this which will do the following:
CREATE OR REPLACE PACKAGE testuser.test_pkg IS
TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);
END test_pkg;
CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
BEGIN
FOR i IN p_parm.first .. p_parm.last
LOOP
dbms_output.put_line(p_parm(i));
END LOOP;
END;
END test_pkg;
Then, to call it you'd need to set up the array and pass it:
DECLARE
l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
l_array(0) := 'hello';
l_array(1) := 'there';
testuser.test_pkg.your_proc(l_array);
END;
/
Assuming you use Python 2.7 (not 3):
print "I have", card.price
(as mentioned above).
print "I have %s" % card.price
(using string formatting)
print " ".join(map(str, ["I have", card.price]))
(by joining lists)
There are a lot of ways to do the same, actually. I would prefer the second one.
I have done it this way:
<?php
$PHPtext = "Your PHP alert!";
?>
var JavaScriptAlert = <?php echo json_encode($PHPtext); ?>;
alert(JavaScriptAlert); // Your PHP alert!
Static block can be used to show that a program can run without main function also.
//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
static
{
System.out.println("Welcome to Java");
System.exit(0);
}
}
In order to get the desired result, you must set "box-sizing: border-box" vs. the default which is "box-sizing: content-box". This is precisely the issue you are referring to (From MDN):
This is the initial and default value as specified by the CSS standard. The width and height properties are measured including only the content, but not the padding, border or margin.
The width and height properties include the content, the padding and border, but not the margin."
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing
Compatibility for this CSS is good.
Using javascript seems to be unnecessary if you choose CSS3.
By using :before
selector, you can do this in two lines of CSS. (no script involved).
Another advantage of this approach is that it does not rely on <label>
tag and works even it is missing.
Note: in browsers without CSS3 support, checkboxes will look normal. (backward compatible).
input[type=checkbox]:before { content:""; display:inline-block; width:12px; height:12px; background:red; }
input[type=checkbox]:checked:before { background:green; }?
You can see a demo here: http://jsfiddle.net/hqZt6/1/
and this one with images:
Below code worked fine for me. Please help me if tuning can be done. This gets all the keys even from the nested JSON objects.
public static void main(String args[]) {
String s = ""; // Sample JSON to be parsed
JSONParser parser = new JSONParser();
JSONObject obj = null;
try {
obj = (JSONObject) parser.parse(s);
@SuppressWarnings("unchecked")
List<String> parameterKeys = new ArrayList<String>(obj.keySet());
List<String> result = null;
List<String> keys = new ArrayList<>();
for (String str : parameterKeys) {
keys.add(str);
result = this.addNestedKeys(obj, keys, str);
}
System.out.println(result.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
public static List<String> addNestedKeys(JSONObject obj, List<String> keys, String key) {
if (isNestedJsonAnArray(obj.get(key))) {
JSONArray array = (JSONArray) obj.get(key);
for (int i = 0; i < array.length(); i++) {
try {
JSONObject arrayObj = (JSONObject) array.get(i);
List<String> list = new ArrayList<>(arrayObj.keySet());
for (String s : list) {
putNestedKeysToList(keys, key, s);
addNestedKeys(arrayObj, keys, s);
}
} catch (JSONException e) {
LOG.error("", e);
}
}
} else if (isNestedJsonAnObject(obj.get(key))) {
JSONObject arrayObj = (JSONObject) obj.get(key);
List<String> nestedKeys = new ArrayList<>(arrayObj.keySet());
for (String s : nestedKeys) {
putNestedKeysToList(keys, key, s);
addNestedKeys(arrayObj, keys, s);
}
}
return keys;
}
private static void putNestedKeysToList(List<String> keys, String key, String s) {
if (!keys.contains(key + Constants.JSON_KEY_SPLITTER + s)) {
keys.add(key + Constants.JSON_KEY_SPLITTER + s);
}
}
private static boolean isNestedJsonAnObject(Object object) {
boolean bool = false;
if (object instanceof JSONObject) {
bool = true;
}
return bool;
}
private static boolean isNestedJsonAnArray(Object object) {
boolean bool = false;
if (object instanceof JSONArray) {
bool = true;
}
return bool;
}
In case you want to deeply iterate into a complex (nested) object for each key & value, you can do so using Object.keys():
const iterate = (obj) => {
Object.keys(obj).forEach(key => {
console.log(`key: ${key}, value: ${obj[key]}`)
if (typeof obj[key] === 'object') {
iterate(obj[key])
}
})
}
In layman's terms, I've always said an API is like a translator between two people who speak different languages. In software, data can be consumed or distributed using an API (or translator) so that two different kinds of software can communicate. Good software has a strong translator (API) that follows rules and protocols for security and data cleanliness.
I"m a Marketer, not a coder. This all might not be quite right, but it's what I"ve tried to express for about 10 years now...
Well, you are using both frame.setSize()
and frame.pack()
.
You should use one of them at one time.
Using setSize()
you can give the size of frame you want but if you use pack()
, it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.
Try removing frame.pack()
from your code or putting it before setting size and then run it.
There is a solution starting with KitKat (4.4.2), called Immersive Mode: https://developer.android.com/training/system-ui/immersive.html
Basically, you should add this code to your onResume() method:
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
Here is my implementation of TRUNC function
private static object Tranc(List<Expression.Expression> p)
{
var target = (decimal)p[0].Evaluate();
// check if formula contains only one argument
var digits = p.Count > 1
? (decimal) p[1].Evaluate()
: 0;
return Math.Truncate((double)target * Math.Pow(10, (int)digits)) / Math.Pow(10, (int)digits);
}
var fd = new FormData();
//Get Form Values
var other_data = $('#form1').serializeArray();
$.each(other_data, function (key, input) {
fd.append(input.name, input.value);
});
//Get File Value
var $file = jq("#photoUpload").get(0);
if ($file.files.length > 0) {
for (var i = 0; i < $file.files.length; i++) {
fd.append('Photograph' + i, $file.files[i]);
}
}
$.ajax({
url: 'test.php',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
I did the following and it seems to work (even in iOS 8):
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
[[UIApplication sharedApplication] setStatusBarHidden:YES];
}
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
Only such dialog is FileDialog. Its part of WinForms, but its actually only wrapper around WinAPI standard OS file dialog. And I don't think it is ugly, its actually part of OS, so it looks like OS it is run on.
Other way, there is nothing to help you with. You either need to look for 3rd party implementation, either free (and I don't think there are any good) or paid.
If you right click on any result of "Edit Top 200 Rows" query in SSMS you will see the option "Pane -> SQL". It then shows the SQL Query that was run, which you can edit as you wish.
In SMSS 2012 and 2008, you can use Ctrl+3 to quickly get there.
I think you want to know the total entries count in a table! For that use this code..
SELECT count( * ) as Total_Entries FROM tbl_ifo;
About looping through a hash:
$Q = @{"ONE"="1";"TWO"="2";"THREE"="3"}
$Q.GETENUMERATOR() | % { $_.VALUE }
1
3
2
$Q.GETENUMERATOR() | % { $_.key }
ONE
THREE
TWO
In my case, display: block was breaking the design as intended.
The max-width
property just saved me.
and for styling, you can use text-overflow: ellipsis
as well.
my code was
max-width: 255px
overflow:hidden
I encourage you to read the Maven Book about multi-module (reactor) builds.
I meant in particular the following:
<parent>
<artifactId>xyz-application</artifactId>
<groupId>com.xyz</groupId>
<version>2.50.0.g</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.xyz</groupId>
<artifactId>xyz-Library</artifactId>
<version>2.50.0.g</version>
should be changed into. Here take care about the not defined version only in parent part it is defined.
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>xyz-application</artifactId>
<groupId>com.xyz</groupId>
<version>2.50.0.g</version>
</parent>
<groupId>com.xyz</groupId>
<artifactId>xyz-Library</artifactId>
This is a better link.
A slight change in the execute query will solve the problem:
DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId int
exec ('SELECT TOP 1 **''@siteId''** = Id FROM ' + @dbName + '..myTbl')
select @siteId
If your dictionary is Int
to String
you can do simply:
dict[3] = "efg"
If you mean adding elements to the value of the dictionary a possible solution:
var dict = Dictionary<String, Array<Int>>()
dict["key"]! += [1]
dict["key"]!.append(1)
dict["key"]?.append(1)
Below solution may help to someone.
I faced this issue, when I use implementation project(':my_project_other_modules') in the new module.
I discussed with my teammates and I finally I got the solution from one of the person, I have to use flavorDimensions & productFlavors. Because the app/build.gradle used flavorDimensions & productFlavors. When I add these in new module, the error didn't occur.
If you wanna create new list, use Stream.map
method:
List<Fruit> newList = fruits.stream()
.map(f -> new Fruit(f.getId(), f.getName() + "s", f.getCountry()))
.collect(Collectors.toList())
If you wanna modify current list, use Collection.forEach
:
fruits.forEach(f -> f.setName(f.getName() + "s"))
console.log
specifically is a method for developers to write code to inconspicuously inform the developers what the code is doing. It can be used to alert you that there's an issue, but shouldn't take the place of an interactive debugger when it comes time to debug the code. Its asynchronous nature means that the logged values don't necessarily represent the value when the method was called.
In short: log errors with console.log
(if available), then fix the errors using your debugger of choice: Firebug, WebKit Developer Tools (built-in to Safari and Chrome), IE Developer Tools or Visual Studio.
A word of caution. Stringing together several not
selectors increases the specificity of the resulting selector, which makes it harder to override: you'll basically need to find the selector with all the nots and copy-paste it into your new selector.
A not(X or Y)
selector would be great to avoid inflating specificity, but I guess we'll have to stick to combining the opposites, like in this answer.
To check battery percentage we use BatteryManager, the following method will return battery percentage.
Source Link
public static float getBatteryLevel(Context context, Intent intent) {
Intent batteryStatus = context.registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int batteryLevel = -1;
int batteryScale = 1;
if (batteryStatus != null) {
batteryLevel = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, batteryLevel);
batteryScale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, batteryScale);
}
return batteryLevel / (float) batteryScale * 100;
}
Be carful adding {data-dismiss="modal"} as mentioned in the second answer. When working with Angulars ng-commit using a controller-scope-defined function the data-dismiss will be executed first and controller-scope-defined function is never called. I spend an hour to figure this out.
EDIT: Thanks for the comments - I looked it up in the C99 standard, which says in section 6.5.3.4:
The value of the result is implementation-defined, and its type (an unsigned integer type) is
size_t
, defined in<stddef.h>
(and other headers)
So, the size of size_t
is not specified, only that it has to be an unsigned integer type. However, an interesting specification can be found in chapter 7.18.3 of the standard:
limit of
size_t
SIZE_MAX 65535
Which basically means that, irrespective of the size of size_t
, the allowed value range is from 0-65535, the rest is implementation dependent.
To use this function/method,you need an instance of the class Date .
This method is always used in conjunction with a Date object.
See the code below :
var d = new Date();
d.getTime();
I'll add my solution here. We can use floor when values are above 0 and ceil when they are less than zero:
function truncateToInt(x)
{
if(x > 0)
{
return Math.floor(x);
}
else
{
return Math.ceil(x);
}
}
Then:
y = truncateToInt(2.9999); // results in 2
y = truncateToInt(-3.118); //results in -3
Notice: This answer was written when Math.trunc(x)
was fairly new and not supported by a lot of browsers. Today, modern browsers support Math.trunc(x)
.
If it's reasonable to alter the original Map
data structure to be serialized to better represent the actual value wanted to be serialized, that's probably a decent approach, which would possibly reduce the amount of Jackson configuration necessary. For example, just remove the null
key entries, if possible, before calling Jackson. That said...
To suppress serializing Map
entries with null values:
Before Jackson 2.9
you can still make use of WRITE_NULL_MAP_VALUES
, but note that it's moved to SerializationFeature
:
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
Since Jackson 2.9
The WRITE_NULL_MAP_VALUES
is deprecated, you can use the below equivalent:
mapper.setDefaultPropertyInclusion(
JsonInclude.Value.construct(Include.ALWAYS, Include.NON_NULL))
To suppress serializing properties with null values, you can configure the ObjectMapper
directly, or make use of the @JsonInclude
annotation:
mapper.setSerializationInclusion(Include.NON_NULL);
or:
@JsonInclude(Include.NON_NULL)
class Foo
{
public String bar;
Foo(String bar)
{
this.bar = bar;
}
}
To handle null Map
keys, some custom serialization is necessary, as best I understand.
A simple approach to serialize null
keys as empty strings (including complete examples of the two previously mentioned configurations):
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
public class JacksonFoo
{
public static void main(String[] args) throws Exception
{
Map<String, Foo> foos = new HashMap<String, Foo>();
foos.put("foo1", new Foo("foo1"));
foos.put("foo2", new Foo(null));
foos.put("foo3", null);
foos.put(null, new Foo("foo4"));
// System.out.println(new ObjectMapper().writeValueAsString(foos));
// Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?)
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer());
System.out.println(mapper.writeValueAsString(foos));
// output:
// {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}}
}
}
class MyNullKeySerializer extends JsonSerializer<Object>
{
@Override
public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused)
throws IOException, JsonProcessingException
{
jsonGenerator.writeFieldName("");
}
}
class Foo
{
public String bar;
Foo(String bar)
{
this.bar = bar;
}
}
To suppress serializing Map
entries with null
keys, further custom serialization processing would be necessary.
This question has already been answered, but for some extra information at the time of Swift 4:
In case of performance, you should reserve memory for the array, in case of dynamically creating it, such as adding elements with Array.append()
.
var array = [SKSpriteNode]()
array.reserveCapacity(64)
for _ in 0..<64 {
array.append(SKSpriteNode())
}
If you know the minimum amount of elements you'll add to it, but not the maximum amount, you should rather use array.reserveCapacity(minimumCapacity: 64)
.
No need for the specificity .navbar-default
in your CSS. Background color requires background-color:#cc333333
(or just background:#cc3333
). Finally, probably best to consolidate all your customizations into a single class, as below:
.navbar-custom {
color: #FFFFFF;
background-color: #CC3333;
}
..
<div id="menu" class="navbar navbar-default navbar-custom">
Example: http://www.bootply.com/OusJAAvFqR#
explode('.', $string)
If you know your string has a fixed number of components you could use something like
list($a, $b) = explode('.', 'object.attribute');
echo $a;
echo $b;
Prints:
object
attribute
I created dedicated class that implements View.OnClickListener.
public class ButtonClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
}
}
Then, I created an instance of this class in MainActivity
private ButtonClickListener onClickBtnListener = new ButtonClickListener();
and then set onClickListener for button
btn.setOnClickListener(onClickBtnListener);
read
Here's an example that uses read
to get the password and store it in the variable pass
. Then, 7z
uses the password to create an encrypted archive:
read -s -p "Enter password: " pass && 7z a archive.zip a_file -p"$pass"; unset pass
But be aware that the password can easily be sniffed.
Is the access modifier of this constructor protected or package?
I think implicitly your constructors access modifier would be your class's access modifier. as your class has public access, constructor would have public access implicitly
The only way to project a collection that is not linear time is to do so lazily, where the resulting "vector" is actually a subtype which delegates to the original collection. For example, Scala's List#subseq
method create a sub-sequence in constant time. However, this only works if the collection is immutable and if the underlying language sports garbage collection.
My approach is very close to Garret Wilson's (thanks, I voted you up ;)
In addition it provides downward compatibility with Android < 3.
I just recognized that my solution is even closer to the one by Kevin Remo. It's just a wee bit cleaner (as it does not rely on the "expection" antipattern).
public class MyPreferenceActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
onCreatePreferenceActivity();
} else {
onCreatePreferenceFragment();
}
}
/**
* Wraps legacy {@link #onCreate(Bundle)} code for Android < 3 (i.e. API lvl
* < 11).
*/
@SuppressWarnings("deprecation")
private void onCreatePreferenceActivity() {
addPreferencesFromResource(R.xml.preferences);
}
/**
* Wraps {@link #onCreate(Bundle)} code for Android >= 3 (i.e. API lvl >=
* 11).
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void onCreatePreferenceFragment() {
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new MyPreferenceFragment ())
.commit();
}
}
For a "real" (but more complex) example see NusicPreferencesActivity and NusicPreferencesFragment.
Another option is to use Homebrew which works on Linux and macOS to install just the supporting libraries:
brew install libpq
then
brew link libpq --force
(the --force
option is required because it conflicts with the postgres formula.)
Use the fnReloadAjax() by the DataTables.net author.
I'm copying the source code below - in case the original ever moves:
$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
{
if ( typeof sNewSource != 'undefined' && sNewSource != null )
{
oSettings.sAjaxSource = sNewSource;
}
this.oApi._fnProcessingDisplay( oSettings, true );
var that = this;
var iStart = oSettings._iDisplayStart;
var aData = [];
this.oApi._fnServerParams( oSettings, aData );
oSettings.fnServerData( oSettings.sAjaxSource, aData, function(json) {
/* Clear the old information from the table */
that.oApi._fnClearTable( oSettings );
/* Got the data - add it to the table */
var aData = (oSettings.sAjaxDataProp !== "") ?
that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
for ( var i=0 ; i<aData.length ; i++ )
{
that.oApi._fnAddData( oSettings, aData[i] );
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
that.fnDraw();
if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
{
oSettings._iDisplayStart = iStart;
that.fnDraw( false );
}
that.oApi._fnProcessingDisplay( oSettings, false );
/* Callback user function - for event handlers etc */
if ( typeof fnCallback == 'function' && fnCallback != null )
{
fnCallback( oSettings );
}
}, oSettings );
}
/* Example call to load a new file */
oTable.fnReloadAjax( 'media/examples_support/json_source2.txt' );
/* Example call to reload from original file */
oTable.fnReloadAjax();
The @jfriend00's answer helps me to understand the technique to animate only remove class (not add).
A "base" class should have transition
property (like transition: 2s linear all;
). This enables animations when any other class is added or removed on this element. But to disable animation when other class is added (and only animate class removing) we need to add transition: none;
to the second class.
Example
CSS:
.issue {
background-color: lightblue;
transition: 2s linear all;
}
.recently-updated {
background-color: yellow;
transition: none;
}
HTML:
<div class="issue" onclick="addClass()">click me</div>
JS (only needed to add class):
var timeout = null;
function addClass() {
$('.issue').addClass('recently-updated');
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(function () {
$('.issue').removeClass('recently-updated');
}, 1000);
}
plunker of this example.
With this code only removing of recently-updated
class will be animated.
Here are some useful links:
The 2nd column is the keyCode and the html column shows how it will displayed. You can test it here.
I just simply forget running the Docker Desktop in my mac, after running Docker Desktop, you will be good to go.
Correct solution is to copy or install to /usr/local/bin
not /usr/bin
.This is due to System Integrity Protection (SIP). SIP makes /usr/bin
read-only but leaves /usr/local
as read-write.
SIP should not be disabled as stated in the answer above because it adds another layer of protection against malware gaining root access. Here is a complete explanation of what SIP does and why it is useful.
As suggested in this answer one should not disable SIP (rootless mode) "It is not recommended to disable rootless mode! The best practice is to install custom stuff to "/usr/local" only."
I think an elegant solution is to use the where
method (also see the API docs
):
In [37]: values = df.Prices * df.Amount
In [38]: df['Values'] = values.where(df.Action == 'Sell', other=-values)
In [39]: df
Out[39]:
Prices Amount Action Values
0 3 57 Sell 171
1 89 42 Sell 3738
2 45 70 Buy -3150
3 6 43 Sell 258
4 60 47 Sell 2820
5 19 16 Buy -304
6 56 89 Sell 4984
7 3 28 Buy -84
8 56 69 Sell 3864
9 90 49 Buy -4410
Further more this should be the fastest solution.
This isn't exactly an "asking for yes or no" but just a hack: alias the hg push ...
not to hgpushrepo
but to hgpushrepoconfirmedpush
and by the time I can spell out the whole thing, the left brain has made a logical choice.
I`ve added
initSelection: function (element, callback) {
callback({ id: 1, text: 'Text' });
}
BUT also
.select2('val', []);
at the end.
This solved my issue.
Resetting the src attribute directly:
iframe.src = iframe.src;
Resetting the src with a time stamp for cache busting:
iframe.src = iframe.src.split("?")[0] + "?_=" + new Date().getTime();
Clearing the src when query strings option is not possible (Data URI):
var wasSrc = iframe.src
iframe.onload = function() {
iframe.onload = undefined;
iframe.src = wasSrc;
}
Easiest solution for this to remove the index.php code which is allocated on
xammp-> htdocs-> index.php
you can delete the code of this page to solution your problem but have another way which is .htaccss file. Some time you show this problem because of have some issue or miss code on .htaccss file thas way yo saw the xammp dashboard every time. Hop it will resolve your problem. Happy Coding and Good Luck
They are just \r\n and \n
are variants.
\r\n
is used in windows
\n
is used in mac and linux
Alternate solution can be:
baseKey hKeyLocalMachine = baseKey.HKEY_LOCAL_MACHINE;
uint value = (uint)hKeyLocalMachine;
Or just:
uint value = (uint)baseKey.HKEY_LOCAL_MACHINE;