Firstly, you should read this page thoroughly http://codex.wordpress.org/AJAX_in_Plugins
Secondly, ajax_script
is not defined so you should change to: url: ajaxurl
. I don't see your function1()
in the above code but you might already define it in other file.
And finally, learn how to debug ajax call using Firebug, network and console tab will be your friends. On the PHP side, print_r()
or var_dump()
will be your friends.
Enclose the field in quotes, e.g.
field1_value,field2_value,"field 3,value",field4, etc...
See wikipedia.
Updated:
To encode a quote, use "
, one double quote symbol in a field will be encoded as ""
, and the whole field will become """"
. So if you see the following in e.g. Excel:
---------------------------------------
| regular_value |,,,"| ,"", |""" |"|
---------------------------------------
the CSV file will contain:
regular_value,",,,""",","""",","""""""",""""
A comma is simply encapsulated using quotes, so ,
becomes ","
.
A comma and quote needs to be encapsulated and quoted, so ","
becomes ""","""
.
I like things to happen automatically and for bins to fall on "nice" values. The following seems to work quite well.
import numpy as np
import numpy.random as random
import matplotlib.pyplot as plt
def compute_histogram_bins(data, desired_bin_size):
min_val = np.min(data)
max_val = np.max(data)
min_boundary = -1.0 * (min_val % desired_bin_size - min_val)
max_boundary = max_val - max_val % desired_bin_size + desired_bin_size
n_bins = int((max_boundary - min_boundary) / desired_bin_size) + 1
bins = np.linspace(min_boundary, max_boundary, n_bins)
return bins
if __name__ == '__main__':
data = np.random.random_sample(100) * 123.34 - 67.23
bins = compute_histogram_bins(data, 10.0)
print(bins)
plt.hist(data, bins=bins)
plt.xlabel('Value')
plt.ylabel('Counts')
plt.title('Compute Bins Example')
plt.grid(True)
plt.show()
The result has bins on nice intervals of bin size.
[-70. -60. -50. -40. -30. -20. -10. 0. 10. 20. 30. 40. 50. 60.]
This is how I handle this, without using exceptions.
import sys
if sys.version_info.major > 2: # Python 3 or later
from urllib.parse import quote
else: # Python 2
from urllib import quote
Show whitespace characters in Visual Studio Code
change the setting.json, by adding the following codes!
// Place your settings in this file to overwrite default and user settings.
{
"editor.renderWhitespace": "all"
}
just like this!
(PS: there is no "true" option!, even it also works.)
Based on the other answers to this question, I've implemented a new approach using bcrypt.
If I understand correctly, the argument to use bcrypt
over SHA512
is that bcrypt
is designed to be slow. bcrypt
also has an option to adjust how slow you want it to be when generating the hashed password for the first time:
# The '12' is the number that dictates the 'slowness'
bcrypt.hashpw(password, bcrypt.gensalt( 12 ))
Slow is desirable because if a malicious party gets their hands on the table containing hashed passwords, then it is much more difficult to brute force them.
def get_hashed_password(plain_text_password):
# Hash a password for the first time
# (Using bcrypt, the salt is saved into the hash itself)
return bcrypt.hashpw(plain_text_password, bcrypt.gensalt())
def check_password(plain_text_password, hashed_password):
# Check hashed password. Using bcrypt, the salt is saved into the hash itself
return bcrypt.checkpw(plain_text_password, hashed_password)
I was able to install the library pretty easily in a linux system using:
pip install py-bcrypt
However, I had more trouble installing it on my windows systems. It appears to need a patch. See this Stack Overflow question: py-bcrypt installing on win 7 64bit python
Why not create a viewmodel with a simple string parameter and then pass that to the view? It has the benefit of being extensible (i.e. you can then add any other things you may want to set in your controller) and it's fairly simple.
public class MyViewModel
{
public string YourString { get; set; }
}
In the view
@model MyViewModel
@Html.Label(model => model.YourString)
In the controller
public ActionResult Index()
{
myViewModel = new MyViewModel();
myViewModel.YourString = "However you are setting this."
return View(myViewModel)
}
var ul = document.getElementById("yourElementId");
while (ul.firstChild)
ul.removeChild(ul.firstChild);
if you handel this from dataBase try :
<img :src="baseUrl + 'path/path' + obj.key +'.png'">
The two functions you need are documented here:
In short:
// Load images in the C++ format
cv::Mat img = cv::imread("something.jpg");
cv::Mat src = cv::imread("src.jpg");
// Resize src so that is has the same size as img
cv::resize(src, src, img.size());
And please, please, stop using the old and completely deprecated IplImage* classes
After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))
HTML:
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>
jQuery:
$(function(){
$('#uploadBTN').on('click', function(){
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
In the upload.php
file you can access the data passed with $_FILES['file']
.
Thanks everyone for trying to help:)
I took the answer from here (with some changes) MDN
I like to use the tr -s command for this
ps aux | tr -s [:blank:] | cut -d' ' -f3
This squeezes all white spaces down to 1 space. This way telling cut to use a space as a delimiter is honored as expected.
change_column :things, :price_1, :integer, default: 123, null: false
Seems to be best way to add a default to an existing column that doesn't have null: false
already.
Otherwise:
change_column :things, :price_1, :integer, default: 123
Some research I did on this:
https://gist.github.com/Dorian/417b9a0e1a4e09a558c39345d50c8c3b
The bash script "corstest" below works for me. It is based on Jun's comment above.
usage
corstest [-v] url
examples
./corstest https://api.coindesk.com/v1/bpi/currentprice.json
https://api.coindesk.com/v1/bpi/currentprice.json Access-Control-Allow-Origin: *
the positive result is displayed in green
./corstest https://github.com/IonicaBizau/jsonrequest
https://github.com/IonicaBizau/jsonrequest does not support CORS
you might want to visit https://enable-cors.org/ to find out how to enable CORS
the negative result is displayed in red and blue
the -v option will show the full curl headers
corstest
#!/bin/bash
# WF 2018-09-20
# https://stackoverflow.com/a/47609921/1497139
#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'
red='\033[0;31m'
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'
#
# a colored message
# params:
# 1: l_color - the color of the message
# 2: l_msg - the message to display
#
color_msg() {
local l_color="$1"
local l_msg="$2"
echo -e "${l_color}$l_msg${endColor}"
}
#
# show the usage
#
usage() {
echo "usage: [-v] $0 url"
echo " -v |--verbose: show curl result"
exit 1
}
if [ $# -lt 1 ]
then
usage
fi
# commandline option
while [ "$1" != "" ]
do
url=$1
shift
# optionally show usage
case $url in
-v|--verbose)
verbose=true;
;;
esac
done
if [ "$verbose" = "true" ]
then
curl -s -X GET $url -H 'Cache-Control: no-cache' --head
fi
origin=$(curl -s -X GET $url -H 'Cache-Control: no-cache' --head | grep -i access-control)
if [ $? -eq 0 ]
then
color_msg $green "$url $origin"
else
color_msg $red "$url does not support CORS"
color_msg $blue "you might want to visit https://enable-cors.org/ to find out how to enable CORS"
fi
I think you should cast the pointers to (void *) to get rid of the warnings.
memcpy((void *)&RTCclk, (void *)&RTCclkBuffert, sizeof RTCclk);
Also you have use sizeof without brackets, you can use this with variables but if RTCclk was defined as an array, sizeof of will return full size of the array. If you use use sizeof with type you should use with brackets.
sizeof(struct RTCclk)
],\s*
],\n
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static MainActivity instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
instance = this;
}
public static MainActivity getInstance() {
return instance;
}
public void myMethod() {
// do something...
}
)
AnotherClass.java
public Class AnotherClass() {
// call this method
MainActivity.getInstance().myMethod();
}
You need to run it using bash
executable like this:
Runtime.getRuntime().exec("/bin/bash -c your_command");
Update: As suggested by xav, it is advisable to use ProcessBuilder instead:
String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start();
Check your problem is solved.
FWIW, Codegear C++Builder doesn't destruct in the expected order according to the standard.
C:\> sample.exe 1 2
Created in foo
Created in if
Destroyed in foo
Destroyed in if
... which is another reason not to rely on the destruction order!
I was just wondering how most people fetch a mime type from a file in Java?
I've published my SimpleMagic Java package which allows content-type (mime-type) determination from files and byte arrays. It is designed to read and run the Unix file(1) command magic files that are a part of most ~Unix OS configurations.
I tried Apache Tika but it is huge with tons of dependencies, URLConnection
doesn't use the bytes of the files, and MimetypesFileTypeMap
also just looks at files names.
With SimpleMagic you can do something like:
// create a magic utility using the internal magic file
ContentInfoUtil util = new ContentInfoUtil();
// if you want to use a different config file(s), you can load them by hand:
// ContentInfoUtil util = new ContentInfoUtil("/etc/magic");
...
ContentInfo info = util.findMatch("/tmp/upload.tmp");
// or
ContentInfo info = util.findMatch(inputStream);
// or
ContentInfo info = util.findMatch(contentByteArray);
// null if no match
if (info != null) {
String mimeType = info.getMimeType();
}
Sharing the solution which worked for me, which may help someone
Issue when compiling for simulator:
building for iOS Simulator, but linking in object file built for iOS, for architecture arm64
XCODE 12.1, POD 1.9.1
My Project structure
arm64
to Build settings -> Exclude Architecture
in all the targets.arm64
from VALID_ARCHS
and added x86_64
in all the targets.Add following code in podfile
post_install do |installer|
installer.pods_project.build_configurations.each do |config|
config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
end
end
Did pod update
, deleted podfile.lock
, and did pod install
Do clean build.
Now I am using the browser kit like this:
{
border-radius: 7px;
-webkit-border-radius: 7px;
-moz-border-radius: 7px;
}
I whipped up a quick (Jquery only) plugin, that saves the value in a data field while an input is disabled. This just means as long as the field is being disabled programmaticly through jquery using .prop() or .attr()... then accessing the value by .val(), .serialize() or .serializeArra() will always return the value even if disabled :)
Shameless plug: https://github.com/Jezternz/jq-disabled-inputs
What you suggest is impossible. You will always have collisions.
In order to map two objects to another single set, the mapped set must have a minimum size of the number of combinations expected:
Assuming a 32-bit integer, you have 2147483647 positive integers. Choosing two of these where order doesn't matter and with repetition yields 2305843008139952128 combinations. This does not fit nicely in the set of 32-bit integers.
You can, however fit this mapping in 61 bits. Using a 64-bit integer is probably easiest. Set the high word to the smaller integer and the low word to the larger one.
I would recommend this (just found via search):
You have your storyboard set up to expect an outlet called tableView
but the actual outlet name is myTableView
.
If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.
The suggestions don't work because they are for the standard MySQL driver, not for mysqli:
$this->db_link->error
contains the error if one did occur
Or
mysqli_error($this->db_link)
will work.
What I have just experiment with VS diagnostic tools is I called this.Close() then formclosing event triggered. Then When I call this.Dispose() at the end in Formclosing event where I dispose many other objects in it, it cleans everything much much smoother.
Parameters are key-value pairs that can appear inside URL path, and start with a semicolon character (;
).
Query string appears after the path (if any) and starts with a question mark character (?
).
Both parameters and query string contain key-value pairs.
In a GET
request, parameters appear in the URL itself:
<scheme>://<username>:<password>@<host>:<port>/<path>;<parameters>?<query>#<fragment>
In a POST
request, parameters can appear in the URL itself, but also in the datastream (as known as content).
Query string is always a part of the URL.
Parameters can be buried in form-data
datastream when using POST method so they may not appear in the URL. Yes a POST
request can define parameters as form data and in the URL, and this is not inconsistent because parameters can have several values.
I've found no explaination for this behavior so far. I guess it might be useful sometimes to "unhide" parameters from a POST
request, or even let the code handling a GET
request share some parts with the code handling a POST
. Of course this can work only with server code supporting parameters in a URL.
Until you get better insights, I suggest you to use parameters only in form-data
datastream of POST
requests.
Sources:
If you want to make the reverse of what you showed consider doing this:
.tint:hover:before {
background: rgba(0,0,250, 0.5);
}
.t2:before {
background: none;
}
and look at the effect on the 2nd picture.
Is it supposed to look like this?
<script>
function subadd(){
subadd= parseFloat(document.forms[0][0].value) + parseFloat(document.forms[0][1].value)
window.alert(subadd)
}
</script>
<body>
<form>
<input type="text" >+
<input type="text" >
<input type="button" value="add" onclick="subadd()">
</form>
</body>
I was trying to call a REST endpoint from a microservice and I was using the resttemplate's put method.
In my design if any error occurred inside the REST endpoint it should return a JSON error response, it was working for some calls but not for this put one, it returned the white label error page instead.
So I did some investigation and I found out that;
Spring try to understand the caller if it is a machine then it returns JSON response or if it is a browser than it returns the white label error page HTML.
As a result: my client app needed to say to REST endpoint that the caller is a machine, not a browser so for this the client app needed to add 'application/json' into the ACCEPT header explicitly for the resttemplate's 'put' method. I added this to the header and solved the problem.
my call to the endpoint:
restTemplate.put(url, request, param1, param2);
for above call I had to add below header param.
headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
or I tried to change put to exchange as well, in this case, exchange call added the same header for me and solved the problem too but I don't know why :)
restTemplate.exchange(....)
To create list of lists, you need to separate them with commas, like this
coin_args = [
["pennies", '2.5', '50.0', '.01'],
["nickles", '5.0', '40.0', '.05'],
["dimes", '2.268', '50.0', '.1'],
["quarters", '5.67', '40.0', '.25']
]
in headers set
content-type : application/x-www-form-urlencoded
In body select option
x-www-form-urlencoded
and insert data as json array
user_ids : ["1234", "5678"]
First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:
ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");
Then inject the mock into m_orderSvc and call your method.
m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
Finally, verify that the mock was called properly:
verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");
You can add an image resource in the project then (right click on the project and choose the Properties item) access that in this way:
this.picturebox.image = projectname.properties.resources.imagename;
You are using two WHERE
clauses but only one is allowed. Use it like this:
SELECT table1.f_id FROM table1
INNER JOIN table2 ON table2.f_id = table1.f_id
WHERE
table1.f_com_id = '430'
AND table1.f_status = 'Submitted'
AND table2.f_type = 'InProcess'
Added in PHP 8.0
It's the NullSafe Operator
, it returns null
in case you try to invoke functions or get values from null
. Nullsafe operator can be chained and can be used both on the methods and properties.
$objDrive = null;
$drive = $objDrive?->func?->getDriver()?->value; //return null
$drive = $objDrive->func->getDriver()->value; // Error: Trying to get property 'func' of non-object
Nullsafe operator doesn't work with array keys:
$drive['admin']?->getDriver()?->value //Warning: Trying to access array offset on value of type null
$drive = [];
$drive['admin']?->getAddress()?->value //Warning: Undefined array key "admin"
my approach is swapping the first and last element of the array
int i,j;
for ( i = 0,j = size - 1 ; i < j ; i++,j--)
{
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
Change var left: Node? = null
to lateinit var left: Node
. Problem solved.
You can write an object that behaves like a dict
quite easily with ABCs (Abstract Base Classes) from the collections.abc
module. It even tells you if you missed a method, so below is the minimal version that shuts the ABC up.
from collections.abc import MutableMapping
class TransformedDict(MutableMapping):
"""A dictionary that applies an arbitrary key-altering
function before accessing the keys"""
def __init__(self, *args, **kwargs):
self.store = dict()
self.update(dict(*args, **kwargs)) # use the free update to set keys
def __getitem__(self, key):
return self.store[self._keytransform(key)]
def __setitem__(self, key, value):
self.store[self._keytransform(key)] = value
def __delitem__(self, key):
del self.store[self._keytransform(key)]
def __iter__(self):
return iter(self.store)
def __len__(self):
return len(self.store)
def _keytransform(self, key):
return key
You get a few free methods from the ABC:
class MyTransformedDict(TransformedDict):
def _keytransform(self, key):
return key.lower()
s = MyTransformedDict([('Test', 'test')])
assert s.get('TEST') is s['test'] # free get
assert 'TeSt' in s # free __contains__
# free setdefault, __eq__, and so on
import pickle
# works too since we just use a normal dict
assert pickle.loads(pickle.dumps(s)) == s
I wouldn't subclass dict
(or other builtins) directly. It often makes no sense, because what you actually want to do is implement the interface of a dict
. And that is exactly what ABCs are for.
For deleting all data:
HTML FILE
class="btn btn-primary" href="{% url 'delete_product'%}">Delete
Put the above code in an anchor tag. (the a tag!)
url.py
path('delete_product', views.delete_product, name='delete_product')]
views.py
def delete_product(request):
if request.method == "GET":
dest = Racket.objects.all()
dest.delete()
return render(request, "admin_page.html")
Declare
public static int[] locations={1,2,3};
outside of the main method.
The best solution ever.
Array.prototype.checkIfArrayIsUnique = function() {
this.sort();
for ( var i = 1; i < this.length; i++ ){
if(this[i-1] == this[i])
return false;
}
return true;
}
df.loc[df['A'] == df['B'], 'C'] = 0
df.loc[df['A'] > df['B'], 'C'] = 1
df.loc[df['A'] < df['B'], 'C'] = -1
Easy to solve using indexing. The first line of code reads like so, if column A
is equal to column B
then create and set column C
equal to 0.
This is very simple and easily manage.
jQuery(document).ready(function(){
jQuery("#search").click(function(){
jQuery("#loader").show("slow");
jQuery("#response_result").hide("slow");
jQuery.post(siteurl+"/ajax.php?q="passyourdata, function(response){
setTimeout("finishAjax('response_result', '"+escape(response)+"')", 850);
});
});
})
function finishAjax(id,response){
jQuery("#loader").hide("slow");
jQuery('#response_result').html(unescape(response));
jQuery("#"+id).show("slow");
return true;
}
Instant stop =
myUtilDateStart.toInstant()
.plus( Duration.ofMinutes( x ) )
;
Other Answers are correct, especially the Answer by Borgwardt. But those Answers use outmoded legacy classes.
The original date-time classes bundled with Java have been supplanted with java.time classes. Perform your business logic in java.time types. Convert to the old types only where needed to work with old code not yet updated to handle java.time types.
If your Calendar
is actually a GregorianCalendar
you can convert to a ZonedDateTime
. Find new methods added to the old classes to facilitate conversion to/from java.time types.
if( myUtilCalendar instanceof GregorianCalendar ) {
GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; // Downcasting from the interface to the concrete class.
ZonedDateTime zdt = gregCal.toZonedDateTime(); // Create `ZonedDateTime` with same time zone info found in the `GregorianCalendar`
end if
If your Calendar
is not a Gregorian
, call toInstant
to get an Instant
object. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myCal.toInstant();
Similarly, if starting with a java.util.Date
object, convert to an Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
Apply a time zone to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
To get a java.util.Date
object, go through the Instant
.
java.util.Date utilDate = java.util.Date.from( zdt.toInstant() );
For more discussion of converting between the legacy date-time types and java.time, and a nifty diagram, see my Answer to another Question.
Duration
Represent the span of time as a Duration
object. Your input for the duration is a number of minutes as mentioned in the Question.
Duration d = Duration.ofMinutes( yourMinutesGoHere );
You can add that to the start to determine the stop.
Instant stop = startInstant.plus( d );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Set it to use as much memory as it wants with:
COMPOSER_MEMORY_LIMIT=-1 composer update
I will use CXF also you can think of AXIS 2 .
The best way to do it may be using JAX RS Refer this example
Example:
wsimport -p stockquote http://stockquote.xyz/quote?wsdl
This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.
I
You can print the request type using:
request.getMethod();
You can print all the headers as mentioned here:
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println("Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
}
To print all the request params, use this:
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = params.nextElement();
System.out.println("Parameter Name - "+paramName+", Value - "+request.getParameter(paramName));
}
request
is the instance of HttpServletRequest
You can beautify the outputs as you desire.
Have you looked at angular-ui bootstrap? There's a Dialog (ui.bootstrap.dialog) directive that works quite well. You can close the dialog during the call back the angular way (per the example):
$scope.close = function(result){
dialog.close(result);
};
Update:
The directive has since been renamed Modal.
I haven't needed to turn on anti-alias because it's on by default but I have needed to turn it off. And if it can be turned off it can also be turned on.
ctx.imageSmoothingEnabled = true;
I usually shut it off when I'm working on my canvas rpg so when I zoom in the images don't look blurry.
my_function = function(hash) { /* use hash.options and hash.content */ };
and then call:
my_function ({ options: options });
my_function ({ options: options, content: content });
For accounting applications it's very common to store the values as integers (some even go so far as to say it's the only way). To get an idea, take the amount of the transactions (let's suppose $100.23) and multiple by 100, 1000, 10000, etc. to get the accuracy you need. So if you only need to store cents and can safely round up or down, just multiply by 100. In my example, that would make 10023 as the integer to store. You'll save space in the database and comparing two integers is much easier than comparing two floats. My $0.02.
For understanding templates, it's of huge advantage to get the terminology straight because the way you speak about them determines the way to think about them.
Specifically, Area
is not a template class, but a class template. That is, it is a template from which classes can be generated. Area<int>
is such a class (it's not an object, but of course you can create an object from that class in the same ways you can create objects from any other class). Another such class would be Area<char>
. Note that those are completely different classes, which have nothing in common except for the fact that they were generated from the same class template.
Since Area
is not a class, you cannot derive the class Rectangle
from it. You only can derive a class from another class (or several of them). Since Area<int>
is a class, you could, for example, derive Rectangle
from it:
class Rectangle:
public Area<int>
{
// ...
};
Since Area<int>
and Area<char>
are different classes, you can even derive from both at the same time (however when accessing members of them, you'll have to deal with ambiguities):
class Rectangle:
public Area<int>,
public Area<char>
{
// ...
};
However you have to specify which classed to derive from when you define Rectangle
. This is true no matter whether those classes are generated from a template or not. Two objects of the same class simply cannot have different inheritance hierarchies.
What you can do is to make Rectangle
a template as well. If you write
template<typename T> class Rectangle:
public Area<T>
{
// ...
};
You have a template Rectangle
from which you can get a class Rectangle<int>
which derives from Area<int>
, and a different class Rectangle<char>
which derives from Area<char>
.
It may be that you want to have a single type Rectangle
so that you can pass all sorts of Rectangle
to the same function (which itself doesn't need to know the Area type). Since the Rectangle<T>
classes generated by instantiating the template Rectangle
are formally independent of each other, it doesn't work that way. However you can make use of multiple inheritance here:
class Rectangle // not inheriting from any Area type
{
// Area independent interface
};
template<typename T> class SpecificRectangle:
public Rectangle,
public Area<T>
{
// Area dependent stuff
};
void foo(Rectangle&); // A function which works with generic rectangles
int main()
{
SpecificRectangle<int> intrect;
foo(intrect);
SpecificRectangle<char> charrect;
foo(charrect);
}
If it is important that your generic Rectangle
is derived from a generic Area
you can do the same trick with Area
too:
class Area
{
// generic Area interface
};
class Rectangle:
public virtual Area // virtual because of "diamond inheritance"
{
// generic rectangle interface
};
template<typename T> class SpecificArea:
public virtual Area
{
// specific implementation of Area for type T
};
template<typename T> class SpecificRectangle:
public Rectangle, // maybe this should be virtual as well, in case the hierarchy is extended later
public SpecificArea<T> // no virtual inheritance needed here
{
// specific implementation of Rectangle for type T
};
If you have a specific (legacy) version of VSCode on your offline instance, pulling the latest extensions might not properly integrate.
To make sure that VSCode and the extensions work together, they must all be installed together on the online machine. This resolves any dependencies (with specific versions), and ensures the exact configuration of the offline instance.
Install the VSCode version, turn off updating, and install the extensions. Copy the extensions from the installed location and place them on the target machine.
Install the exact version of VSCode on online machine. Then turn off updates by going to File -> Preferences -> Settings
. In the Settings
window, under User Settings -> Application
, go to Update
section, and change the parameter for Channel
to none
. This prevents VSCode from reaching out to the internet and auto-updating your versions to the latest.
Then go to the VSCode extensions section and install all of your desired extensions. Copy the installed extensions from their install location (with windows its C:\Users\<username>\.vscode\extensions
) to the same location on the target machine.
Works perfectly.
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, new MySchedule()).commit();
MySchedule is the name of my java class.
To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:
Open Source:
Paid:
** - means I didn't try those so I can't really recommend it but other users suggested it..
You can load a DataTable
directly from a data reader using the Load()
method that accepts an IDataReader
.
var dataReader = cmd.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(dataReader);
For Windows 10 and Python 3.6, this worked for me
pip install opencv-contrib-python
@Adrian Cornish's answer is correct. However, there is another caveat to dropping an existing primary key. If that primary key is being used as a foreign key by another table you will get an error when trying to drop it. In some versions of mysql the error message there was malformed (as of 5.5.17, this error message is still
alter table parent drop column id;
ERROR 1025 (HY000): Error on rename of
'./test/#sql-a04_b' to './test/parent' (errno: 150).
If you want to drop a primary key that's being referenced by another table, you will have to drop the foreign key in that other table first. You can recreate that foreign key if you still want it after you recreate the primary key.
Also, when using composite keys, order is important. These
1) ALTER TABLE provider ADD PRIMARY KEY(person,place,thing);
and
2) ALTER TABLE provider ADD PRIMARY KEY(person,thing,place);
are not the the same thing. They both enforce uniqueness on that set of three fields, however from an indexing standpoint there is a difference. The fields are indexed from left to right. For example, consider the following queries:
A) SELECT person, place, thing FROM provider WHERE person = 'foo' AND thing = 'bar';
B) SELECT person, place, thing FROM provider WHERE person = 'foo' AND place = 'baz';
C) SELECT person, place, thing FROM provider WHERE person = 'foo' AND place = 'baz' AND thing = 'bar';
D) SELECT person, place, thing FROM provider WHERE place = 'baz' AND thing = 'bar';
B can use the primary key index in ALTER statement 1
A can use the primary key index in ALTER statement 2
C can use either index
D can't use either index
A uses the first two fields in index 2 as a partial index. A can't use index 1 because it doesn't know the intermediate place portion of the index. It might still be able to use a partial index on just person though.
D can't use either index because it doesn't know person.
See the mysql docs here for more information.
It might be a conflict with the same port specified in docker-compose.yml
and docker-compose.override.yml
or the same port specified explicitly and using an environment variable.
I had a docker-compose.yml
with ports on a container specified using environment variables, and a docker-compose.override.yml
with one of the same ports specified explicitly. Apparently docker tried to open both on the same container. docker container ls -a
listed neither because the container could not start and list the ports.
I had this problem when setting up a new EC2 instance. I had not added HTTPS to my security group, and so port 443 was not open.
With recent builds of mongodb community edition, this is straightforward.
When you install via brew, it tells you what exactly to do. There is no need to create a new launch control file.
$ brew install mongodb
==> Downloading https://homebrew.bintray.com/bottles/mongodb-3.0.6.yosemite.bottle.tar.gz ### 100.0%
==> Pouring mongodb-3.0.6.yosemite.bottle.tar.gz
==> Caveats
To have launchd start mongodb at login:
ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents
Then to load mongodb now:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
Or, if you don't want/need launchctl, you can just run:
mongod --config /usr/local/etc/mongod.conf
==> Summary
/usr/local/Cellar/mongodb/3.0.6: 17 files, 159M
you can use arraylist object from collections class
using System.Collections;
static void Main()
{
ArrayList arr = new ArrayList();
}
when you want to add elements you can use
arr.Add();
A stub, in this context, means a mock implementation.
That is, a simple, fake implementation that conforms to the interface and is to be used for testing.
Like this:
people = []
begin
info = gets.chomp
people += [Person.new(info)] if not info.empty?
end while not info.empty?
Reference: Ruby's Hidden do {} while () Loop
Try this:
dir /s /b /o:n /ad > f.txt
Apart from the IE conditional comments, this is an updated list on how to target IE6 to IE10.
See specific CSS & JS hacks beyond IE.
/***** Attribute Hacks ******/
/* IE6 */
#once { _color: blue }
/* IE6, IE7 */
#doce { *color: blue; /* or #color: blue */ }
/* Everything but IE6 */
#diecisiete { color/**/: blue }
/* IE6, IE7, IE8, but also IE9 in some cases :( */
#diecinueve { color: blue\9; }
/* IE7, IE8 */
#veinte { color/*\**/: blue\9; }
/* IE6, IE7 -- acts as an !important */
#veintesiete { color: blue !ie; } /* string after ! can be anything */
/* IE8, IE9 */
#anotherone {color: blue\0/;} /* must go at the END of all rules */
/* IE9, IE10, IE11 */
@media screen and (min-width:0\0) {
#veintidos { color: red}
}
/***** Selector Hacks ******/
/* IE6 and below */
* html #uno { color: red }
/* IE7 */
*:first-child+html #dos { color: red }
/* IE8 (Everything but IE 6,7) */
html>/**/body #cuatro { color: red }
/* Everything but IE6-8 */
:root *> #quince { color: red }
/* IE7 */
*+html #dieciocho { color: red }
/* IE 10+ */
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
#veintiun { color: red; }
}
Expanding on @Shripad's and @Ivan's answer, I would recommend that you use Node.js's standard module.export functionality.
In your file for constants (e.g. constants.js
), you'd write constants like this:
const CONST1 = 1;
module.exports.CONST1 = CONST1;
const CONST2 = 2;
module.exports.CONST2 = CONST2;
Then in the file in which you want to use those constants, write the following code:
const {CONST1 , CONST2} = require('./constants.js');
If you've never seen the const { ... }
syntax before: that's destructuring assignment.
You can use **kwargs
to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):
>>> def print_keyword_args(**kwargs):
... # kwargs is a dict of the keyword args passed to the function
... for key, value in kwargs.iteritems():
... print "%s = %s" % (key, value)
...
>>> print_keyword_args(first_name="John", last_name="Doe")
first_name = John
last_name = Doe
You can also use the **kwargs
syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:
>>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
>>> print_keyword_args(**kwargs)
first_name = Bobby
last_name = Smith
The Python Tutorial contains a good explanation of how it works, along with some nice examples.
<--Update-->
For people using Python 3, instead of iteritems(), use items()
Try this:
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
public static void main(String[] argv) throws Exception {
JTextField textField = new JTextField();
textField.addKeyListener(new Keychecker());
JFrame jframe = new JFrame();
jframe.add(textField);
jframe.setSize(400, 350);
jframe.setVisible(true);
}
class Keychecker extends KeyAdapter {
@Override
public void keyPressed(KeyEvent event) {
char ch = event.getKeyChar();
System.out.println(event.getKeyChar());
}
}
import java.util.Scanner;
public class Myapplication{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int a;
System.out.println("enter:");
a = in.nextInt();
System.out.println("Number is= " + a);
}
}
Its short and sweet
(?=.*jack)(?=.*james)
[
"xxx james xxx jack xxx",
"jack xxx james ",
"jack xxx jam ",
" jam and jack",
"jack",
"james",
]
.forEach(s => console.log(/(?=.*james)(?=.*jack)/.test(s)) )
_x000D_
Try comparing the value of the column to the DBNull.Value
value to filter and manage null values in whatever way you see fit.
foreach(DataRow row in table.Rows)
{
object value = row["ColumnName"];
if (value == DBNull.Value)
// do something
else
// do something else
}
More information about the DBNull class
If you want to check if a null value exists in the table you can use this method:
public static bool HasNull(this DataTable table)
{
foreach (DataColumn column in table.Columns)
{
if (table.Rows.OfType<DataRow>().Any(r => r.IsNull(column)))
return true;
}
return false;
}
which will let you write this:
table.HasNull();
If someone is using @Sceduled this might work for you.
@Scheduled(cron = "${name-of-the-cron:0 0/30 * * * ?}")
This worked for me.
If you don't mind using 3rd party libraries, my cyclops-react lib has extensions for all JDK Collection types, including Map. We can just transform the map directly using the 'map' operator (by default map acts on the values in the map).
MapX<String,Integer> y = MapX.fromMap(HashMaps.of("hello","1"))
.map(Integer::parseInt);
bimap can be used to transform the keys and values at the same time
MapX<String,Integer> y = MapX.fromMap(HashMaps.of("hello","1"))
.bimap(this::newKey,Integer::parseInt);
For debug purposes only, you can call _viewDelegate
on views to get their view controllers. This is private API, so not safe for App Store, but for debugging it is useful.
Other useful methods:
_viewControllerForAncestor
- get the first controller that manages
a view in the superview chain. (thanks n00neimp0rtant)_rootAncestorViewController
- get the ancestor controller whose
view hierarchy is set in the window currently.I am not sure if this applies to your situation, but I will post what worked for me.
I change my table view based on queries / searches to a database. For example, a database table contains Patient data. My initial table view in my program contains all Patients. I can then search query for Patients by firstName and lastName. I use the results of this query to repopulate my Observable list. Then I reset the items in the tableview by calling tableview.setItems(observableList):
/**
* Searches the table for an existing Patient.
*/
@FXML
public void handleSearch() {
String fname = this.fNameSearch.getText();
String lname = this.lNameSearch.getText();
LocalDate bdate = this.bDateSearch.getValue();
if (this.nameAndDOBSearch(fname, lname, bdate)) {
this.patientData = this.controller.processNursePatientSearch(fname, lname, bdate);
} else if (this.birthDateSearch(fname, lname, bdate)) {
this.patientData = this.controller.processNursePatientSearch(bdate);
} else if (this.nameSearch(fname, lname, bdate)) {
this.patientData = this.controller.processNursePatientSearch(fname, lname);
}
this.patientTable.setItems(this.patientData);
}
The if blocks update the ObservableList with the query results.
Query scopes may help you to let your code more readable.
http://laravel.com/docs/eloquent#query-scopes
Updating this answer with some example:
In your model, create scopes methods like this:
public function scopeActive($query)
{
return $query->where('active', '=', 1);
}
public function scopeThat($query)
{
return $query->where('that', '=', 1);
}
Then, you can call this scopes while building your query:
$users = User::active()->that()->get();
One more way to accomplish it will be as shown below. Here, we use Enumerable#each_with_object
to collect values, and make use of Object#tap
to get rid of temporary variable that is otherwise needed for nil
check on result of process_x
method.
items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}
Complete example for illustration:
items = [1,2,3,4,5]
def process x
rand(10) > 5 ? nil : x
end
items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}
Alternate approach:
By looking at the method you are calling process_x url
, it is not clear what is the purpose of input x
in that method. If I assume that you are going to process the value of x
by passing it some url
and determine which of the x
s really get processed into valid non-nil results - then, may be Enumerabble.group_by
is a better option than Enumerable#map
.
h = items.group_by {|x| (process x).nil? ? "Bad" : "Good"}
#=> {"Bad"=>[1, 2], "Good"=>[3, 4, 5]}
h["Good"]
#=> [3,4,5]
You have to seed it. Seeding it with the time is a good idea:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) );
printf ("Random Number: %d\n", rand() %100);
return 0;
}
You get the same sequence because rand()
is automatically seeded with the a value of 1 if you do not call srand()
.
Due to comments
rand()
will return a number between 0 and RAND_MAX
(defined in the standard library). Using the modulo operator (%
) gives the remainder of the division rand() / 100
. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand() % 1000
.
If you're trying to create a single jar that contains your application and its required libraries, there are two ways (that I know of) to do that. The first is One-Jar, which uses a special classloader to allow the nesting of jars. The second is UberJar, (or Shade), which explodes the included libraries and puts all the classes in the top-level jar.
I should also mention that UberJar and Shade are plugins for Maven1 and Maven2 respectively. As mentioned below, you can also use the assembly plugin (which in reality is much more powerful, but much harder to properly configure).
Old question but anyway !
Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)
So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!
Bitmasks are used when you want to encode multiple layers of information in a single number.
So (assuming unix file permissions) if you want to store 3 levels of access restriction (read, write, execute) you could check for each level by checking the corresponding bit.
rwx
---
110
110 in base 2 translates to 6 in base 10.
So you can easily check if someone is allowed to e.g. read the file by and'ing the permission field with the wanted permission.
Pseudocode:
PERM_READ = 4
PERM_WRITE = 2
PERM_EXEC = 1
user_permissions = 6
if (user_permissions & PERM_READ == TRUE) then
// this will be reached, as 6 & 4 is true
fi
You need a working understanding of binary representation of numbers and logical operators to understand bit fields.
Put a div
inside td
and give following style width:50px;overflow: hidden;
to the div
Jsfiddle link
<td>
<div style="width:50px;overflow: hidden;">
<span>A long string more than 50px wide</span>
</div>
</td>
The foo.bar
reference should not contain the braces:
<p ng-hide="foo.bar">I could be shown, or I could be hidden</p>
<p ng-show="foo.bar">I could be shown, or I could be hidden</p>
Angular expressions need to be within the curly-brace bindings, where as Angular directives do not.
See also Understanding Angular Templates.
You don't need jQuery to do this. Embrace the power of JavaScript.
window.location.reload()
I had a similar issue. I added write permissions to the .bak file itself, and my folder that I was writing the backup to for the NETWORK SERVICE user. To add permissions just right-click what file/directory you want to alter, select the security tab, and add the appropriate users/permissions there.
I have been suffering of this issue for very long time. I was unable to open websites like GitHub. I almost tried all the answer on web and not anyone worked. Tried to reinstall chrome also. I found the solution for this from our network guy and it worked. There is a fix in registry which will resolve this error for permanent basis.
The solution above is for Windows 8. It is almost identical in later versions but i’m not sure for earlier versions like XP and vista. So that needs to be checked.
You can use my plugin for this purpose.
JQuery:
(function() {_x000D_
$.pseudoElements = {_x000D_
length: 0_x000D_
};_x000D_
_x000D_
var setPseudoElement = function(parameters) {_x000D_
if (typeof parameters.argument === 'object' || (parameters.argument !== undefined && parameters.property !== undefined)) {_x000D_
for (var element of parameters.elements.get()) {_x000D_
if (!element.pseudoElements) element.pseudoElements = {_x000D_
styleSheet: null,_x000D_
before: {_x000D_
index: null,_x000D_
properties: null_x000D_
},_x000D_
after: {_x000D_
index: null,_x000D_
properties: null_x000D_
},_x000D_
id: null_x000D_
};_x000D_
_x000D_
var selector = (function() {_x000D_
if (element.pseudoElements.id !== null) {_x000D_
if (Number(element.getAttribute('data-pe--id')) !== element.pseudoElements.id) element.setAttribute('data-pe--id', element.pseudoElements.id);_x000D_
return '[data-pe--id="' + element.pseudoElements.id + '"]::' + parameters.pseudoElement;_x000D_
} else {_x000D_
var id = $.pseudoElements.length;_x000D_
$.pseudoElements.length++_x000D_
_x000D_
element.pseudoElements.id = id;_x000D_
element.setAttribute('data-pe--id', id);_x000D_
_x000D_
return '[data-pe--id="' + id + '"]::' + parameters.pseudoElement;_x000D_
};_x000D_
})();_x000D_
_x000D_
if (!element.pseudoElements.styleSheet) {_x000D_
if (document.styleSheets[0]) {_x000D_
element.pseudoElements.styleSheet = document.styleSheets[0];_x000D_
} else {_x000D_
var styleSheet = document.createElement('style');_x000D_
_x000D_
document.head.appendChild(styleSheet);_x000D_
element.pseudoElements.styleSheet = styleSheet.sheet;_x000D_
};_x000D_
};_x000D_
_x000D_
if (element.pseudoElements[parameters.pseudoElement].properties && element.pseudoElements[parameters.pseudoElement].index) {_x000D_
element.pseudoElements.styleSheet.deleteRule(element.pseudoElements[parameters.pseudoElement].index);_x000D_
};_x000D_
_x000D_
if (typeof parameters.argument === 'object') {_x000D_
parameters.argument = $.extend({}, parameters.argument);_x000D_
_x000D_
if (!element.pseudoElements[parameters.pseudoElement].properties && !element.pseudoElements[parameters.pseudoElement].index) {_x000D_
var newIndex = element.pseudoElements.styleSheet.rules.length || element.pseudoElements.styleSheet.cssRules.length || element.pseudoElements.styleSheet.length;_x000D_
_x000D_
element.pseudoElements[parameters.pseudoElement].index = newIndex;_x000D_
element.pseudoElements[parameters.pseudoElement].properties = parameters.argument;_x000D_
};_x000D_
_x000D_
var properties = '';_x000D_
_x000D_
for (var property in parameters.argument) {_x000D_
if (typeof parameters.argument[property] === 'function')_x000D_
element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property]();_x000D_
else_x000D_
element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property];_x000D_
};_x000D_
_x000D_
for (var property in element.pseudoElements[parameters.pseudoElement].properties) {_x000D_
properties += property + ': ' + element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';_x000D_
};_x000D_
_x000D_
element.pseudoElements.styleSheet.addRule(selector, properties, element.pseudoElements[parameters.pseudoElement].index);_x000D_
} else if (parameters.argument !== undefined && parameters.property !== undefined) {_x000D_
if (!element.pseudoElements[parameters.pseudoElement].properties && !element.pseudoElements[parameters.pseudoElement].index) {_x000D_
var newIndex = element.pseudoElements.styleSheet.rules.length || element.pseudoElements.styleSheet.cssRules.length || element.pseudoElements.styleSheet.length;_x000D_
_x000D_
element.pseudoElements[parameters.pseudoElement].index = newIndex;_x000D_
element.pseudoElements[parameters.pseudoElement].properties = {};_x000D_
};_x000D_
_x000D_
if (typeof parameters.property === 'function')_x000D_
element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property();_x000D_
else_x000D_
element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property;_x000D_
_x000D_
var properties = '';_x000D_
_x000D_
for (var property in element.pseudoElements[parameters.pseudoElement].properties) {_x000D_
properties += property + ': ' + element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';_x000D_
};_x000D_
_x000D_
element.pseudoElements.styleSheet.addRule(selector, properties, element.pseudoElements[parameters.pseudoElement].index);_x000D_
};_x000D_
};_x000D_
_x000D_
return $(parameters.elements);_x000D_
} else if (parameters.argument !== undefined && parameters.property === undefined) {_x000D_
var element = $(parameters.elements).get(0);_x000D_
_x000D_
var windowStyle = window.getComputedStyle(_x000D_
element, '::' + parameters.pseudoElement_x000D_
).getPropertyValue(parameters.argument);_x000D_
_x000D_
if (element.pseudoElements) {_x000D_
return $(parameters.elements).get(0).pseudoElements[parameters.pseudoElement].properties[parameters.argument] || windowStyle;_x000D_
} else {_x000D_
return windowStyle || null;_x000D_
};_x000D_
} else {_x000D_
console.error('Invalid values!');_x000D_
return false;_x000D_
};_x000D_
};_x000D_
_x000D_
$.fn.cssBefore = function(argument, property) {_x000D_
return setPseudoElement({_x000D_
elements: this,_x000D_
pseudoElement: 'before',_x000D_
argument: argument,_x000D_
property: property_x000D_
});_x000D_
};_x000D_
$.fn.cssAfter = function(argument, property) {_x000D_
return setPseudoElement({_x000D_
elements: this,_x000D_
pseudoElement: 'after',_x000D_
argument: argument,_x000D_
property: property_x000D_
});_x000D_
};_x000D_
})();_x000D_
_x000D_
$(function() {_x000D_
$('.element').cssBefore('content', '"New before!"');_x000D_
});
_x000D_
.element {_x000D_
width: 480px;_x000D_
margin: 0 auto;_x000D_
border: 2px solid red;_x000D_
}_x000D_
_x000D_
.element::before {_x000D_
content: 'Old before!';_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="element"></div>
_x000D_
The values should be specified, as in the normal function of jQuery.css
In addition, you can also get the value of the pseudo-element parameter, as in the normal function of jQuery.css:
console.log( $(element).cssBefore(parameter) );
JS:
(function() {_x000D_
document.pseudoElements = {_x000D_
length: 0_x000D_
};_x000D_
_x000D_
var setPseudoElement = function(parameters) {_x000D_
if (typeof parameters.argument === 'object' || (parameters.argument !== undefined && parameters.property !== undefined)) {_x000D_
if (!parameters.element.pseudoElements) parameters.element.pseudoElements = {_x000D_
styleSheet: null,_x000D_
before: {_x000D_
index: null,_x000D_
properties: null_x000D_
},_x000D_
after: {_x000D_
index: null,_x000D_
properties: null_x000D_
},_x000D_
id: null_x000D_
};_x000D_
_x000D_
var selector = (function() {_x000D_
if (parameters.element.pseudoElements.id !== null) {_x000D_
if (Number(parameters.element.getAttribute('data-pe--id')) !== parameters.element.pseudoElements.id) parameters.element.setAttribute('data-pe--id', parameters.element.pseudoElements.id);_x000D_
return '[data-pe--id="' + parameters.element.pseudoElements.id + '"]::' + parameters.pseudoElement;_x000D_
} else {_x000D_
var id = document.pseudoElements.length;_x000D_
document.pseudoElements.length++_x000D_
_x000D_
parameters.element.pseudoElements.id = id;_x000D_
parameters.element.setAttribute('data-pe--id', id);_x000D_
_x000D_
return '[data-pe--id="' + id + '"]::' + parameters.pseudoElement;_x000D_
};_x000D_
})();_x000D_
_x000D_
if (!parameters.element.pseudoElements.styleSheet) {_x000D_
if (document.styleSheets[0]) {_x000D_
parameters.element.pseudoElements.styleSheet = document.styleSheets[0];_x000D_
} else {_x000D_
var styleSheet = document.createElement('style');_x000D_
_x000D_
document.head.appendChild(styleSheet);_x000D_
parameters.element.pseudoElements.styleSheet = styleSheet.sheet;_x000D_
};_x000D_
};_x000D_
_x000D_
if (parameters.element.pseudoElements[parameters.pseudoElement].properties && parameters.element.pseudoElements[parameters.pseudoElement].index) {_x000D_
parameters.element.pseudoElements.styleSheet.deleteRule(parameters.element.pseudoElements[parameters.pseudoElement].index);_x000D_
};_x000D_
_x000D_
if (typeof parameters.argument === 'object') {_x000D_
parameters.argument = (function() {_x000D_
var cloneObject = typeof parameters.argument.pop === 'function' ? [] : {};_x000D_
_x000D_
for (var property in parameters.argument) {_x000D_
cloneObject[property] = parameters.argument[property];_x000D_
};_x000D_
_x000D_
return cloneObject;_x000D_
})();_x000D_
_x000D_
if (!parameters.element.pseudoElements[parameters.pseudoElement].properties && !parameters.element.pseudoElements[parameters.pseudoElement].index) {_x000D_
var newIndex = parameters.element.pseudoElements.styleSheet.rules.length || parameters.element.pseudoElements.styleSheet.cssRules.length || parameters.element.pseudoElements.styleSheet.length;_x000D_
_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].index = newIndex;_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties = parameters.argument;_x000D_
};_x000D_
_x000D_
var properties = '';_x000D_
_x000D_
for (var property in parameters.argument) {_x000D_
if (typeof parameters.argument[property] === 'function')_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property]();_x000D_
else_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property];_x000D_
};_x000D_
_x000D_
for (var property in parameters.element.pseudoElements[parameters.pseudoElement].properties) {_x000D_
properties += property + ': ' + parameters.element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';_x000D_
};_x000D_
_x000D_
parameters.element.pseudoElements.styleSheet.addRule(selector, properties, parameters.element.pseudoElements[parameters.pseudoElement].index);_x000D_
} else if (parameters.argument !== undefined && parameters.property !== undefined) {_x000D_
if (!parameters.element.pseudoElements[parameters.pseudoElement].properties && !parameters.element.pseudoElements[parameters.pseudoElement].index) {_x000D_
var newIndex = parameters.element.pseudoElements.styleSheet.rules.length || parameters.element.pseudoElements.styleSheet.cssRules.length || parameters.element.pseudoElements.styleSheet.length;_x000D_
_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].index = newIndex;_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties = {};_x000D_
};_x000D_
_x000D_
if (typeof parameters.property === 'function')_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property();_x000D_
else_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property;_x000D_
_x000D_
var properties = '';_x000D_
_x000D_
for (var property in parameters.element.pseudoElements[parameters.pseudoElement].properties) {_x000D_
properties += property + ': ' + parameters.element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';_x000D_
};_x000D_
_x000D_
parameters.element.pseudoElements.styleSheet.addRule(selector, properties, parameters.element.pseudoElements[parameters.pseudoElement].index);_x000D_
};_x000D_
} else if (parameters.argument !== undefined && parameters.property === undefined) {_x000D_
var windowStyle = window.getComputedStyle(_x000D_
parameters.element, '::' + parameters.pseudoElement_x000D_
).getPropertyValue(parameters.argument);_x000D_
_x000D_
if (parameters.element.pseudoElements) {_x000D_
return parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] || windowStyle;_x000D_
} else {_x000D_
return windowStyle || null;_x000D_
};_x000D_
} else {_x000D_
console.error('Invalid values!');_x000D_
return false;_x000D_
};_x000D_
};_x000D_
_x000D_
Object.defineProperty(Element.prototype, 'styleBefore', {_x000D_
enumerable: false,_x000D_
value: function(argument, property) {_x000D_
return setPseudoElement({_x000D_
element: this,_x000D_
pseudoElement: 'before',_x000D_
argument: argument,_x000D_
property: property_x000D_
});_x000D_
}_x000D_
});_x000D_
Object.defineProperty(Element.prototype, 'styleAfter', {_x000D_
enumerable: false,_x000D_
value: function(argument, property) {_x000D_
return setPseudoElement({_x000D_
element: this,_x000D_
pseudoElement: 'after',_x000D_
argument: argument,_x000D_
property: property_x000D_
});_x000D_
}_x000D_
});_x000D_
})();_x000D_
_x000D_
document.querySelector('.element').styleBefore('content', '"New before!"');
_x000D_
.element {_x000D_
width: 480px;_x000D_
margin: 0 auto;_x000D_
border: 2px solid red;_x000D_
}_x000D_
_x000D_
.element::before {_x000D_
content: 'Old before!';_x000D_
}
_x000D_
<div class="element"></div>
_x000D_
GitHub: https://github.com/yuri-spivak/managing-the-properties-of-pseudo-elements/
Another reason to use object
over iframe is that object
sub resources (when an <object>
performs HTTP
requests) are considered as passive/display
in terms of Mixed content
, which means it's more secure when you must have Mixed content
.
Mixed content means that when you have https
but your resource is from http
.
Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content
I answered a similar question here: AngularJS Authentication + RESTful API
I've written an AngularJS module for UserApp that supports protected/public routes, rerouting on login/logout, heartbeats for status checks, stores the session token in a cookie, events, etc.
You could either:
https://github.com/userapp-io/userapp-angular
If you use UserApp, you won't have to write any server-side code for the user stuff (more than validating a token). Take the course on Codecademy to try it out.
Here's some examples of how it works:
How to specify which routes that should be public, and which route that is the login form:
$routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
$routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
$routeProvider.when('/home', {templateUrl: 'partials/home.html'});
The .otherwise()
route should be set to where you want your users to be redirected after login. Example:
$routeProvider.otherwise({redirectTo: '/home'});
Login form with error handling:
<form ua-login ua-error="error-msg">
<input name="login" placeholder="Username"><br>
<input name="password" placeholder="Password" type="password"><br>
<button type="submit">Log in</button>
<p id="error-msg"></p>
</form>
Signup form with error handling:
<form ua-signup ua-error="error-msg">
<input name="first_name" placeholder="Your name"><br>
<input name="login" ua-is-email placeholder="Email"><br>
<input name="password" placeholder="Password" type="password"><br>
<button type="submit">Create account</button>
<p id="error-msg"></p>
</form>
Log out link:
<a href="#" ua-logout>Log Out</a>
(Ends the session and redirects to the login route)
Access user properties:
User properties are accessed using the user
service, e.g: user.current.email
Or in the template: <span>{{ user.email }}</span>
Hide elements that should only be visible when logged in:
<div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>
Show an element based on permissions:
<div ua-has-permission="admin">You are an admin</div>
And to authenticate to your back-end services, just use user.token()
to get the session token and send it with the AJAX request. At the back-end, use the UserApp API (if you use UserApp) to check if the token is valid or not.
If you need any help, just let me know!
You simply combine the ideas of a link to another page, as with href=foo.html
, and a link to an element on the same page, as with href=#bar
, so that the fragment like #bar
is written immediately after the URL that refers to another page:
<a href="foo.html#bar">Some nice link text</a>
The target is specified the same was as when linking inside one page, e.g.
<div id="bar">
<h2>Some heading</h2>
Some content
</div>
or (if you really want to link specifically to a heading only)
<h2 id="bar">Some heading</h2>
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
You can do it in the following way:
myfxn <- function(var1,var2,var3){
var1*var2*var3
}
lapply(1:3,myfxn,var2=2,var3=100)
and you will get the answer:
[[1]] [1] 200
[[2]] [1] 400
[[3]] [1] 600
var timeout_check_change_class;
function check_change_class( selector )
{
$(selector).each(function(index, el) {
var data_old_class = $(el).attr('data-old-class');
if (typeof data_old_class !== typeof undefined && data_old_class !== false)
{
if( data_old_class != $(el).attr('class') )
{
$(el).trigger('change_class');
}
}
$(el).attr('data-old-class', $(el).attr('class') );
});
clearTimeout( timeout_check_change_class );
timeout_check_change_class = setTimeout(check_change_class, 10, selector);
}
check_change_class( '.breakpoint' );
$('.breakpoint').on('change_class', function(event) {
console.log('haschange');
});
For Ubuntu i use this:
(exec PROG_SH &> /dev/null &)
regards
Since you haven't posted code, we're kind of working in the dark. What are the details of the exception?
Are you calling Thread.wait() from within the thread, or outside it?
I ask this because according to the javadoc for IllegalMonitorStateException, it is:
Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.
To clarify this answer, this call to wait on a thread also throws IllegalMonitorStateException, despite being called from within a synchronized block:
private static final class Lock { }
private final Object lock = new Lock();
@Test
public void testRun() {
ThreadWorker worker = new ThreadWorker();
System.out.println ("Starting worker");
worker.start();
System.out.println ("Worker started - telling it to wait");
try {
synchronized (lock) {
worker.wait();
}
} catch (InterruptedException e1) {
String msg = "InterruptedException: [" + e1.getLocalizedMessage() + "]";
System.out.println (msg);
e1.printStackTrace();
System.out.flush();
}
System.out.println ("Worker done waiting, we're now waiting for it by joining");
try {
worker.join();
} catch (InterruptedException ex) { }
}
Plotly supports interactive 2D and 3D graphing. Graphs are rendered with D3.js and can be created with a Python API, matplotlib, ggplot for Python, Seaborn, prettyplotlib, and pandas. You can zoom, pan, toggle traces on and off, and see data on the hover. Plots can be embedded in HTML, apps, dashboards, and IPython Notebooks. Below is a temperature graph showing interactivity. See the gallery of IPython Notebooks tutorials for more examples.
The docs provides examples of supported plot types and code snippets.
Specifically to your question, you can also make interactive plots from NetworkX.
For 3D plotting with Python, you can make 3D scatter, line, and surface plots that are similarly interactive. Plots are rendered with WebGL. For example, see a 3D graph of UK Swap rates.
Disclosure: I'm on the Plotly team.
You need the actual instance of the WindowSettings
that's open, not a new one.
Currently, you are creating a new instance of WindowSettings
and calling Close
on that. That doesn't do anything because that new instance never has been shown.
Instead, when showing DialogSettingsCancel
set the current instance of WindowSettings
as the parent.
Something like this:
In WindowSettings
:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel();
dialogSettingsCancel.OwningWindowSettings = this;
dialogSettingsCancel.Show();
}
In DialogSettingsCancel
:
public WindowSettings OwningWindowSettings { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.Close();
if(OwningWindowSettings != null)
OwningWindowSettings.Close();
}
This approach takes into account, that a DialogSettingsCancel
could potentially be opened without a WindowsSettings
as parent.
If the two are always connected, you should instead use a constructor parameter:
In WindowSettings
:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel(this);
dialogSettingsCancel.Show();
}
In DialogSettingsCancel
:
WindowSettings _owningWindowSettings;
public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
if(owningWindowSettings == null)
throw new ArgumentNullException("owningWindowSettings");
_owningWindowSettings = owningWindowSettings;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
_owningWindowSettings.Close();
}
I know this is old, but I ran into an issue where I was running a function after checking if there was a session. It would throw an error everytime I tried loading the page after logging out, still worked just logged an error page. Make sure you use exit(); if you are running into the same problem.
function sessionexists(){
if(!empty($_SESSION)){
return true;
}else{
return false;
}
}
if (!sessionexists()){
redirect("https://www.yoursite.com/");
exit();
}else{call_user_func('check_the_page');
}
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
Try parent_window.maxsize(x,x);
to set the maximum size. It shouldn't get larger even if you set the background, etc.
Edit: use parent_window.minsize(x,x)
also to set it to a constant size!
if you are using mysqli and have two db_connection file. like first one is
define('HOST','localhost');
define('USER','user');
define('PASS','passs');
define('**DB1**','database_name1');
$connMitra = new mysqli(HOST, USER, PASS, **DB1**);
second one is
define('HOST','localhost');
define('USER','user');
define('PASS','passs');
define(**'DB2**','database_name1');
$connMitra = new mysqli(HOST, USER, PASS, **DB2**);
SO just change the name of parameter pass in mysqli like DB1 and DB2. if you pass same parameter in mysqli suppose DB1 in both file then second database will no connect any more. So remember when you use two or more connection pass different parameter name in mysqli function
You can add one Section(with zero rows) above, then set the above sectionFooterView as current section's headerView, footerView doesn't float. Hope it gives a help.
I get consistent behaviour for both instances:
>>> ls[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[10:-1]
[10, 11, 12, 13, 14, 15, 16, 17, 18]
Note, though, that tenth element of the list is at index 9, since the list is 0-indexed. That might be where your hang-up is.
In other words, [0:10]
doesn't go from index 0-10, it effectively goes from 0 to the tenth element (which gets you indexes 0-9, since the 10 is not inclusive at the end of the slice).
In order to get the sha/hash of the commit that a tag refers to (not the sha of the tag):
git rev-list -1 <tag>
Once I faced with the issue when I did not know which the element currently stored in my variable (svg or html) but I needed to get it width and height. I created this function and want to share it:
function computeDimensions(selection) {
var dimensions = null;
var node = selection.node();
if (node instanceof SVGGraphicsElement) { // check if node is svg element
dimensions = node.getBBox();
} else { // else is html element
dimensions = node.getBoundingClientRect();
}
console.log(dimensions);
return dimensions;
}
Little demo in the hidden snippet below. We handle click on the blue div and on the red svg circle with the same function.
var svg = d3.select('svg')
.attr('width', 50)
.attr('height', 50);
function computeDimensions(selection) {
var dimensions = null;
var node = selection.node();
if (node instanceof SVGElement) {
dimensions = node.getBBox();
} else {
dimensions = node.getBoundingClientRect();
}
console.clear();
console.log(dimensions);
return dimensions;
}
var circle = svg
.append("circle")
.attr("r", 20)
.attr("cx", 30)
.attr("cy", 30)
.attr("fill", "red")
.on("click", function() { computeDimensions(circle); });
var div = d3.selectAll("div").on("click", function() { computeDimensions(div) });
_x000D_
* {
margin: 0;
padding: 0;
border: 0;
}
body {
background: #ffd;
}
.div {
display: inline-block;
background-color: blue;
margin-right: 30px;
width: 30px;
height: 30px;
}
_x000D_
<h3>
Click on blue div block or svg circle
</h3>
<svg></svg>
<div class="div"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
Start session from terminal:
openssl s_client -connect smtp.gmail.com:25 -starttls smtp
The last line of the response should be "250 SMTPUTF8"
Initiate login
auth login
This should return "334 VXNlcm5hbWU6".
Type username
Type your username in base64 encoding (eg. echo -n 'your-username' | base64
)
This should return "334 UGFzc3dvcmQ6"
Type password
Type your password in base64 encoding (eg. echo -n 'your-password' | base64
)
Success
You should see "235 2.7.0 Accepted" and you're are successfully logged in
You can't set the input value in most browsers, but what you can do is create a new element, copy the attributes from the old element, and swap the two.
Given a form like:
<form>
<input id="fileInput" name="fileInput" type="file" />
</form>
The straight DOM way:
function clearFileInput(id)
{
var oldInput = document.getElementById(id);
var newInput = document.createElement("input");
newInput.type = "file";
newInput.id = oldInput.id;
newInput.name = oldInput.name;
newInput.className = oldInput.className;
newInput.style.cssText = oldInput.style.cssText;
// TODO: copy any other relevant attributes
oldInput.parentNode.replaceChild(newInput, oldInput);
}
clearFileInput("fileInput");
Simple DOM way. This may not work in older browsers that don't like file inputs:
oldInput.parentNode.replaceChild(oldInput.cloneNode(), oldInput);
The jQuery way:
$("#fileInput").replaceWith($("#fileInput").val('').clone(true));
// .val('') required for FF compatibility as per @nmit026
Resetting the whole form via jQuery: https://stackoverflow.com/a/13351234/1091947
var element = $("#parentDiv .myClassNameOfInterest")
Instead a format such as yours, use ISO 8601 standard formats for exchanging date-time values as text.
The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
Your IST
could mean Iceland Standard Time, India Standard Time, Ireland Standard Time, or others. The java.time classes are left to merely guessing, as there is no logical solution to this ambiguity.
The modern approach uses the java.time classes.
Define a formatting pattern to match your input strings.
String input = "Sat Jun 01 12:53:10 IST 2013";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
zdt.toString(): 2013-06-01T12:53:10Z[Atlantic/Reykjavik]
If your input was not intended for Iceland, you should pre-parse the string to adjust to a proper time zone name. For example, if you are certain the input was intended for India, change IST
to Asia/Kolkata
.
String input = "Sat Jun 01 12:53:10 IST 2013".replace( "IST" , "Asia/Kolkata" );
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
zdt.toString(): 2013-06-01T12:53:10+05:30[Asia/Kolkata]
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
The map() function is a best choice for this case
tl;dr - Do this:
const newArr = [
{name: 'eve'},
{name: 'john'},
{name: 'jane'}
].map(v => ({...v, isActive: true}))
The map() function won't modify the initial array, but creates a new one. This is also a good practice to keep initial array unmodified.
Alternatives:
const initialArr = [
{name: 'eve'},
{name: 'john'},
{name: 'jane'}
]
const newArr1 = initialArr.map(v => ({...v, isActive: true}))
const newArr2 = initialArr.map(v => Object.assign(v, {isActive: true}))
// Results of newArr1 and newArr2 are the same
Add a key value pair conditionally
const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr1 = arr.map(v => ({...v, isActive: v.value > 1}))
What if I don't want to add new field at all if the condition is false?
const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr = arr.map(v => {
return v.value > 1 ? {...v, isActive: true} : v
})
Adding WITH modification of the initial array
const initialArr = [{a: 1}, {b: 2}]
initialArr.forEach(v => {v.isActive = true;});
This is probably not a best idea, but in a real life sometimes it's the only way.
Questions
...
), or Object.assign
and what's the difference?Personally I prefer to use spread operator, because I think it uses much wider in modern web community (especially react's developers love it). But you can check the difference yourself: link(a bit opinionated and old, but still)
function
keyword instead of =>
?Sure you can. The fat arrow (=>
) functions play a bit different with this
, but it's not so important for this particular case. But fat arrows function shorter and sometimes plays better as a callbacks. Therefore the usage of fat arrow functions is more modern approach.
.map(v => ({...v, isActive: true})
?Map function iterates by array's elements and apply callback function for each of them. That callback function should return something that will become an element of a new array.
We tell to the .map()
function following: take current value(v
which is an object), take all key-value pairs away from v
andput it inside a new object({...v}
), but also add property isActive
and set it to true ({...v, isActive: true}
) and then return the result. Btw, if original object contains isActive
filed it will be overwritten. Object.assign
works in a similar way.
Yes.
[{value: 1}, {value: 1}, {value: 2}].map(v => ({...v, isActive: true, howAreYou: 'good'}))
.map()
methodYou shouldn't do any side effects[link 1, link 2], but apparently you can.
Also be noticed that map()
iterates over each element of the array and apply function for each of them. So if you do some heavy stuff inside, you might be slow. This (a bit hacky) solution might be more productive in some cases (but I don't think you should apply it more then once in a lifetime).
Sure you can.
const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr = arr.map(addIsActive)
function addIsActive(v) {
return {...v, isActive: true}
}
Nothing is wrong with for
, you can still use it, it's just an old-school approach which is more verbose, less safe and mutate the initial array. But you can try:
const arr = [{a: 1}, {b: 2}]
for (let i = 0; i < arr.length; i++) {
arr[i].isActive = true
}
It would be smart to learn well following methods map(), filter(), reduce(), forEach(), and find(). These methods can solve 80% of what you usually want to do with arrays.
You could simply have: var result = (str == "true")
.
Your code is blanking out your file:
import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)
if you want to read the file in, you will need to use csv.reader and open the file for reading.
import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
print line
If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).
The best way in my opinion is to use the browser's inbuilt HTML escape functionality to handle many of the cases. To do this simply create a element in the DOM tree and set the innerText
of the element to your string. Then retrieve the innerHTML
of the element. The browser will return an HTML encoded string.
function HtmlEncode(s)
{
var el = document.createElement("div");
el.innerText = el.textContent = s;
s = el.innerHTML;
return s;
}
Test run:
alert(HtmlEncode('&;\'><"'));
Output:
&;'><"
This method of escaping HTML is also used by the Prototype JS library though differently from the simplistic sample I have given.
Note: You will still need to escape quotes (double and single) yourself. You can use any of the methods outlined by others here.
Type:
type = list.AsEnumerable().SingleOrDefault().GetType();
In addition to romkyns's great answer.. here is some relevant documentation/examples.
DOM Elements have a native .click()
method.
The
HTMLElement.click()
method simulates a mouse click on an element.When click is used, it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an
<a>
element to initiate navigation as if a real mouse-click had been received. (mdn reference)
Relevant W3 documentation.
A few examples..
You can access a specific DOM element from a jQuery object: (example)
$('a')[0].click();
You can use the .get()
method to retrieve a DOM element from a jQuery object: (example)
$('a').get(0).click();
As expected, you can select the DOM element and call the .click()
method. (example)
document.querySelector('a').click();
It's worth pointing out that jQuery is not required to trigger a native .click()
event.
(You already mentioned all but the last one).
Those are the only differences to regular classes.
You should try something like this
<Button
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/qrcode"/>
the android:background="@drawable/qrcode"
will do it
You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.
Have you set the DataContext to your ConnectionViewModel object?
I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.
Here is my XAML content:
<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<StackPanel>
<Button Click="Button_Click">asdf</Button>
<ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=PhonebookEntry}" />
</StackPanel>
</Grid>
</Window>
And here is my code-behind:
namespace WpfApplication6
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
ConnectionViewModel vm = new ConnectionViewModel();
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
((ConnectionViewModel)DataContext).PhonebookEntry = "test";
}
}
public class PhoneBookEntry
{
public string Name { get; set; }
public PhoneBookEntry(string name)
{
Name = name;
}
public override string ToString()
{
return Name;
}
}
public class ConnectionViewModel : INotifyPropertyChanged
{
public ConnectionViewModel()
{
IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
list.Add(new PhoneBookEntry("test"));
list.Add(new PhoneBookEntry("test2"));
_phonebookEntries = new CollectionView(list);
}
private readonly CollectionView _phonebookEntries;
private string _phonebookEntry;
public CollectionView PhonebookEntries
{
get { return _phonebookEntries; }
}
public string PhonebookEntry
{
get { return _phonebookEntry; }
set
{
if (_phonebookEntry == value) return;
_phonebookEntry = value;
OnPropertyChanged("PhonebookEntry");
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.
Maybe there is an issue with the CollectionView? I noticed a warning in the output console:
System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.
Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.
Note that
You can configure Apache so that all files With .inc
extension are forbidden to be retrieved by visiting URL directly.
see link:https://serverfault.com/questions/22577/how-to-deny-the-web-access-to-some-files
I managed to use a one-line Ruby script for that purpose (although it had to go in a separate file). First, run these commands once on each client machine you'll be pushing docs from:
gem install github-markup
gem install commonmarker
Next, install this script in your client image, and call it render-readme-for-javadoc.rb
:
require 'github/markup'
puts GitHub::Markup.render_s(GitHub::Markups::MARKUP_MARKDOWN, File.read('README.md'))
Finally, invoke it like this:
ruby ./render-readme-for-javadoc.rb >> project/src/main/javadoc/overview.html
ETA: This won't help you with StackOverflow-flavor Markdown, which seems to be failing on this answer.
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
Another solution is to check for the command's exit code.
git rev-parse 2> /dev/null; [ $? == 0 ] && echo 1
This will print 1 if you're in a git repository folder.
update YourTable
set YourColumn = replace(YourColumn, '@domain2', '@domain1')
where charindex('@domain2', YourColumn) <> 0
if (grid.selectedKeyNames().length > 0) {
$('#btnRemoveFromList').show();
} else {
$('#btnRemoveFromList').hide();
}
}
()
- calls the method
no parentheses - returns the property
I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)
public static bool IsStringType(object data)
{
return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
}
MathGL have many plot types, C/Fortran interface and basic data analysis
Keep in mind the second parameter to @Html.HiddenFor will only be used to set the value when it can't find route or model data matching the field. Darin is correct, use view model.
check this out https://forum.jquery.com/topic/get-index-of-same-class-element-on-click then http://jsfiddle.net/me2loveit2/d6rFM/2/
var index = $('selector').index(this);
console.log(index)
On a Mac, I solved it using this code:
gem install pg -v '0.18.4' -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config
umount -l
At the time of writing, the top-voted answer recommends using umount -l
.
umount -l
is dangerous or at best unsafe. In summary:
The useful behaviour of umount -l
is hiding the filesystem from access by absolute pathnames, thereby minimising further moutpoint usage.
This same behaviour can be achieved by mounting an empty directory with permissions 000
over the directory to be unmounted.
Then any new accesses to filenames in the below the mountpoint will hit the newly overlaid directory with zero permissions - new blockers to the unmount are thereby prevented.
remount,ro
The major unmount achievement to be unlocked is the read-only remount. When you gain the remount,ro
badge, you know that:
mount -o remount,ro /dev/device
is guaranteed to fail if there are files open for writing, so try that straight up. You may be feeling lucky, punk!
If you are unlucky, focus only on processes with files open for writing:
lsof +f -- /dev/<devicename> | awk 'NR==1 || $4~/[0-9]+[uw -]/'
You should then be able to remount the device read-only and ensure a consistent state.
If you can't remount read-only at this point, investigate some of the other possible causes listed here.
Read-only re-mount achievement unlocked ?
Congratulations, your data on the mountpoint is now consistent and protected from future writing.
fuser
is inferior to lsof
Why not use use fuser
earlier? Well, you could have, but fuser
operates upon a directory, not a device, so if you wanted to remove the mountpoint from the file name space and still use fuser
, you'd need to:
mount -o bind /media/hdd /mnt
to another locationHere's how:
null_dir=$(sudo mktemp --directory --tmpdir empty.XXXXX")
sudo chmod 000 "$null_dir"
# A request to remount,ro will fail on a `-o bind,ro` duplicate if there are
# still files open for writing on the original as each mounted instance is
# checked. https://unix.stackexchange.com/a/386570/143394
# So, avoid remount, and bind mount instead:
sudo mount -o bind,ro "$original" "$original_duplicate"
# Don't propagate/mirror the empty directory just about hide the original
sudo mount --make-private "$original_duplicate"
# Hide the original mountpoint
sudo mount -o bind,ro "$null_dir" "$original"
You'd then have:
fuser
.This is more convoluted[1], but allows you to use:
fuser -vmMkiw <mountpoint>
which will interactively ask to kill the processes with files open for writing. Of course, you could do this without hiding the mount point at all, but the above mimicks umount -l
, without any of the dangers.
The -w
switch restricts to writing processes, and the -i
is interactive, so after a read-only remount, if you're it a hurry you could then use:
fuser -vmMk <mountpoint>
to kill all remaining processes with files open under the mountpoint.
Hopefully at this point, you can unmount the device. (You'll need to run umount
on the mountpoint twice if you've bind mounted a mode 000
directory on top.)
Or use:
fuser -vmMki <mountpoint>
to interactively kill the remaining read-only processes blocking the unmount.
target is busy
!Open files aren't the only unmount blocker. See here and here for other causes and their remedies.
Even if you've got some lurking gremlin which is preventing you from fully unmounting the device, you have at least got your filesystem in a consistent state.
You can then use lsof +f -- /dev/device
to list all processes with open files on the device containing the filesystem, and then kill them.
[1] It is less convoluted to use mount --move
, but that requires mount --make-private /parent-mount-point
which has implications. Basically, if the mountpoint is mounted under the /
filesystem, you'd want to avoid this.
viewDidLoad()
—Called when the view controller’s content view (the top of its view hierarchy) is created and loaded from a storyboard. … Use this method to perform any additional setup required by your view controller.
viewWillAppear()
—Called just before the view controller’s content view is added to the app’s view hierarchy. Use this method to trigger any operations that need to occur before the content view is presented onscreen
viewDidAppear()
—Called just after the view controller’s content view has been added to the app’s view hierarchy. Use this method to trigger any operations that need to occur as soon as the view is presented onscreen, such as fetching data or showing an animation.
viewWillDisappear()
—Called just before the view controller’s content view is removed from the app’s view hierarchy. Use this method to perform cleanup tasks like committing changes or resigning the first responder status.
viewDidDisappear()
—Called just after the view controller’s content view has been removed from the app’s view hierarchy. Use this method to perform additional teardown activities.
function atLeastTwoTrue($a, $b, $c) { int count = 0; count = (a ? count + 1 : count); count = (b ? count + 1 : count); count = (c ? count + 1 : count); return (count >= 2); }
As of February 2020, for Android Studio 3.5.3, the simplest answer I found is this video.
Note 1: At 01.24 "Find" tab appears below. Click "Do Refactor" and continue as in the video.
Note 2: If you have any Java/Kotlin files "Marked as Plain Text" you need to modify the package name at the top manually, i.e. package com.example.thisplaceneedstobemanuallyupdated
Note 3: Be careful about letter cases while renaming, just as in the video.
Note 4: If you want to update the project name on title bar of project window, modify rootProject.name = 'YourProjectName'
inside "settings.gradle" file under "Gradle Scripts" directory.
Why not just do this:
function oddOrEven(num){
if(num % 2 == 0)
return "even";
return "odd";
}
oddOrEven(num);
SERIOUS DISCLAIMER
This solution has a serious security flaw. Please use at your own risk.
Have a look at the comments on this post, and look at all the answers to this question.
OK, I had to go to the customer premises and found a solution. I:
Then I opened the JAWS application without any warning. This is a little bit cumbersome, but much cheaper than buying a signed certificate!
For UWP:
<ResourceDictionary Source="ms-appx:///##Namespace.External.Assembly##/##FOLDER##/##FILE##.xaml" />
I create equations with random numbers in VBA and for x squared put in x^2.
I read each square (or textbox) text into a string.
I then read each character in the string in turn and note the location of the ^ ("hats")'s in each.
Say the hats were at positions 4, 8 and 12.
I then "chop out" the first hat - the position of the character to be superscripted is now 4, the position of the other hats is now 7 and 11. I chop out the second hat, the character to superscript is now at 7 and the hat has moved to 10. I chop out the last hat .. the superscript character is now position 10.
I now select each character in turn and change the font to superscript.
Thus I can fill a whole spreadsheet with algebra using ^ and then call a routine to tidy it up.
For big powers like x to the 23 I build x^2^3 and the above routine does it.
There are two general approaches here:
nan
and take any
.nan
s (like sum
) and check its result.While the first approach is certainly the cleanest, the heavy optimization of some of the cumulative operations (particularly the ones that are executed in BLAS, like dot
) can make those quite fast. Note that dot
, like some other BLAS operations, are multithreaded under certain conditions. This explains the difference in speed between different machines.
import numpy
import perfplot
def min(a):
return numpy.isnan(numpy.min(a))
def sum(a):
return numpy.isnan(numpy.sum(a))
def dot(a):
return numpy.isnan(numpy.dot(a, a))
def any(a):
return numpy.any(numpy.isnan(a))
def einsum(a):
return numpy.isnan(numpy.einsum("i->", a))
perfplot.show(
setup=lambda n: numpy.random.rand(n),
kernels=[min, sum, dot, any, einsum],
n_range=[2 ** k for k in range(20)],
logx=True,
logy=True,
xlabel="len(a)",
)
In addition to display:block
OR display:inline-block
Try giving sufficient padding
to your .btn-pToolName
and make sure you have the correct values for background-position
In Javascript it is better to use screen.width
and screen.height
. These two values are available in all modern browsers. They give the real dimensions of the screen, even if the browser has been scaled down when the app fires up. window.innerWidth
changes when the browser is scaled down, which can't happen on mobile devices but can happen on PCs and laptops.
The values of screen.width
and screen.height
change when the mobile device flips between portrait and landscape modes, so it is possible to determine the mode by comparing the values. If screen.width
is greater than 1280px you're dealing with a PC or laptop.
You can construct an event listener in Javascript to detect when the two values are flipped. The portrait screen.width values to concentrate on are 320px (mainly iPhones), 360px (most other phones), 768px (small tablets) and 800px (regular tablets).
I had same problem. I need show url for a search engine
I use two routes like this
Route::get('buscar/{nom}', 'FrontController@buscarPrd');
Route::post('buscar', function(){
$bsqd = Input::get('nom');
return Redirect::action('FrontController@buscarPrd', array('nom'=>$bsqd));
});
First one used to show url like we want
Second one used by form and redirect to first one
The following method doesn't require root and should work anywhere (according to docs, even on Android Q+, if you keep targetSdkVersion = 28
).
Make a blank app.
Create a ContentProvider
:
class ApiProvider : ContentProvider() {
private val wifiManager: WifiManager? by lazy(LazyThreadSafetyMode.NONE) {
requireContext().getSystemService(WIFI_SERVICE) as WifiManager?
}
private fun requireContext() = checkNotNull(context)
private val matcher = UriMatcher(UriMatcher.NO_MATCH).apply {
addURI("wifi", "enable", 0)
addURI("wifi", "disable", 1)
}
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
when (matcher.match(uri)) {
0 -> {
enforceAdb()
withClearCallingIdentity {
wifiManager?.isWifiEnabled = true
}
}
1 -> {
enforceAdb()
withClearCallingIdentity {
wifiManager?.isWifiEnabled = false
}
}
}
return null
}
private fun enforceAdb() {
val callingUid = Binder.getCallingUid()
if (callingUid != 2000 && callingUid != 0) {
throw SecurityException("Only shell or root allowed.")
}
}
private inline fun <T> withClearCallingIdentity(block: () -> T): T {
val token = Binder.clearCallingIdentity()
try {
return block()
} finally {
Binder.restoreCallingIdentity(token)
}
}
override fun onCreate(): Boolean = true
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
override fun getType(uri: Uri): String? = null
}
Declare it in AndroidManifest.xml
along with necessary permission:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application>
<provider
android:name=".ApiProvider"
android:authorities="wifi"
android:exported="true" />
</application>
Build the app and install it.
Call from ADB:
adb shell content query --uri content://wifi/enable
adb shell content query --uri content://wifi/disable
Make a batch script/shell function/shell alias with a short name that calls these commands.
Depending on your device you may need additional permissions.
Run this in your interactive terminal
import os
os.path
It will give you the folder where python is installed
As the error message says, non-default argument til
should not follow default argument hgt
.
Changing order of parameters (function call also be adjusted accordingly) or making hgt
non-default parameter will solve your problem.
def a(len1, hgt=len1, til, col=0):
->
def a(len1, hgt, til, col=0):
UPDATE
Another issue that is hidden by the SyntaxError.
os.system
accepts only one string parameter.
def a(len1, hgt, til, col=0):
system('mode con cols=%s lines=%s' % (len1, hgt))
system('title %s' % til)
system('color %s' % col)
Fix bugs with the first's answer:
def longestSubstringFinder(string1, string2):
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
for j in range(len2):
lcs_temp=0
match=''
while ((i+lcs_temp < len1) and (j+lcs_temp<len2) and string1[i+lcs_temp] == string2[j+lcs_temp]):
match += string2[j+lcs_temp]
lcs_temp+=1
if (len(match) > len(answer)):
answer = match
return answer
print longestSubstringFinder("dd apple pie available", "apple pies")
print longestSubstringFinder("cov_basic_as_cov_x_gt_y_rna_genes_w1000000", "cov_rna15pcs_as_cov_x_gt_y_rna_genes_w1000000")
print longestSubstringFinder("bapples", "cappleses")
print longestSubstringFinder("apples", "apples")
As the error code says, "no alternative certificate subject name matches target host name" - so there is an issue with the SSL certificate.
The certificate should include SAN, and only SAN will be used. Some browsers ignore the deprecated Common Name.
RFC 2818 clearly states "If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead."
client = new OkHttpClient();
Request request = new Request.Builder().header("authorization", token).url(url).build();
MyWebSocketListener wsListener = new MyWebSocketListener(LudoRoomActivity.this);
client.newWebSocket(request, wsListener);
client.dispatcher().executorService().shutdown();
modulus division is simply this : divide two numbers and return the remainder only
27 / 16 = 1 with 11 left over, therefore 27 % 16 = 11
ditto 43 / 16 = 2 with 11 left over so 43 % 16 = 11 too
I had a similar error
/{path to project root}/Pods/Target Support Files/Pods-{project name}/Pods-{project name}-frameworks.sh: Permission denied
Command PhaseScriptExecution failed with a nonzero exit code
In my case I had received a zip of a repo that included the Pods folder. It turns out that at some point between it being originally created and sent to me, the *.sh files in Pods/Target Support Files/Pods-{PROJECT}/
had all lost their execute permissions. Giving those files +x
was the solution
The problem was caused by not setting the CUDA_VISIBLE_DEVICES
variable within the shell correctly.
To specify CUDA device 1
for example, you would set the CUDA_VISIBLE_DEVICES
using
export CUDA_VISIBLE_DEVICES=1
or
CUDA_VISIBLE_DEVICES=1 ./cuda_executable
The former sets the variable for the life of the current shell, the latter only for the lifespan of that particular executable invocation.
If you want to specify more than one device, use
export CUDA_VISIBLE_DEVICES=0,1
or
CUDA_VISIBLE_DEVICES=0,1 ./cuda_executable
One of the nice things about the syntax is that you can be sure that a CREATE OR REPLACE
will never cause you to lose data (the most you will lose is code, which hopefully you'll have stored in source control somewhere).
The equivalent syntax for tables is ALTER, which means you have to explicitly enumerate the exact changes that are required.
EDIT: By the way, if you need to do a DROP + CREATE in a script, and you don't care for the spurious "object does not exist" errors (when the DROP doesn't find the table), you can do this:
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE owner.mytable';
EXCEPTION
WHEN OTHERS THEN
IF sqlcode != -0942 THEN RAISE; END IF;
END;
/
select *
from table
order by empno(primary key) desc
fetch first 5 rows only
I know this is an old post, but a good time to use PrimaryKeyColumn
would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.
In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn
.
Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.
If you want to fit other type of models, like a dose-response curve using logistic models you would also need to create more data points with the function predict if you want to have a smoother regression line:
fit: your fit of a logistic regression curve
#Create a range of doses:
mm <- data.frame(DOSE = seq(0, max(data$DOSE), length.out = 100))
#Create a new data frame for ggplot using predict and your range of new
#doses:
fit.ggplot=data.frame(y=predict(fit, newdata=mm),x=mm$DOSE)
ggplot(data=data,aes(x=log10(DOSE),y=log(viability)))+geom_point()+
geom_line(data=fit.ggplot,aes(x=log10(x),y=log(y)))
I just found a solution that I think works really well and gets around all of the pitfalls of custom symbols. The main problem with the li:before solution is that if list-items are longer than one line will not indent properly after the first line of text. By using text-indent with a negative padding we can circumvent that problem and have all the lines aligned properly:
ul{
padding-left: 0; // remove default padding
}
li{
list-style-type: none; // remove default styles
padding-left: 1.2em;
text-indent:-1.2em; // remove padding on first line
}
li::before{
margin-right: 0.5em;
width: 0.7em; // margin-right and width must add up to the negative indent-value set above
height: 0.7em;
display: inline-block;
vertical-align: middle;
border-radius: 50%;
background-color: orange;
content: ' '
}
There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions:
import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]
If you want to find overlapping matches, lookahead will do that:
[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]
If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:
search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
#[1]
re.finditer
returns a generator, so you could change the []
in the above to ()
to get a generator instead of a list which will be more efficient if you're only iterating through the results once.
DELETE /api/items/1,2
DELETE /api/items/1
public class CustomBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Metadata.ModelType == typeof(int[]) || context.Metadata.ModelType == typeof(List<int>))
{
return new BinderTypeModelBinder(typeof(CommaDelimitedArrayParameterBinder));
}
return null;
}
}
public class CommaDelimitedArrayParameterBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var value = bindingContext.ActionContext.RouteData.Values[bindingContext.FieldName] as string;
// Check if the argument value is null or empty
if (string.IsNullOrEmpty(value))
{
return Task.CompletedTask;
}
var ints = value?.Split(',').Select(int.Parse).ToArray();
bindingContext.Result = ModelBindingResult.Success(ints);
if(bindingContext.ModelType == typeof(List<int>))
{
bindingContext.Result = ModelBindingResult.Success(ints.ToList());
}
return Task.CompletedTask;
}
}
services.AddMvc(options =>
{
// add custom binder to beginning of collection
options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
});
/// <summary>
/// Deletes a list of items.
/// </summary>
/// <param name="itemIds">The list of unique identifiers for the items.</param>
/// <returns>The deleted item.</returns>
/// <response code="201">The item was successfully deleted.</response>
/// <response code="400">The item is invalid.</response>
[HttpDelete("{itemIds}", Name = ItemControllerRoute.DeleteItems)]
[ProducesResponseType(typeof(void), StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task Delete(List<int> itemIds)
=> await _itemAppService.RemoveRangeAsync(itemIds);
EDIT: Microsoft recommends using a TypeConverter for these kids of operations over this approach. So follow the below posters advice and document your custom type with a SchemaFilter.
System.Threading.Thread.Sleep(50);
Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish")
Just remove the ;
to make it work for VB.net as well.
Trunk : After the completion of every sprint in agile we come out with a partially shippable product. These releases are kept in trunk.
Branches : All parallel developments codes for each ongoing sprint are kept in branches.
Tags : Every time we release a partially shippable product kind of beta version, we make a tag for it. This gives us the code that was available at that point of time, allowing us to go back at that state if required at some point during development.
If I want to edit a specified comment, how do I get its content and its question?
If you had kept track of the number of comments and the index of the comment you wanted to alter, you could use the dot operator (SO example).
You could do f.ex.
db.questions.update(
{
"title": "aaa"
},
{
"comments.0.contents": "new text"
}
)
(as another way to edit the comments inside the question)
Not Bootstrap specific really... You can use inline styles or define a custom class to specify the desired "background-color".
On the other hand, Bootstrap does have a few built in background colors that have semantic meaning like "bg-success" (green) and "bg-danger" (red).
For Java 1.6 and lower, I believe the safest and cleanest API for this is Guava's Files.move.
Example:
File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());
The first line makes sure that the location of the new file is the same directory, i.e. the parent directory of the old file.
EDIT: I wrote this before I started using Java 7, which introduced a very similar approach. So if you're using Java 7+, you should see and upvote kr37's answer.
If you are using Linux, you can use this bash script: (it perhaps needs some additional code cleaning but it works ... and it's much faster then mysqldump|mysql)
#!/bin/bash
DBUSER=user
DBPASSWORD=pwd
DBSNAME=sourceDb
DBNAME=destinationDb
DBSERVER=db.example.com
fCreateTable=""
fInsertData=""
echo "Copying database ... (may take a while ...)"
DBCONN="-h ${DBSERVER} -u ${DBUSER} --password=${DBPASSWORD}"
echo "DROP DATABASE IF EXISTS ${DBNAME}" | mysql ${DBCONN}
echo "CREATE DATABASE ${DBNAME}" | mysql ${DBCONN}
for TABLE in `echo "SHOW TABLES" | mysql $DBCONN $DBSNAME | tail -n +2`; do
createTable=`echo "SHOW CREATE TABLE ${TABLE}"|mysql -B -r $DBCONN $DBSNAME|tail -n +2|cut -f 2-`
fCreateTable="${fCreateTable} ; ${createTable}"
insertData="INSERT INTO ${DBNAME}.${TABLE} SELECT * FROM ${DBSNAME}.${TABLE}"
fInsertData="${fInsertData} ; ${insertData}"
done;
echo "$fCreateTable ; $fInsertData" | mysql $DBCONN $DBNAME
Your initial approach was right, but you forgot one little thing about foreach. It doesn't work on the original array/object, but creates a copy of each element as it iterates, so you did unset the copy. Use reference like this:
foreach($doc->seg as &$seg)
{
if($seg['id'] == 'A12')
{
unset($seg);
}
}
There are some issues with the scripts above:
shift "removes" the parameter $1, otherwise, "push" will read it and "misunderstand it".
My tip :
git config --global alias.acpp '!git add -A && branchatu="$(git symbolic-ref HEAD 2>/dev/null)" && branchatu=${branchatu##refs/heads/} && git commit -m "$1" && shift && git pull -u origin $branchatu && git push -u origin $branchatu'
It's possible to effectively define a variable that can be used in both the SELECT, WHERE and other clauses.
A subquery doesn't necessarily allow for appropriate binding to the referenced table columns, however OUTER APPLY does.
SELECT A.identifier
, A.name
, vars.MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A
, table_b B ON A.identifier = B.identifier
OUTER APPLY (
SELECT
-- variables
MONTH_NO = TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL))
) vars
WHERE vars.MONTH_NO > UPD_DATE
Kudos to Syed Mehroz Alam.
To clarify a point in Thomas' excellent answer, it should be mentioned that append()
is thread safe.
This is because there is no concern that data being read will be in the same place once we go to write to it. The append()
operation does not read data, it only writes data to the list.
Not really related match to the original question, but may be someone will find it useful. PermGen is indeed an area in memory where Java used to keep its classes. So, many of us have came across OOM in PermGen, if there were, for example a lot of classes.
Since Java 8, PermGen area has been replaced by MetaSpace area, which is more efficient and is unlimited by default (or more precisely - limited by amount of native memory, depending on 32 or 64 bit jvm and OS virtual memory availability) . However it is possible to tune it in some ways, by for example specifying a max limit for the area. You can find more useful information in this blog post.
Try to use this :
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < chBoxListTables.Items.Count; i++)
if (chBoxListTables.GetItemCheckState(i) == CheckState.Checked)
{
txtBx.text += chBoxListTables.Items[i].ToString() + " \n";
}
}
In addition to the above answers, there is always the scorched earth method.
rm -R <folder>
in Windows shell the command is:
rd /s <folder>
Then you can just checkout the project again:
git clone -v <repository URL>
This will definitely remove any local changes and pull the latest from the remote repository. Be careful with rm -R as it will delete your good data if you put the wrong path. For instance, definitely do not do:
rm -R /
edit: To fix spelling and add emphasis.
This ORA error is occurred because of violation of unique constraint.
ORA-00001: unique constraint (constraint_name) violated
This is caused because of trying to execute an INSERT
or UPDATE
statement that has created a duplicate value in a field restricted by a unique index.
You can resolve this either by
I know I'm kinda late to the party but I was looking for a solution for this..and I bumped into this post. Here is my take on this, maybe it will help some of you.
The html part:
<button type="button" class="btn btn-lg btn-danger" data-content="test" data-placement="right" data-toggle="popover" title="Popover title" >Hover to toggle popover</button><br>
// with custom html stored in a separate element, using "data-target"
<button type="button" class="btn btn-lg btn-danger" data-target="#custom-html" data-placement="right" data-toggle="popover" >Hover to toggle popover</button>
<div id="custom-html" style="display: none;">
<strong>Helloooo!!</strong>
</div>
The js part:
$(function () {
let popover = '[data-toggle="popover"]';
let popoverId = function(element) {
return $(element).popover().data('bs.popover').tip.id;
}
$(popover).popover({
trigger: 'manual',
html: true,
animation: false
})
.on('show.bs.popover', function() {
// hide all other popovers
$(popover).popover("hide");
})
.on("mouseenter", function() {
// add custom html from element
let target = $(this).data('target');
$(this).popover().data('bs.popover').config.content = $(target).html();
// show the popover
$(this).popover("show");
$('#' + popoverId(this)).on("mouseleave", () => {
$(this).popover("hide");
});
}).on("mouseleave", function() {
setTimeout(() => {
if (!$("#" + popoverId(this) + ":hover").length) {
$(this).popover("hide");
}
}, 100);
});
})
What version of Excel?
In general, you cannot change the column letters. They are part of the Excel system.
You can use a row in the sheet to enter headers for a table that you are using. The table headers can be descriptive column names.
In Excel 2007 and later, you can convert a range of data into an Excel Table (Insert Ribbon > Table). An Excel Table can use structured table references instead of cell addresses, so the labels in the first row of the table now serve as a name reference for the data in the column.
If you have an Excel Table in your sheet (Excel 2007 and later) and scroll down, the column letters will be replaced with the column headers for the table column.
If this does not answer your question, please consider editing your question to include the detail you want to learn about.
Case statement syntax in SQL SERVER:
CASE column
WHEN value1 THEN 1
WHEN value3 THEN 2
WHEN value3 THEN 3
WHEN value1 THEN 4
ELSE ''
END
And we can use like below also:
CASE
WHEN column=value1 THEN 1
WHEN column=value3 THEN 2
WHEN column=value3 THEN 3
WHEN column=value1 THEN 4
ELSE ''
END
I know this is an old question. But i couldnt get the jquery $(this).change() event to fire correctly onSelect. So i went with the following approach to fire the change event via vanilla js.
$('.date').datepicker({
showOn: 'focus',
dateFormat: 'mm-dd-yy',
changeMonth: true,
changeYear: true,
onSelect: function() {
var event;
if(typeof window.Event == "function"){
event = new Event('change');
this.dispatchEvent(event);
} else {
event = document.createEvent('HTMLEvents');
event.initEvent('change', false, false);
this.dispatchEvent(event);
}
}
});
For Swift 3
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
//Landscape
}
else if UIDevice.current.orientation.isFlat {
//isFlat
}
else {
//Portrait
}
}
You can use Maven Version Manager through which you can use multiple version of Maven per directory base.
Installation
Using Homebrew brew install mvnvm
Without Homebrew mkdir -p ~/bin && curl -s https://bitbucket.org/mjensen/mvnvm/raw/master/mvn > ~/bin/mvn && chmod 0755 ~/bin/mvn
and add ~/bin
to path.
Usage
Default Version
To set default maven version set the environment variable DEFAULT_MVN_VERSION
to the maven version to be used by default.
Maven version for the folder
Create a file named mvnvm.properties
in the folder and configure the maven version as follows
mvn_version=<maven version>
You said that
the browser gets the certificate's issuer information from that certificate, then uses that to contact the issuerer, and somehow compares certificates for validity.
The client doesn't have to check with the issuer because two things :
Notice that 2. can't be done without 1.
This is better explained in this big diagram I made some time ago
(skip to "what's a signature ?" at the bottom)
You can use Environment.Exit(0)
and Application.Exit
.
Environment.Exit()
: terminates this process and gives the underlying operating system the specified exit code.
You can also use a second image to give the effect of a button being pressed. Just add the "pressed" button image in the HTML
before the input image:
<img src="http://integritycontractingofva.com/images/go2.jpg" id="pressed"/>
<input id="unpressed" type="submit" value=" " style="background:url(http://integritycontractingofva.com/images/go1.jpg) no-repeat;border:none;"/>
And use CSS
to change the opacity of the "unpressed" image on hover:
#pressed, #unpressed{position:absolute; left:0px;}
#unpressed{opacity: 1; cursor: pointer;}
#unpressed:hover{opacity: 0;}
I use it for the blue "GO" button on this page
Maybe because I have an older version of pandas but on Jupyter notebook this work for me
import pandas as pd
from IPython.core.display import HTML
df=pd.read_pickle('Data1')
display(HTML(df.to_html()))
I don't think you should be returning any http error codes, rather custom exceptions that are useful to the client end of the application so the interface knows what had actually occurred. I wouldn't try and mask real issues with 404 error codes or something to that nature.
I have tested this on EF core 2.1
Here you cannot use either Conventions or Data Annotations. You must use the Fluent API.
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Created)
.HasDefaultValueSql("getdate()");
}
}
Although very late, hope it still helps someone:
Many of comments here and in other posts are concerned about setting initial size.
I used jqueryUi.Resizable. Initial widths shall be defined within each "< td >" tag at first line (< TR >). This is unlike what colResizable recommends; colResizable prohibits defining widths at first line, there I had to define widths in "< col>" tag which wasn't consikstent with jqueryresizable.
the following snippet is very neat and easier to read than usual samples:
$("#Content td").resizable({
handles: "e, s",
resize: function (event, ui) {
var sizerID = "#" + $(event.target).attr("id");
$(sizerID).width(ui.size.width);
}
});
Content is id of my table. Handles (e, s) define in which directions the plugin can change the size. You must have a link to css of jquery-ui, otherwise it won't work.
One contending technology you've omitted is Server-Sent Events / Event Source. What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet? has a good discussion of all of these. Keep in mind that some of these are easier than others to integrate with on the server side.
This may be a good explanation example
CREATE TABLE employees (
id INTEGER NOT NULL PRIMARY KEY,
managerId INTEGER REFERENCES employees(id),
name VARCHAR(30) NOT NULL
);
INSERT INTO employees(id, managerId, name) VALUES(1, NULL, 'John');
INSERT INTO employees(id, managerId, name) VALUES(2, 1, 'Mike');
-- Explanation: -- In this example. -- John is Mike's manager. Mike does not manage anyone. -- Mike is the only employee who does not manage anyone.
curl --head https://www.example.net
I was pointed to this by curl itself; when I issued the command with -X HEAD
, it printed:
Warning: Setting custom HTTP method to HEAD with -X/--request may not work the
Warning: way you want. Consider using -I/--head instead.
You would need to manage the referential constraint across databases using a Trigger.
Basically you create an insert, update trigger to verify the existence of the Key in the Primary key table. If the key does not exist then revert the insert or update and then handle the exception.
Example:
Create Trigger dbo.MyTableTrigger ON dbo.MyTable, After Insert, Update
As
Begin
If NOT Exists(select PK from OtherDB.dbo.TableName where PK in (Select FK from inserted) BEGIN
-- Handle the Referential Error Here
END
END
Edited: Just to clarify. This is not the best approach with enforcing referential integrity. Ideally you would want both tables in the same db but if that is not possible. Then the above is a potential work around for you.
I'd use modulus and a loop.
int[] GetIntArray(int num)
{
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
Because in Python 3, print statement
has been replaced with a print() function
, with keyword arguments to replace most of the special syntax of the old print statement. So you have to write it as
print("Hello World")
But if you write this in a program and someone using Python 2.x tries to run it, they will get an error. To avoid this, it is a good practice to import print function:
from __future__ import print_function
Now your code works on both 2.x & 3.x.
Check out below examples also to get familiar with print() function.
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not the same as print(x, y)!
Source: What’s New In Python 3.0?
You can use plain javascript, this will call your_func once, after 5 seconds:
setTimeout(function() { your_func(); }, 5000);
If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)
There is also a plugin I've used once. It has oneTime
and everyTime
methods.
Make a normal breakpoint on the doIt(tablist[i]);
line
Right-click -> Properties
Check 'Conditional'
Enter tablist[i].equalsIgnoreCase("LEADDELEGATES")
It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)
git pull origin master
for me that simple call solved those error messages:
To deal with the following special cases in Ray casting algorithm:
Check Determining Whether A Point Is Inside A Complex Polygon. The article provides an easy way to resolve them so there will be no special treatment required for the above cases.
You can do
dt[, !c("V1","V2","V3","V5")]
to get
V4 V6 V7 V8 V9 V10
1: 0.88612076 0.94727825 0.50502208 0.6702523 0.24186706 0.96263313
2: 0.11121752 0.13969145 0.19092645 0.9589867 0.27968190 0.07796870
3: 0.50179822 0.10641301 0.08540322 0.3297847 0.03643195 0.18082180
4: 0.09787517 0.07312777 0.88077548 0.3218041 0.75826099 0.55847774
5: 0.73475574 0.96644484 0.58261312 0.9921499 0.78962675 0.04976212
6: 0.88861117 0.85690337 0.27723130 0.3662264 0.50881663 0.67402625
7: 0.33933983 0.83392047 0.30701697 0.6138122 0.85107176 0.58609504
8: 0.89907094 0.61389815 0.19957386 0.3968331 0.78876682 0.90546328
9: 0.54136123 0.08274569 0.25190790 0.1920462 0.15142604 0.12134807
10: 0.36511064 0.88117171 0.05730210 0.9441072 0.40125023 0.62828674