One of the benefits is that Razor views can be rendered inside unit tests, this is something that was not easily possible with the previous ASP.Net renderer.
From ScottGu's announcement this is listed as one of the design goals:
Unit Testable: The new view engine implementation will support the ability to unit test views (without requiring a controller or web-server, and can be hosted in any unit test project – no special app-domain required).
if you found an issue when you try to import xgboost (my case it is Windows 10 and anaconda spyder) do the following:
conda install -c anaconda py-xgboost
That's all...Good luck.
from selenium import webdriver
driver = webdriver.Firefox()
driver.implicitly_wait(12)
driver.set_page_load_timeout(10)
def _post_selenium(self, url: str, data: dict):
input_template = '{k} <input type="text" name="{k}" id="{k}" value="{v}"><BR>\n'
inputs = ""
if data:
for k, v in data.items():
inputs += input_template.format(k=k, v=v)
html = f'<html><body>\n<form action="{url}" method="post" id="formid">\n{inputs}<input type="submit" id="inputbox">\n</form></body></html>'
html_file = os.path.join(os.getcwd(), 'temp.html')
with open(html_file, "w") as text_file:
text_file.write(html)
driver.get(f"file://{html_file}")
driver.find_element_by_id('inputbox').click()
_post_selenium("post.to.my.site.url", {"field1": "val1"})
driver.close()
As everyone else says, you can't from a simple programmatic way.
Consider these examples:
President "George Herbert Walker Bush" (First Middle Middle Last)
Presidential assassin "John Wilkes Booth" (First Middle Last)
Guitarist "Eddie Van Halen" (First Last Last)
And his mom probably calls him Edward Lodewijk Van Halen (First Middle Last Last)
Famed castaway "Mary Ann Summers" (First First Last)
New Mexico GOP chairman "Fernando C de Baca" (First Last Last Last)
I don't know if I understand your problem correctly, so let me restate it in my own words...
Problem: Given classes B
and D
, determine if D
is a subclass of B
(or vice-versa?)
Solution: Use some template magic! Okay, seriously you need to take a look at LOKI, an excellent template meta-programming library produced by the fabled C++ author Andrei Alexandrescu.
More specifically, download LOKI and include header TypeManip.h
from it in your source code then use the SuperSubclass
class template as follows:
if(SuperSubClass<B,D>::value)
{
...
}
According to documentation, SuperSubClass<B,D>::value
will be true if B
is a public base of D
, or if B
and D
are aliases of the same type.
i.e. either D
is a subclass of B
or D
is the same as B
.
I hope this helps.
edit:
Please note the evaluation of SuperSubClass<B,D>::value
happens at compile time unlike some methods which use dynamic_cast
, hence there is no penalty for using this system at runtime.
Simple:
public int getArrayIndex(int[] arr,int value) {
for(int i=0;i<arr.length;i++)
if(arr[i]==value) return i;
return -1;
}
If you have trouble with caching ajax you can turn it off:
$.ajaxSetup({cache: false});
Take a look at PHP COM documents (The comments are helpful) http://us3.php.net/com
You could just nest the Text components with the required style. The style will be applied along with already defined style in the first Text component.
Example:
<Text style={styles.paragraph}>
Trouble singing in. <Text style={{fontWeight: "bold"}}> Resolve</Text>
</Text>
If you need Base64 over JSON, check out Jackson: it has explicit support for binary data read/write as Base64 at both the low level (JsonParser, JsonGenerator) and data-binding level. So you can just have POJOs with byte[] properties, and encoding/decoding is automatically handled.
And pretty efficiently too, should that matter.
Here is a basic example of how an image file with certain restrictions (listed below) can be uploaded to the server.
Checks for image size.
<?php
$newfilename = "newfilename";
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png");
if(file_exists($file_name)) {
echo "Sorry, file already exists.";
}
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$newfilename.".".$file_ext);
echo "Success";
echo "<script>window.close();</script>";
}
else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>
Credit to this page.
Although many great answers were written to this question, none of them uses the Rspec tags
approach.
I use tags to run one or more specs in different files -- only those related to my current development task.
For example, I add the tag "dev" with the value "current":
it "creates an user", dev: :current do
user = create(:user)
expect(user.persisted?).to be_truthy
end
then I run
bundle exec rspec . --tag dev:current
Different tags/values can be set in individual specs or groups.
The error you're getting appears to be the result of the fact that there is no underscore between "chartered" and "flight" in the table name. I assume you want something like this where the name of the table is chartered_flight
.
CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, flight_time INTERVAL DAY TO SECOND NOT NULL
, takeoff_at CHAR (3) NOT NULL
, destination CHAR (3) NOT NULL)
Generally, there is no benefit to declaring a column as CHAR(3)
rather than VARCHAR2(3)
. Declaring a column as CHAR(3)
doesn't force there to be three characters of (useful) data. It just tells Oracle to space-pad data with fewer than three characters to three characters. That is unlikely to be helpful if someone inadvertently enters an incorrect code. Potentially, you could declare the column as VARCHAR2(3)
and then add a CHECK
constraint that LENGTH(takeoff_at) = 3
.
CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, flight_time INTERVAL DAY TO SECOND NOT NULL
, takeoff_at CHAR (3) NOT NULL CHECK( length( takeoff_at ) = 3 )
, destination CHAR (3) NOT NULL CHECK( length( destination ) = 3 )
)
Since both takeoff_at
and destination
are airport codes, you really ought to have a separate table of valid airport codes and define foreign key constraints between the chartered_flight
table and this new airport_code
table. That ensures that only valid airport codes are added and makes it much easier in the future if an airport code changes.
And from a naming convention standpoint, since both takeoff_at
and destination
are airport codes, I would suggest that the names be complementary and indicate that fact. Something like departure_airport_code
and arrival_airport_code
, for example, would be much more meaningful.
For smaller font, I use
ax1.set_xticklabels(xticklabels, fontsize=7)
and it works!
Update
Dav Glass from Yahoo has given a talk at YuiConf2010 in November which is now available in Video from.
He shows to great extend how one can use YUI3 to render out widgets on the server side an make them work with GET requests when JS is disabled, or just make them work normally when it's active.
He also shows examples of how to use server side DOM to apply style sheets before rendering and other cool stuff.
The demos can be found on his GitHub Account.
The part that's missing IMO to make this really awesome, is some kind of underlying storage of the widget state. So that one can visit the page without JavaScript and everything works as expected, then they turn JS on and now the widget have the same state as before but work without page reloading, then throw in some saving to the server + WebSockets to sync between multiple open browser.... and the next generation of unobtrusive and gracefully degrading ARIA's is born.
Original Answer
Well go ahead and built it yourself then.
Seriously, 90% of all WebApps out there work fine with a REST approach, of course you could do magical things like superior user tracking, tracking of downloads in real time, checking which parts of videos are being watched etc.
One problem is scalability, as soon as you have more then 1 Node process, many (but not all) of the benefits of having the data stored between requests go away, so you have to make sure that clients always hit the same process. And even then, bigger things will yet again need a database layer.
Node.js isn't the solution to everything, I'm sure people will build really great stuff in the future, but that needs some time, right now many are just porting stuff over to Node to get things going.
What (IMHO) makes Node.js so great, is the fact that it streamlines the Development process, you have to write less code, it works perfectly with JSON, you loose all that context switching.
I mainly did gaming experiments so far, but I can for sure say that there will be many cool multi player (or even MMO) things in the future, that use both HTML5 and Node.js.
Node.js is still gaining traction, it's not even near to the RoR Hype some years ago (just take a look at the Node.js tag here on SO, hardly 4-5 questions a day).
Rome (or RoR) wasn't built over night, and neither will Node.js be.
Node.js has all the potential it needs, but people are still trying things out, so I'd suggest you to join them :)
First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.
Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:
Consider following query.
Select A.*
, (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
, (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)
FROM A
You can use lateral in this condition.
Select A.*
, x.Column1
, x.Column2
FROM A LEFT JOIN LATERAL (
Select B.Column1,B.Column2,B.Fk1 from B Limit 1
) x ON X.Fk1 = A.PK
In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.
There are more usages for lateral or cross apply but this is most common one I found.
Find below 3 methods:
Checking page readyState (not reliable):
def page_has_loaded(self):
self.log.info("Checking if {} page is loaded.".format(self.driver.current_url))
page_state = self.driver.execute_script('return document.readyState;')
return page_state == 'complete'
The
wait_for
helper function is good, but unfortunatelyclick_through_to_new_page
is open to the race condition where we manage to execute the script in the old page, before the browser has started processing the click, andpage_has_loaded
just returns true straight away.
id
Comparing new page ids with the old one:
def page_has_loaded_id(self):
self.log.info("Checking if {} page is loaded.".format(self.driver.current_url))
try:
new_page = browser.find_element_by_tag_name('html')
return new_page.id != old_page.id
except NoSuchElementException:
return False
It's possible that comparing ids is not as effective as waiting for stale reference exceptions.
staleness_of
Using staleness_of
method:
@contextlib.contextmanager
def wait_for_page_load(self, timeout=10):
self.log.debug("Waiting for page to load at {}.".format(self.driver.current_url))
old_page = self.find_element_by_tag_name('html')
yield
WebDriverWait(self, timeout).until(staleness_of(old_page))
For more details, check Harry's blog.
I'm on Ubuntu 15.04. This seemed to work:
$ sudo pip3 install numpy
On RHEL this worked:
$ sudo python3 -m pip install numpy
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
Your bat file could be like:
CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319
msbuild C:\Users\mmaratt\Desktop\BladeTortoise\build\ALL_BUILD.vcxproj
PAUSE
EXIT
Tried and working. you are using,
<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>
I am using javascript , (don't know about php), use id ="status" in textarea like
<textarea name='Status' id="status"> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>
then make a call to servlet sending the status to backend for updating using whatever strutucre(like MVC in java or anyother) you like, like this in your UI in script tag
<srcipt>
function UpdateStatus(){
//make an ajax call and get status value using the same 'id'
var var1= document.getElementById("status").value;
$.ajax({
type:"GET",//or POST
url:'http://localhost:7080/ajaxforjson/Testajax',
// (or whatever your url is)
data:{data1:var1},
//can send multipledata like {data1:var1,data2:var2,data3:var3
//can use dataType:'text/html' or 'json' if response type expected
success:function(responsedata){
// process on data
alert("got response as "+"'"+responsedata+"'");
}
})
}
</script>
and jsp is like
the servlet will look like: //webservlet("/zcvdzv") is just for url annotation
@WebServlet("/Testajax")
public class Testajax extends HttpServlet {
private static final long serialVersionUID = 1L;
public Testajax() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String data1=request.getParameter("data1");
//do processing on datas pass in other java class to add to DB
// i am adding or concatenate
String data="i Got : "+"'"+data1+"' ";
System.out.println(" data1 : "+data1+"\n data "+data);
response.getWriter().write(data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
I had an identical problem, which I solved by restarting my Python editor and shell. I had installed pywin32
but the new modules were not picked up until the restarts.
If you've already done that, do a search in your Python installation for win32api
and you should find win32api.pyd
under ${PYTHON_HOME}\Lib\site-packages\win32
.
webBrowser.NavigateToString(yourString);
Post to the UI thread works for me.
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
iv.post(new Runnable() {
@Override
public void run() {
int width = iv.getMeasuredWidth();
int height = iv.getMeasuredHeight();
}
});
You can do injection on Directives, and it looks just like it does everywhere else.
app.directive('changeIt', ['myData', function(myData){
return {
restrict: 'C',
link: function (scope, element, attrs) {
scope.name = myData.name;
}
}
}]);
Alongside the classic causes, mentioned elsewhere:
setContentView()
before findViewById()
id
you want is in the view or layout you've given to setContentView()
id
isn't accidentally duplicated in different layoutsThere is one I have found for custom views in standard layouts, which goes against the documentation:
In theory you can create a custom view and add it to a layout (see here). However, I have found that in such situations, sometimes the id
attribute works for all the views in the layout except the custom ones. The solution I use is:
FrameLayout
with the same layout properties as you would like the custom view to have. Give it an appropriate id
, say frame_for_custom_view
.In onCreate
:
setContentView(R.layout.my_layout);
FrameView fv = findViewById(R.id.frame_for_custom_layout);
MyCustomView cv = new MyCustomView(context);
fv.addView(cv);
which puts the custom view in the frame.
First off, Xvfb doesn't read configuration from xorg.conf. Xvfb is a variant of the KDrive X servers and like all members of that family gets its configuration from the command line.
It is true that XRandR and Xinerama are mutually exclusive, but in the case of Xvfb there's no Xinerama in the first place. You can enable the XRandR extension by starting Xvfb using at least the following command line options
Xvfb +extension RANDR [further options]
you also do something good:
text_empty = df['column name'].str.len() > -1
df.loc[text_empty].index
The results will be the rows which are empty & it's index number.
Use $PSVersionTable.PSVersion
to determine the engine version. If the variable does not exist, it is safe to assume the engine is version 1.0
.
Note that $Host.Version
and (Get-Host).Version
are not reliable - they reflect
the version of the host only, not the engine. PowerGUI,
PowerShellPLUS, etc. are all hosting applications, and
they will set the host's version to reflect their product
version — which is entirely correct, but not what you're looking for.
PS C:\> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
A bit late, but whatever.
If you prefer parsing JSON to JavaScript-like constructs making use of Kotlin syntax, I recommend JSONKraken, of which I am the author.
Suggestions and opinions on the matter are much apreciated!
for /r %%v in (*.xls) do ssconvert "%%v" "%%vx"
a couple have people have asked me to explain this, so:
Part 1: for /r %%v in (*.xls)
This part returns an array of files in the current directory that have the xls
extension. The %%
may look a little curious. This is basically the special %
character from command line as used in %PATH% or %TEMP%. To use it in a batch file we need to escape it like so: %%PATH%%
or %%TEMP%%
. In this case we are simply escaping the temporary variable v
, which will hold our array of filenames.
We are using the /r
switch to search for files recursively, so any matching files in child folders will also be located.
Part 2: do ssconvert "%%v" "%%vx"
This second part is what will get executed once per matching filename, so if the following files were present in the current folder:
c:\temp\mySheet.xls,
c:\temp\mySheet_yesterday.xls,
c:\temp\mySheet_20160902.xls
the following commands would be executed:
ssconvert "c:\temp\mySheet.xls" "c:\temp\mySheet.xlsx"
ssconvert "c:\temp\mySheet_yesterday.xls" "c:\temp\mySheet_yesterday.xlsx"
ssconvert "c:\temp\mySheet_20160902.xls" "c:\temp\mySheet_20160902.xlsx"
Why not use the Actions menu option to set this?
Do the following: If you have Acrobat Pro, go to your pages tab, right click on the thumbnail for the first page, and click page properties. Click on the actions tab at the top of the window and under select trigger choose page open. Under select action choose 'Execute a menu item'. Click the Add button then select 'File > Print' then OK. Click OK again and save the PDF.
I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:
ModelState.AddModelError(string key, string errorMessage);
but use an empty string for the key:
ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");
The error message will present itself in the <%: Html.ValidationSummary() %>
as you'd expect.
Isn't it smoother to make a method to be called after the creation of the EditText unit in an AlertDialog, for general use?
public static void EditTextListPicker(final Activity activity, final EditText EditTextItem, final String SelectTitle, final String[] SelectList) {
EditTextItem.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(SelectTitle);
builder.setItems(SelectList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
EditTextItem.setText(SelectList[item]);
}
});
builder.create().show();
return false;
}
});
}
If You using Android 9.0 with legacy jar than you have to use. in your mainfest file.
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
For me none of the packages mentioned above did help.
I finally managed to install lxml
after running:
sudo apt-get install python3.5-dev
Try executing 'mysql' or 'mysql -- version' without quotes on terminal. it will prompt version otherwise Command Not Found
Had this issue today on iOS 8 & 9 and it seems that we now need to add height: 100%;
So add
html,
body {
position: relative;
height: 100%;
overflow: hidden;
}
getElementById
returns null
if there is no such element.
$(document).ready(function() {
// place this within dom ready function
function showpanel() {
$(".navigation").hide();
$(".page").children(".panel").fadeIn(1000);
}
// use setTimeout() to execute
setTimeout(showpanel, 1000)
});
For more see here
As per apple docs: https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/Selector.html
A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled. A selector by itself doesn’t do anything. It simply identifies a method. The only thing that makes the selector method name different from a plain string is that the compiler makes sure that selectors are unique. What makes a selector useful is that (in conjunction with the runtime) it acts like a dynamic function pointer that, for a given name, automatically points to the implementation of a method appropriate for whichever class it’s used with. Suppose you had a selector for the method run, and classes Dog, Athlete, and ComputerSimulation (each of which implemented a method run). The selector could be used with an instance of each of the classes to invoke its run method—even though the implementation might be different for each.
Example: (lldb) breakpoint --set selector viewDidLoad
This will set a breakpoint on all viewDidLoad implementations in your app. So selector is kind of a global identifier for a method.
When implementing the constructor()
function inside a React component, super()
is a requirement. Keep in mind that your MyComponent
component is extending or borrowing functionality from the React.Component
base class.
This base class has a constructor()
function of its own that has some code inside of it, to setup our React component for us.
When we define a constructor()
function inside our MyComponent
class, we are essentially, overriding or replacing the constructor()
function that is inside the React.Component
class, but we still need to ensure that all the setup code inside of this constructor()
function still gets called.
So to ensure that the React.Component
’s constructor()
function gets called, we call super(props)
. super(props)
is a reference to the parents constructor()
function, that’s all it is.
We have to add super(props)
every single time we define a constructor()
function inside a class-based component.
If we don’t we will see an error saying that we have to call super(props)
.
The entire reason for defining this constructor()
funciton is to initialize our state object.
So in order to initialize our state object, underneath the super call I am going to write:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
// React says we have to define render()
render() {
return <div>Hello world</div>;
}
};
So we have defined our constructor()
method, initialized our state object by creating a JavaScript object, assigning a property or key/value pair to it, assigning the result of that to this.state
. Now of course this is just an example here so I have not really assigned a key/value pair to the state object, its just an empty object.
Use this:
Request.Url.AbsoluteUri
That will get you the full path (including http://...)
I have come accross same as this problem i installed cv2 by
pip install cv2
However when i import cv2 module it displayed no module named cv2 error.
Then i searched and find cv2.pyd
files in my computer and i copy and paste to site-packages directory
C:\Python27\Lib\site-packages
then i closed and reopened existing application, it worked.
EDIT
I will tell how to install cv2
correctly.
1. Firstly install numpy on your computer by
pip install numpy
2. Download opencv from internet (almost 266 mb).
I download opencv-2.4.12.exe
for python 2.7. Then install this opencv-2.4.12.exe file.
I extracted to C:\Users\harun\Downloads
to this folder.
After installation go look for cv2.py
into the folders.
For me
C:\Users\harun\Downloads\opencv\build\python\2.7\x64
in this folder take thecv2.pyd
and copy it in to the
C:\Python27\Lib\site-packages
now you can able to use cv2
in you python scripts.
You can do it with _.pullAllBy.
var countries = {};_x000D_
_x000D_
countries.results = [_x000D_
{id:'AF',name:'Afghanistan'},_x000D_
{id:'AL',name:'Albania'},_x000D_
{id:'DZ',name:'Algeria'}_x000D_
];_x000D_
_x000D_
// Remove element by id_x000D_
_.pullAllBy(countries.results , [{ 'id': 'AL' }], 'id');_x000D_
_x000D_
// Remove element by name_x000D_
// _.pullAllBy(countries.results , [{ 'name': 'Albania' }], 'name');_x000D_
console.log(countries);
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
top: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
I've a span
inside a div
and just setting margin: auto
to the container div
worked for me.
i wasn't able to make it work on windows even after installing pyopenssl and trying various python versions (while it worked fine on mac), so i switched to urllib and it works on python 3.6 (from python .org) and 3.7 (anaconda)
import urllib
from urllib.request import urlopen
html = urlopen("http://pythonscraping.com/pages/page1.html")
contents = html.read()
print(contents)
You can run a shell in a running docker container using a command like:
docker exec -it --user root <container id> /bin/bash
You can use
alter table <tblname> drop column <colname>
var future = new Date(); // get today date_x000D_
future.setDate(future.getDate() + 7); // add 7 days_x000D_
var finalDate = future.getFullYear() +'-'+ ((future.getMonth() + 1) < 10 ? '0' : '') + (future.getMonth() + 1) +'-'+ future.getDate();_x000D_
console.log(finalDate);
_x000D_
I understand what you are trying to do.The best and the most successful way is :
<select name='department' required>
<option value="">None</option>
<option value="Teaching">Teaching department</option>
<option value="nonTeaching">Non-teaching department</option>
</select>
MultiBinding friendly version...
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
BindingOperations.GetBindingExpressionBase((ComboBox)sender, ComboBox.ItemsSourceProperty).UpdateTarget();
}
One thing that to be remembered while solving such problems is that in JSON file, a {
indicates a JSONObject
and a [
indicates JSONArray
. If one could manage them properly, it would be very easy to accomplish the task of parsing the JSON file. The above code was really very helpful for me and I hope this content adds some meaning to the above code.
The Gson JsonReader documentation explains how to handle parsing of JsonObjects
and JsonArrays
:
- Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
- Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().
As of June 2020, adding role='button'
to any HTML tag would add cursor: "pointer"
to the element styling.
<span role="button">Non-button element button</span>
Official discussion on this feature - https://github.com/twbs/bootstrap/issues/23709
Documentation link - https://getbootstrap.com/docs/4.5/content/reboot/#pointers-on-buttons
There are three ways to save objects from your R session:
The save.image()
function will save all objects currently in your R session:
save.image(file="1.RData")
These objects can then be loaded back into a new R session using the load()
function:
load(file="1.RData")
If you want to save some, but not all objects, you can use the save()
function:
save(city, country, file="1.RData")
Again, these can be reloaded into another R session using the load()
function:
load(file="1.RData")
If you want to save a single object you can use the saveRDS()
function:
saveRDS(city, file="city.rds")
saveRDS(country, file="country.rds")
You can load these into your R session using the readRDS()
function, but you will need to assign the result into a the desired variable:
city <- readRDS("city.rds")
country <- readRDS("country.rds")
But this also means you can give these objects new variable names if needed (i.e. if those variables already exist in your new R session but contain different objects):
city_list <- readRDS("city.rds")
country_vector <- readRDS("country.rds")
I tried all the steps mentioned here and on similar questions but couldn't solve this problem. I could neither solve problem nor update my m2eclipse. So I installed Eclipse Luna and it solved my problem... though it mean that I had to spend about 45 min to configure all the environment in my workspace.
I used the ../ method to fetch the current project path.
Example: Project1 -- D:\projects
src
ConfigurationFiles
Configuration.cfg
Path="../src/ConfigurationFiles/Configuration.cfg"
Download the latest version of genymotion and after creating a device click on Open GAPP in device right side.
That work for me
I found the approach how to get data from child component in parents when i need it.
Parent:
class ParentComponent extends Component{
onSubmit(data) {
let mapPoint = this.getMapPoint();
}
render(){
return (
<form onSubmit={this.onSubmit.bind(this)}>
<ChildComponent getCurrentPoint={getMapPoint => {this.getMapPoint = getMapPoint}} />
<input type="submit" value="Submit" />
</form>
)
}
}
Child:
class ChildComponent extends Component{
constructor(props){
super(props);
if (props.getCurrentPoint){
props.getCurrentPoint(this.getMapPoint.bind(this));
}
}
getMapPoint(){
return this.Point;
}
}
This example showing how to pass function from child component to parent and use this function to get data from child.
Don't split on commas -- it won't work for most CSV files, and this question has wayyyy too many views for the asker's kind of input data to apply to everyone. Parsing CSV is kind of scary since there's no truly official standard, and lots of delimited text writers don't consider edge cases.
This question is old, but I believe there's a better solution now that Papa Parse is available. It's a library I wrote, with help from contributors, that parses CSV text or files. It's the only JS library I know of that supports files gigabytes in size. It also handles malformed input gracefully.
1 GB file parsed in 1 minute:
(Update: With Papa Parse 4, the same file took only about 30 seconds in Firefox. Papa Parse 4 is now the fastest known CSV parser for the browser.)
Parsing text is very easy:
var data = Papa.parse(csvString);
Parsing files is also easy:
Papa.parse(file, {
complete: function(results) {
console.log(results);
}
});
Streaming files is similar (here's an example that streams a remote file):
Papa.parse("http://example.com/bigfoo.csv", {
download: true,
step: function(row) {
console.log("Row:", row.data);
},
complete: function() {
console.log("All done!");
}
});
If your web page locks up during parsing, Papa can use web workers to keep your web site reactive.
Papa can auto-detect delimiters and match values up with header columns, if a header row is present. It can also turn numeric values into actual number types. It appropriately parses line breaks and quotes and other weird situations, and even handles malformed input as robustly as possible. I've drawn on inspiration from existing libraries to make Papa, so props to other JS implementations.
There's another solution that also works.
This works because you have multiple classes in different jar files. Removing and re-adding the JRE lib will make the right classes be first. If you want a fundamental solution make sure you exclude the jar files with the same classes.
For me I have: javax.xml.soap.SOAPPart
in three different jars: axis-saaj-1.4.jar
, saaj-api-1.3.jar
and the rt.jar
Sometimes you have an object to the MyEnum
type. Like
var MyEnumType = typeof(MyEnum);
Then:
Enum.ToObject(typeof(MyEnum), 3)
IF you are using Vector3 this is what i did
1- I create a class Name it Player
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Player
{
public Vector3[] Position;
}
2- then i call it like this
if ( _ispressed == true)
{
Player playerInstance = new Player();
playerInstance.Position = newPos;
string jsonData = JsonUtility.ToJson(playerInstance);
reference.Child("Position" + Random.Range(0, 1000000)).SetRawJsonValueAsync(jsonData);
Debug.Log(jsonData);
_ispressed = false;
}
3- and this is the result
"Position":[ {"x":-2.8567452430725099,"y":-2.4323320388793947,"z":0.0}]}
Use compareWith
, A function to compare the option values with the selected values. see here: https://material.angular.io/components/select/api#MatSelect
For an object of the following structure:
listOfObjs = [{ name: 'john', id: '1'}, { name: 'jimmy', id: '2'},...]
Define markup like this:
<mat-form-field>
<mat-select
[compareWith]="compareObjects"
[(ngModel)]="obj">
<mat-option *ngFor="let obj of listOfObjs" [value]="obj">
{{ obj.name }}
</mat-option>
</mat-select>
</mat-form-field>
And define comparison function like this:
compareObjects(o1: any, o2: any): boolean {
return o1.name === o2.name && o1.id === o2.id;
}
you can use the DomDocument method to get an individual HTML tag level variable too
$homepage = file_get_contents('https://www.example.com/');
$doc = new DOMDocument;
$doc->loadHTML($homepage);
$titles = $doc->getElementsByTagName('h3');
echo $titles->item(0)->nodeValue;
Converting of a hash map to a string of query parameters:
Map<String, String> params = new HashMap<>();
params.put("msisdn", msisdn);
params.put("email", email);
params.put("clientVersion", clientVersion);
params.put("clientType", clientType);
params.put("issuerName", issuerName);
params.put("applicationName", applicationName);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.queryParam(entry.getKey(), entry.getValue());
}
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
HttpEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, new HttpEntity(headers), String.class);
Try casting to List in the extension method before running the loop. That way you can take advantage of the performance of List.AddRange.
public static void AddRange<T>(this ICollection<T> destination,
IEnumerable<T> source)
{
List<T> list = destination as List<T>;
if (list != null)
{
list.AddRange(source);
}
else
{
foreach (T item in source)
{
destination.Add(item);
}
}
}
Spring Data JPA 1.11 now supports the exists
projection in repository query derivation.
See documentation here.
In your case the following will work:
public interface MyEntityRepository extends CrudRepository<MyEntity, String> {
boolean existsByFoo(String foo);
}
import random
result=[]
for i in range(1,50):
rng=random.randint(1,20)
result.append(rng)
I understand the original post is for Oracle 10 but this is for reference by anyone else who finds it via Google.
Under Oracle 12c, I found that that my registry$history is empty. This works instead:
select * from registry$sqlpatch;
First, let's make some test data:
create table client (client_id integer not null primary key auto_increment,
name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
client_id integer references client.id,
cash decimal(10,2),
stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
(1, 10.11, 23.22),
(2, 30.30, 40.40),
(2, 40.40, 50.50);
If you didn't need the portfolio ID, it would be easy:
select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id
+-----------+----------+--------------------+
| client_id | name | max(cash + stocks) |
+-----------+----------+--------------------+
| 1 | John Doe | 33.33 |
| 2 | Jane Doe | 90.90 |
+-----------+----------+--------------------+
Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:
select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id
+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
| 1 | 33.33 |
| 2 | 90.90 |
+-----------+----------+
Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:
select portfolio_id, cash + stocks from portfolio
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
| 5 | 33.33 |
| 6 | 33.33 |
| 8 | 90.90 |
+--------------+---------------+
Finally, we can join to the client table (as you did) in order to include the name of each client:
select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
+-----------+----------+--------------+---------------+
| client_id | name | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
| 1 | John Doe | 5 | 33.33 |
| 1 | John Doe | 6 | 33.33 |
| 2 | Jane Doe | 8 | 90.90 |
+-----------+----------+--------------+---------------+
Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:
select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks
+-----------+----------+--------------+---------------+
| client_id | name | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
| 1 | John Doe | 5 | 33.33 |
| 2 | Jane Doe | 8 | 90.90 |
+-----------+----------+--------------+---------------+
Here is perhaps the simplest explanation of how OAuth2 works for all 4 grant types, i.e., 4 different flows where the app can acquire the access token.
Similarity
All grant type flows have 2 parts:
The 2nd part 'use access token' is the same for all flows
Difference
The 1st part of the flow 'get access token' for each grant type varies.
However, in general the 'get access token' part can be summarized as consisting 5 steps:
Here is a side-by-side diagram comparing how each grant type flow is different based on the 5 steps.
This diagram is from https://blog.oauth.io/introduction-oauth2-flow-diagrams/
Each have different levels of implementation difficulty, security, and uses cases. Depending on your needs and situation, you will have to use one of them. Which to use?
Client Credential: If your app is only serving a single user
Resource Owner Password Crendential: This should be used only as last resort as the user has to hand over his credentials to the app, which means the app can do everything the user can
Authorization Code: The best way to get user authorization
Implicit: If you app is mobile or single-page app
There is more explanation of the choice here: https://blog.oauth.io/choose-oauth2-flow-grant-types-for-app/
Check this thread out: read and write image file.
Also, have a look at this other question at Stackoverflow.
You can use something like this:
for i in `cat foo.txt`
do
sudo $i
done
Though if the commands have arguments (i.e. there is whitespace in the lines) you may have to monkey around with that a bit to protect the whitepace so that the whole string is seen by sudo
as a command. But it gives you an idea on how to start.
The way to get the results of your formula would be to start in a new sheet.
In cell A1 put the formula
=IF('testsheet'!C1 <= 99,'testsheet'!A1,"")
Copy that cell down to row 40 In cell B1 put the formula
=A1
In cell B2 put the formula
=B1 & A2
Copy that cell down to row 40.
The value you want is now in that column in row 40.
Not really the answer you want, but that is the fastest way to get things done excel wise without creating a custom formula that takes in a range and makes the calculation (which would be more fun to do).
Why do you want to enforce that only a single thread can access the DB at any one time?
It is the job of the database driver to implement any necessary locking, assuming a Connection
is only used by one thread at a time!
Most likely, your database is perfectly capable of handling multiple, parallel access
For Rect-Native developers. I encounter this error while renderingItem in FlatList. I had two Text components. I was using them like below
renderItem = { ({item}) =>
<Text style = {styles.item}>{item.key}</Text>
<Text style = {styles.item}>{item.user}</Text>
}
But after I put these tow Inside View Components it worked for me.
renderItem = { ({item}) =>
<View style={styles.flatview}>
<Text style = {styles.item}>{item.key}</Text>
<Text style = {styles.item}>{item.user}</Text>
</View>
}
You might be using other components but putting them into View may be worked for you.
From the numpy fft page http://docs.scipy.org/doc/numpy/reference/routines.fft.html:
When the input a is a time-domain signal and A = fft(a), np.abs(A) is its amplitude spectrum and np.abs(A)**2 is its power spectrum. The phase spectrum is obtained by np.angle(A).
Ultimately it probably doesn't have a safe .get
method because a dict
is an associative collection (values are associated with names) where it is inefficient to check if a key is present (and return its value) without throwing an exception, while it is super trivial to avoid exceptions accessing list elements (as the len
method is very fast). The .get
method allows you to query the value associated with a name, not directly access the 37th item in the dictionary (which would be more like what you're asking of your list).
Of course, you can easily implement this yourself:
def safe_list_get (l, idx, default):
try:
return l[idx]
except IndexError:
return default
You could even monkeypatch it onto the __builtins__.list
constructor in __main__
, but that would be a less pervasive change since most code doesn't use it. If you just wanted to use this with lists created by your own code you could simply subclass list
and add the get
method.
On the SubLogin Form I would expose a SetLocation method so that you can set it from your parent form:
public class SubLogin : Form
{
public void SetLocation(Point p)
{
this.Location = p;
}
}
Then, from your main form:
loginForm = new SubLogin();
Point p = //do math to get point
loginForm.SetLocation(p);
loginForm.Show();
Can you use date as a factor?
Yes, but you probably shouldn't.
...or should you use
as.Date
on a date column?
Yes.
Which leads us to this:
library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) +
geom_bar(stat = "identity") +
theme_bw() +
labs(x = "Month", y = "Average Visits per User") +
scale_x_date(labels = date_format("%m-%Y"))
in which I've added stat = "identity"
to your geom_bar
call.
In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.
If you don't want to make the button a separate image, you can use the <area>
tag. This is done by using html similar to this:
<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">
<map name="mapname">
<area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>
Note 1: The coords=" "
attribute must be formatted in this way: coords="x1,y1,x2,y2"
where:
x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate
Note 2: The usemap="#mapname"
attribute must include the #
.
EDIT:
I looked at your code and added in the <map>
and <area>
tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.
<div class="flexslider">
<ul class="slides" runat="server" id="Ul">
<li class="flex-active-slide" style="background: url("images/slider-bg-1.jpg") no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
<div class="container">
<div class="sixteen columns contain"></div>
<img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
<map name="imgmap">
<area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
</map>
<!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
</div>
</li>
</ul>
</div>
<!-- <ul class="flex-direction-nav">
<li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
<li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->
Notes:
coord="48,341,294,275"
is in reference to your screenshot you posted.src="./test.png"
is the location and name of the screenshot you posted on my computer.href="http://www.example.com/"
is an example link.For us-based address data my company has used GeoStan. It has bindings for C and Java (and we created a Perl binding). Note that it is a commercial product and isn't cheap. It is quite fast though (~300 addresses per second) and offers features like CASS certification (USPS bulk mail discount), DPV (Delivery point verification) flagging, and LON/LAT geocoding.
There is a Perl module Geo::PostalAddress, but it uses heuristics and doesn't have the other features mentioned for GeoStan.
Edit: some have mentioned 'doing it yourself', if you do decide to do this, a good source of information to start with is the US Census Tiger Data Set, which contains a lot of information about the US including address information.
df = pandas.DataFrame({'g':[1]}, index=['isStop'])
#df.loc['g']
if 'g' in df.index:
print("find g")
if 'isStop' in df.index:
print("find a")
Yet another option is argh. It builds on argparse, and lets you write things like:
import argh
# declaring:
def echo(text):
"Returns given word as is."
return text
def greet(name, greeting='Hello'):
"Greets the user with given name. The greeting is customizable."
return greeting + ', ' + name
# assembling:
parser = argh.ArghParser()
parser.add_commands([echo, greet])
# dispatching:
if __name__ == '__main__':
parser.dispatch()
It will automatically generate help and so on, and you can use decorators to provide extra guidance on how the arg-parsing should work.
You want in page A to know the URL of page B?
Or to know in page B the URL of page A?
In Page B: document.referrer if set. As already shown here: How to get the previous URL in JavaScript?
In page A you would need to read a cookie or local/sessionStorage you set in page B, assuming the same domains
Heres a quick solution.
You find styles.xml and you change the base application theme to "Theme.AppCompat.NoActionBar" as shown below.
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
<!-- Customize your theme here. -->
</style>
If you using JavaScript to test your Regex, try \\.
instead of \.
.
It acts on the same way because JS remove first backslash.
You're saying you want a "serverless" solution. But that means you have no ability to put any of "your" code in the loop. (NOTE: Once you give your code to a client, it's "their" code now.) Locking down CORS is not going to help: People can easily write a non-web-based tool (or a web-based proxy) that adds the correct CORS header to abuse your system.
The big problem is that you can't differentiate between the different users. You can't allow one user to list/access his files, but prevent others from doing so. If you detect abuse, there is nothing you can do about it except change the key. (Which the attacker can presumably just get again.)
Your best bet is to create an "IAM user" with a key for your javascript client. Only give it write access to just one bucket. (but ideally, do not enable the ListBucket operation, that will make it more attractive to attackers.)
If you had a server (even a simple micro instance at $20/month), you could sign the keys on your server while monitoring/preventing abuse in realtime. Without a server, the best you can do is periodically monitor for abuse after-the-fact. Here's what I would do:
1) periodically rotate the keys for that IAM user: Every night, generate a new key for that IAM user, and replace the oldest key. Since there are 2 keys, each key will be valid for 2 days.
2) enable S3 logging, and download the logs every hour. Set alerts on "too many uploads" and "too many downloads". You will want to check both total file size and number of files uploaded. And you will want to monitor both the global totals, and also the per-IP address totals (with a lower threshold).
These checks can be done "serverless" because you can run them on your desktop. (i.e. S3 does all the work, these processes just there to alert you to abuse of your S3 bucket so you don't get a giant AWS bill at the end of the month.)
I have used both MVP and MVC and although we as developers tend to focus on the technical differences of both patterns the point for MVP in IMHO is much more related to ease of adoption than anything else.
If I’m working in a team that already as a good background on web forms development style it’s far easier to introduce MVP than MVC. I would say that MVP in this scenario is a quick win.
My experience tells me that moving a team from web forms to MVP and then from MVP to MVC is relatively easy; moving from web forms to MVC is more difficult.
I leave here a link to a series of articles a friend of mine has published about MVP and MVC.
http://www.qsoft.be/post/Building-the-MVP-StoreFront-Gutthrie-style.aspx
I recently saw that I was having the same problem. Visual Studio 2010 was refusing to update the designer file.
As it turns out, VS doesn't modify the designer file for a page that uses CodeFile (run off of pages) instead of CodeBehind (DLL). This is true no matter how many times you close VS, reload the project, re-create the control(s), or modify a file. Nothing would prompt VS to regenerate the designer. It's as if it doesn't create the designer file for CodeFile pages but does require it to be there.
I changed it to CodeBehind and saved the page. The designer file updated immediately. Then I just changed it back and everything was still golden. This behavior seems to be new with VS 2010 / .NET 4.0 as VS 2008 by default didn't suffer from this.
It's this part:
<%@ Page Language="vb" AutoEventWireup="false" CodeFile="YourPage.aspx.vb" Inherits="YourPageClass" %>
Change CodeFile to CodeBehind, save, and then revert.
If you have configuration like this:
<VirtualHost *:80>
ServerName example.com
DocumentRoot "/var/www/example.com"
<FilesMatch "\.php$">
SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>
</VirtualHost>
Uncomment next lines in your httpd.conf
LoadModule proxy_module lib/httpd/modules/mod_proxy.so
LoadModule proxy_fcgi_module lib/httpd/modules/mod_proxy_fcgi.so
It works for me
for my use case, i wanted to grab the SHA1 hash from the magisk config file. the below worked for me.
adb shell "su -c "cat /sbin/.magisk/config | grep SHA | awk -F= '{ print $2 }'""
Since Android 7.0 you can use adb shell cmd package resolve-activity
command to get the default activity of an installed app like this:
adb shell "cmd package resolve-activity --brief com.google.android.calculator | tail -n 1"
com.google.android.calculator/com.android.calculator2.Calculator
For Each dcfColumn As DataControlField In gvGridview.Columns
If dcfColumn.HeaderText = "ColumnHeaderText" Then
dcfColumn.Visible = false
End If
Next
Null is not an instance of any class.
However, you can assign null to variables of any (object or array) type:
// this is false
boolean nope = (null instanceof String);
// but you can still use it as a String
String x = null;
"abc".startsWith(null);
5th highest salary:
SELECT
*
FROM
emp a
WHERE
4 = (
SELECT
COUNT(DISTINCT b.sal)
FROM
emp b
WHERE
a.sal < b.sal
)
Replace 4 with any value of N.
It is possible to have 2 groovy-xxx-all.jar files by excample in lib directory. which makes that an app is not running
The most voted solution did not work for me.(Bootstrap 3.0.0) However, this did:
.nav-pills > li.active > a, .nav-pills > li.active > a:hover, .nav-pills > li.active > a:focus {
color:black;
background-color:#fcd900;
}
including this on the page <style></style>
tags serves for the per page basis well
and mixing it on two shades gives a brilliant effect like:
<style>
.nav-pills > li.active > a, .nav-pills > li.active > a:focus {
color: black;
background-color: #fcd900;
}
.nav-pills > li.active > a:hover {
background-color: #efcb00;
color:black;
}
</style>
When adding a directory to github check that the directory does not contain a .git file using "ls -a" if it does remove it. .git files in a directory will cause problems when you are trying to add a that directory in git
This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.
It is now possible using:
@import 'CSS:directory/filename.css';
long timestamp = Long.parseLong(date)
Date expiry = new Date(timestamp * 1000)
As several answer explained the you should run:
npm i
BUT if it does not solve...
Check the version of your npm
executable. (For me it was 3.x.x which doesn't uses the package-lock.json
(at all))
npm -v
It should be at least 5.x.x (which introduced the package-lock.json file.)
To update npm
on Linux, follow these instructions.
For more details about package files, please read this medium story.
You can give the background image in css :
#canvas { background:url(example.jpg) }
it will show you canvas back ground image
You can also use the read-only property key
. It also respects special keys like shift etc. and is supported by IE9.
When a non-printable or special character is pressed, the value will be on of the defined key values like 'Shift'
or 'Multiply'
.
event.key
'x'
'X'
'F5'
Supported Operating Systems:
- Windows 8.1 (x86 and x64)
- Windows 8 (x86 and x64)
- Windows 7 SP1 (x86 and x64)
- Windows Server 2012 R2 (x64)
- Windows Server 2012 (x64)
- Windows Server 2008 R2 SP1 (x64)
Hardware requirements:
- 1.6 GHz or faster processor
- 1 GB of RAM (1.5 GB if running on a virtual machine)
- 20 GB of available hard disk space
- 5400 RPM hard disk drive
- DirectX 9-capable video card that runs at 1024 x 768 or higher display resolution
Additional Requirements for the laptop:
- Internet Explorer 10
- KB2883200 (available through Windows Update) is required
And don't forget to reboot after updating your windows
If you wish to have a progress bar without adding some code PACE can be an awesome tool for you.
Just include pace.js and a CSS theme of your choice, and you get a beautiful progress indicator for your page load and AJAX navigation. Best thing with PACE is the auto detection of progress.
It contains various themes and color schemes as well.
Worth a try.
perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/' file1 file2
Another mode is: If your editor HAS NO BLOCK comment option,
DONE
it WORKS with ANY editor
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
With HTML 5, use the history.pushState
function. As an example:
<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>
and a href:
<a href="#" id='click'>Click to change url to bar.html</a>
If you want to change the URL without adding an entry to the back button list, use history.replaceState
instead.
For someone looking for a NEST JS TYPESCRIPT
version of the above:
/**
* to fetch a signed URL of a file
* @param key key of the file to be fetched
* @param bucket name of the bucket containing the file
*/
public getFileUrl(key: string, bucket?: string): Promise<string> {
var scopeBucket: string = bucket ? bucket : this.defaultBucket;
var params: any = {
Bucket: scopeBucket,
Key: key,
Expires: signatureTimeout // const value: 30
};
return this.account.getSignedUrlPromise(getSignedUrlObject, params);
}
/**
* to get the downloadable file buffer of the file
* @param key key of the file to be fetched
* @param bucket name of the bucket containing the file
*/
public async getFileBuffer(key: string, bucket?: string): Promise<Buffer> {
var scopeBucket: string = bucket ? bucket : this.defaultBucket;
var params: GetObjectRequest = {
Bucket: scopeBucket,
Key: key
};
var fileObject: GetObjectOutput = await this.account.getObject(params).promise();
return Buffer.from(fileObject.Body.toString());
}
/**
* to upload a file stream onto AWS S3
* @param stream file buffer to be uploaded
* @param key key of the file to be uploaded
* @param bucket name of the bucket
*/
public async saveFile(file: Buffer, key: string, bucket?: string): Promise<any> {
var scopeBucket: string = bucket ? bucket : this.defaultBucket;
var params: any = {
Body: file,
Bucket: scopeBucket,
Key: key,
ACL: 'private'
};
var uploaded: any = await this.account.upload(params).promise();
if (uploaded && uploaded.Location && uploaded.Bucket === scopeBucket && uploaded.Key === key)
return uploaded;
else {
throw new HttpException("Error occurred while uploading a file stream", HttpStatus.BAD_REQUEST);
}
}
You're pretty much right about cout
and cin
. They are objects (not functions) defined inside the std
namespace. Here are their declarations as defined by the C++ standard:
Header
<iostream>
synopsis#include <ios> #include <streambuf> #include <istream> #include <ostream> namespace std { extern istream cin; extern ostream cout; extern ostream cerr; extern ostream clog; extern wistream wcin; extern wostream wcout; extern wostream wcerr; extern wostream wclog; }
::
is known as the scope resolution operator. The names cout
and cin
are defined within std
, so we have to qualify their names with std::
.
Classes behave a little like namespaces in that the names declared inside the class belong to the class. For example:
class foo
{
public:
foo();
void bar();
};
The constructor named foo
is a member of the class named foo
. They have the same name because its the constructor. The function bar
is also a member of foo
.
Because they are members of foo
, when referring to them from outside the class, we have to qualify their names. After all, they belong to that class. So if you're going to define the constructor and bar
outside the class, you need to do it like so:
foo::foo()
{
// Implement the constructor
}
void foo::bar()
{
// Implement bar
}
This is because they are being defined outside the class. If you had not put the foo::
qualification on the names, you would be defining some new functions in the global scope, rather than as members of foo
. For example, this is entirely different bar
:
void bar()
{
// Implement different bar
}
It's allowed to have the same name as the function in the foo
class because it's in a different scope. This bar
is in the global scope, whereas the other bar
belonged to the foo
class.
Here is the solution I came up with when using PowerShell
.
Add the below function to your Microsoft.PowerShell_profile.ps1
function RunSsh($userIdentity ) {
$agent=ssh-agent
$position=$agent[0].IndexOf("=")
$ending=$agent[0].IndexOf(";")
$variableStartPosition=$agent[0].IndexOf("export")
$variableEndPosition=$agent[0].LastIndexOf(";")
$variableName=$agent[0].Substring($variableStartPosition+7,$variableEndPosition-$variableStartPosition-7)
[Environment]::SetEnvironmentVariable($variableName, $agent[0].Substring($position+1,$ending-$position-1))
$position=$agent[1].IndexOf("=")
$ending=$agent[1].IndexOf(";")
$variableStartPosition=$agent[1].IndexOf("export")
$variableEndPosition=$agent[1].LastIndexOf(";")
$variableName=$agent[1].Substring($variableStartPosition+7,$variableEndPosition-$variableStartPosition-7)
[Environment]::SetEnvironmentVariable($variableName, $agent[1].Substring($position+1,$ending-$position-1))
if($userIdentity.Length -eq 0) {
ssh-add
} else {
ssh-add $userIdentity
}
}
Now from the command line you can run RunSsh
which uses identity file in ~\.ssh
folder or pass in the identity file with RunSsh C:\ssh\id_rsa
where C:\ssh\id_rsa
is your identity file.
For this to work you need to have ssh-add
and ssh-agent
in your path
environment variable.
For the JS, try
data: {id: the_id}
...
success: function(data) {
alert('the server returned ' + data;
}
and
$the_id = intval($_POST['id']);
in PHP
If you happen to scroll down to this point, I found a solution for Firefox. It will print contents from a specific div without the footers and headers. You can customize as you wish.
Firstly, download and install this addon : JSPrintSetup.
Secondly, write this function:
<script>
function PrintElem(elem)
{
var mywindow = window.open('', 'PRINT', 'height=400,width=600');
mywindow.document.write('<html><head><title>' + document.title + '</title>');
mywindow.document.write('</head><body >');
mywindow.document.write(elem);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
//jsPrintSetup.setPrinter('PDFCreator'); //set the printer if you wish
jsPrintSetup.setSilentPrint(1);
//sent empty page header
jsPrintSetup.setOption('headerStrLeft', '');
jsPrintSetup.setOption('headerStrCenter', '');
jsPrintSetup.setOption('headerStrRight', '');
// set empty page footer
jsPrintSetup.setOption('footerStrLeft', '');
jsPrintSetup.setOption('footerStrCenter', '');
jsPrintSetup.setOption('footerStrRight', '');
// print my window silently.
jsPrintSetup.printWindow(mywindow);
jsPrintSetup.setSilentPrint(1); //change to 0 if you want print dialog
mywindow.close();
return true;
}
</script>
Thirdly, In your code, wherever you want to write the print code, do this (I have used JQuery. You can use plain javascript):
<script>
$("#print").click(function () {
var contents = $("#yourDivToPrint").html();
PrintElem(contents);
})
</script>
Obviously, you need the link to click:
<a href="#" id="print">Print my Div</a>
And your div to print:
<div id="yourDivToPrint">....</div>
I had the same problem. Changing controlers first letter to uppercase helped.
Following code will do the task....
<?php
$contacts = array(
"[email protected]",
"[email protected]",
//....as many email address as you need
);
foreach($contacts as $contact) {
$to = $contact;
$subject = 'the subject';
$message = 'hello';
mail($to, $subject, $message, $headers);
}
?>
Note this isn't at heart a question about JComboBox, but about any collection that can include multiple types of objects. The same could be said for "How do I get a String out of a List?" or "How do I get a String
out of an Object[]
?"
Read from excel, modify and write back
/// <summary>
/// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
/// </summary>
/// <param name="filename"></param>
/// <param name="headers">If set to true the first row will be considered as headers</param>
/// <returns></returns>
public DataSet Import(string filename, bool headers = true)
{
var _xl = new Excel.Application();
var wb = _xl.Workbooks.Open(filename);
var sheets = wb.Sheets;
DataSet dataSet = null;
if (sheets != null && sheets.Count != 0)
{
dataSet = new DataSet();
foreach (var item in sheets)
{
var sheet = (Excel.Worksheet)item;
DataTable dt = null;
if (sheet != null)
{
dt = new DataTable();
var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[1, j + 1];
var column = new DataColumn(headers ? cell.Value : string.Empty);
dt.Columns.Add(column);
}
for (int i = 0; i < rowCount; i++)
{
var r = dt.NewRow();
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
r[j] = cell.Value;
}
dt.Rows.Add(r);
}
}
dataSet.Tables.Add(dt);
}
}
_xl.Quit();
return dataSet;
}
public string Export(DataTable dt, bool headers = false)
{
var wb = _xl.Workbooks.Add();
var sheet = (Excel.Worksheet)wb.ActiveSheet;
//process columns
for (int i = 0; i < dt.Columns.Count; i++)
{
var col = dt.Columns[i];
//added columns to the top of sheet
var currentCell = (Excel.Range)sheet.Cells[1, i + 1];
currentCell.Value = col.ToString();
currentCell.Font.Bold = true;
//process rows
for (int j = 0; j < dt.Rows.Count; j++)
{
var row = dt.Rows[j];
//added rows to sheet
var cell = (Excel.Range)sheet.Cells[j + 1 + 1, i + 1];
cell.Value = row[i];
}
currentCell.EntireColumn.AutoFit();
}
var fileName="{somepath/somefile.xlsx}";
wb.SaveCopyAs(fileName);
_xl.Quit();
return fileName;
}
You can use like the following
string result = null;
object value = cmd.ExecuteScalar();
if (value != null)
{
result = value.ToString();
}
conn.Close();
return result;
No. The only officially supported tool for downloading and updating Cygwin packages is the setup.exe file you used for the initial install, although that can be invoked with command line arguments to help the process.
From that same page:
The basic reason for not having a more full-featured package manager is that such a program would need full access to all of Cygwin's POSIX functionality. That is, however, difficult to provide in a Cygwin-free environment, such as exists on first installation. Additionally, Windows does not easily allow overwriting of in-use executables so installing a new version of the Cygwin DLL while a package manager is using the DLL is problematic.
This will download all packages and dependencies (no already installed) to a directory of your choice:
sudo apt-get install -d -o Dir::Cache=/path-to/directory/apt/cache -o Dir::State::Lists=/path-to/directory/apt/lists packages
Make sure /path-to/directory/apt/cache
and /path-to/directory/apt/lists
exist.
If you don't set -o Dir::Cache
it points to /var/cache/apt
,
Dir::State::Lists
points to /var/lib/apt/lists
(which keeps the index files of available packages)
Both -o
options can be used with update and upgrade instead of install.
On different machine run the same command without '-d
'
Has there been any development with Actuator HTTP Trace since the initial question was posted i.e. is there a way to enrich it with the response body?
What about enriching it with custom metadata from MDC or from Spring-Sleuth or Zipkin, such as traceId and spanId?
Also for me Actuator HTTP Trace didn't work Spring Boot 2.2.3, and I found the fix here: https://juplo.de/actuator-httptrace-does-not-work-with-spring-boot-2-2/
pom.xml
<dependency>
<groupId>org.springframework.boot
<artifactId>spring-boot-starter-actuator
</dependency>
application.properties
management.endpoints.web.exposure.include=httptrace
The fix:
The simple fix for this problem is, to add a @Bean of type InMemoryHttpTraceRepository to your @Configuration-class:
@Bean
public HttpTraceRepository htttpTraceRepository()
{
return new InMemoryHttpTraceRepository();
}
The Explanation:
The cause of this problem is not a bug, but a legitimate change in the default configuration. Unfortunately, this change is not noted in the according section of the documentation. Instead it is burried in the Upgrade Notes for Spring Boot 2.2
The default-implementation stores the captured data in memory. Hence, it consumes much memory, without the user knowing, or even worse: needing it. This is especially undesirable in cluster environments, where memory is a precious good. And remember: Spring Boot was invented to simplify cluster deployments!
That is, why this feature is now turned of by default and has to be turned on by the user explicitly, if needed.
Simply use :
echo "password" | sudo -S mount -t vfat /dev/sda1 /media/usb/;
if [ $? -eq 0 ]; then
echo -e '[ ok ] Usb key mounted'
else
echo -e '[warn] The USB key is not mounted'
fi
This code is working for me, and its in /etc/init.d/myscriptbash.sh
it's late for this answer but i think maybe still can help, i try the both methods above, using two where conditions and the method with the array, none of those work for me i did several test and the condition was never getting executed, so i did a workaround, here is my code:
public function validateLogin($email, $password){
$password = md5($password);
$this->db->select("userID,email,password");
$query = $this->db->get_where("users", array("email" => $email));
$p = $query->row_array();
if($query->num_rows() == 1 && $password == $p['password']){
return $query->row();
}
}
import os
import fnmatch
def recursive_glob(treeroot, pattern):
results = []
for base, dirs, files in os.walk(treeroot):
goodfiles = fnmatch.filter(files, pattern)
results.extend(os.path.join(base, f) for f in goodfiles)
return results
fnmatch
gives you exactly the same patterns as glob
, so this is really an excellent replacement for glob.glob
with very close semantics. An iterative version (e.g. a generator), IOW a replacement for glob.iglob
, is a trivial adaptation (just yield
the intermediate results as you go, instead of extend
ing a single results list to return at the end).
First find the condition that occurs in all situations, then filter the special conditions:
$('[myc="blue"]')
.filter('[myid="1"],[myid="3"]');
Surrounding the path and the argument with spaces inside quotes as in your example should do. The command may need to handle the quotes when the parameters are passed to it, but it usually is not a big deal.
To escape backslashes that cause problems for JSON data I use this function.
//escape backslash to avoid errors
var escapeJSON = function(str) {
return str.replace(/\\/g,'\\');
};
The bash script runs in a separate subshell. In order to make this work you will need to source this other script as well.
If loading via pip install mysql-connector
and leads an error Unable to find Protobuf include directory
then this would be useful pip install mysql-connector==2.1.4
mysql-connector
is obsolete, so use pip install mysql-connector-python
. Same here
Simply run:
npm uninstall bcrypt
Followed by:
npm install bcrypt
(or npm install
, if bcrypt is declared as dependency in your package.json file)
Kotlin Extension
fun Int.toMonthName(): String {
return DateFormatSymbols().months[this]
}
Usage
calendar.get(Calendar.MONTH).toMonthName()
Create a lookup table that computes font-size based on the length of the string inside your <div>
.
const fontSizeLookupTable = () => {
// lookup table looks like: [ '72px', ..., '32px', ..., '16px', ..., ]
let a = [];
// adjust this based on how many characters you expect in your <div>
a.length = 32;
// adjust the following ranges empirically
a.fill( '72px' , );
a.fill( '32px' , 4 , );
a.fill( '16px' , 8 , );
// add more ranges as necessary
return a;
}
const computeFontSize = stringLength => {
const table = fontSizeLookupTable();
return stringLength < table.length ? table[stringLength] : '16px';
}
Adjust and tune all parameters by empirical test.
You can also just grab the WebViewClient
wvClient = new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("youtube:")) {
String youtubeUrl = "http://www.youtube.com/watch?v="
+ url.Replace("youtube:", "");
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(youtubeUrl)));
}
return false;
}
Worked fine in my app.
try
$(document).ready(function () {
//$('#dialog').dialog();
$('#dialog_link').click(function () {
$('#dialog').dialog('open');
return false;
});
});
there is a open arg in the last part
Try https://github.com/tmpvar/jsdom - you give it some HTML and it gives you a DOM.
If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)
<select chosen="{width: '100%'}" ng-
model="modelName" class="form-control input-
sm"
ng-
options="persons.persons as
persons.persons for persons in
jsonData"
ng-
change="anyFunction(anyParam)"
required>
<option value=""> </option>
</select>
<style>
.chosen-container .chosen-drop {
border-bottom: 0;
border-top: 1px solid #aaa;
top: auto;
bottom: 40px;
}
.chosen-container.chosen-with-drop .chosen-single {
border-top-left-radius: 0px;
border-top-right-radius: 0px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
background-image: none;
}
.chosen-container.chosen-with-drop .chosen-drop {
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
box-shadow: none;
margin-bottom: -16px;
}
</style>
Yes. It is also true for for
scope. But not functions of course.
In your example: if the condition in the if
statement is false, x
will not be defined though.
This actually worked for me
Spinner spinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
spinner = (Spinner) findViewById( R.id.spinner );
spinner.setAdapter(spinnerArrayAdapter);
You're not saying how exactly putdata()
is not behaving. I'm assuming you're doing
>>> pic.putdata(a)
Traceback (most recent call last):
File "...blablabla.../PIL/Image.py", line 1185, in putdata
self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple
This is because putdata
expects a sequence of tuples and you're giving it a numpy array. This
>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)
will work but it is very slow.
As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply
>>> pix = numpy.array(pic)
although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).
Then, after you make your changes to the array, you should be able to do either pic.putdata(pix)
or create a new image with Image.fromarray(pix)
.
First add #include <cmath>
then
you can use pow
methode in your code for example :
pow(3.5, 3);
Which 3.5 is base and 3 is exp
#define IsIOS8 (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
Use insert
:
In [1]: ls = [1,2,3]
In [2]: ls.insert(0, "new")
In [3]: ls
Out[3]: ['new', 1, 2, 3]
start "" "%SystemRoot%\Notepad.exe"
Keep the ""
in between start and your application path.
Added explanation:
Normally when we launch a program from a batch file like below, we'll have the black windows at the background like OP said.
%SystemRoot%\Notepad.exe
This was cause by Notepad running in same command prompt (process). The command prompt will close AFTER notepad is closed. To avoid that, we can use the start
command to start a separate process like this.
start %SystemRoot%\Notepad.exe
This command is fine as long it doesn't has space in the path. To handle space in the path for just in case, we added the "
quotes like this.
start "%SystemRoot%\Notepad.exe"
However running this command would just start another blank command prompt. Why? If you lookup to the start /?
, the start
command will recognize the argument between the "
as the title of the new command prompt it is going to launch. So, to solve that, we have the command like this:
start "" "%SystemRoot%\Notepad.exe"
The first argument of ""
is to set the title (which we set as blank), and the second argument of
"%SystemRoot%\Notepad.exe"
is the target command to run (that support spaces in the path).
If you need to add parameters to the command, just append them quoted, i.e.:
start "" "%SystemRoot%\Notepad.exe" "<filename>"
This will convert "Hello World" to "48656c6c6f20576f726c64" and will store this hex value in str1 and also will convert "48656c6c6f20576f726c64" to "Hello World".
#include <iostream>
#include<sstream>
using namespace std;
int hexCharToInt(char);
string hexToString(string);
int main()
{
std::string str;
std::stringstream str1;
str="Hello World";
for(int i=0;i<str.length();i++){
str1 << std::hex << (int)str.at(i);
}
std::cout << str1.str() <<"\n";
string test = "48656c6c6f20576f726c64";
std::cout << hexToString(test) <<"\n";
return 0;
}
string hexToString(string str){
std::stringstream HexString;
for(int i=0;i<str.length();i++){
char a = str.at(i++);
char b = str.at(i);
int x = hexCharToInt(a);
int y = hexCharToInt(b);
HexString << (char)((16*x)+y);
}
return HexString.str();
}
int hexCharToInt(char a){
if(a>='0' && a<='9')
return(a-48);
else if(a>='A' && a<='Z')
return(a-55);
else
return(a-87);
}
get current activity from parent, then using this code
getActivity().getSupportFragmentManager()
cycles, arrays, regexp... for what? It can be much quicker :)
function isVowel(char)
{
return char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u' || false;
}
If the types of the parameters are all the same (varchar2
for example), you can have a package like this which will do the following:
CREATE OR REPLACE PACKAGE testuser.test_pkg IS
TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);
END test_pkg;
CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
BEGIN
FOR i IN p_parm.first .. p_parm.last
LOOP
dbms_output.put_line(p_parm(i));
END LOOP;
END;
END test_pkg;
Then, to call it you'd need to set up the array and pass it:
DECLARE
l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
l_array(0) := 'hello';
l_array(1) := 'there';
testuser.test_pkg.your_proc(l_array);
END;
/
This question is old and things have evolved in JavaScript. You can now do this:
const params = {}
document.location.search.substr(1).split('&').forEach(pair => {
[key, value] = pair.split('=')
params[key] = value
})
and you get params.year
that contains 2008
.
You would also get other query params in your params
object.
Edit: a shorter/cleaner way to do this:
const params = new Map(location.search.slice(1).split('&').map(kv => kv.split('=')))
You can then test if the year
param exists with:
params.has('year') // true
Or retrieve it with:
params.get('year') // 2008
You can convert URL params to an Object:
const params = location.search.slice(1).split('&').reduce((acc, s) => {
const [k, v] = s.split('=')
return Object.assign(acc, {[k]: v})
}, {})
Then it can be used as a regular JS Object:
params.year // 2008
Non-empty secondary constructor for data class in Kotlin:
data class ChemicalElement(var name: String,
var symbol: String,
var atomicNumber: Int,
var atomicWeight: Double,
var nobleMetal: Boolean?) {
constructor(): this("Silver",
"Ag",
47,
107.8682,
true)
}
fun main() {
var chemicalElement = ChemicalElement()
println("RESULT: ${chemicalElement.symbol} means ${chemicalElement.name}")
println(chemicalElement)
}
// RESULT: Ag means Silver
// ChemicalElement(name=Silver, symbol=Ag, atomicNumber=47, atomicWeight=107.8682, nobleMetal=true)
Empty secondary constructor for data class in Kotlin:
data class ChemicalElement(var name: String,
var symbol: String,
var atomicNumber: Int,
var atomicWeight: Double,
var nobleMetal: Boolean?) {
constructor(): this("",
"",
-1,
0.0,
null)
}
fun main() {
var chemicalElement = ChemicalElement()
println(chemicalElement)
}
// ChemicalElement(name=, symbol=, atomicNumber=-1, atomicWeight=0.0, nobleMetal=null)
You could just create a new database and then go to tasks, import data, and import all the data from the database you want to duplicate to the database you just created.
Great reference. Thanks! An addition to it:
If you happen to have a library project included which has declared custom attributes for a custom view, you have to declare your project namespace, not the library one's. Eg:
Given that the library has the package "com.example.library.customview" and the working project has the package "com.example.customview", then:
Will not work (shows the error " error: No resource identifier found for attribute 'newAttr' in package 'com.example.library.customview'" ):
<com.library.CustomView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.example.library.customview"
android:id="@+id/myView"
app:newAttr="value" />
Will work:
<com.library.CustomView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.example.customview"
android:id="@+id/myView"
app:newAttr="value" />
A nice solution that I've found is to do on UI something like:
<div *ngIf="vendorServicePricing && quantityPricing && service">
...Your page...
</div
Only when: vendorServicePricing
, quantityPricing
and service
are loaded the page is rendered.
var inputs = $('input, select, textarea').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
When you pass a lambda
to sort
, you need to return an integer, not a boolean. So your code should instead read as follows:
xs.sort(lambda x,y: cmp(len(x), len(y)))
Note that cmp is a builtin function such that cmp(x, y)
returns -1 if x
is less than y
, 0 if x
is equal to y
, and 1 if x
is greater than y
.
Of course, you can instead use the key
parameter:
xs.sort(key=lambda s: len(s))
This tells the sort
method to order based on whatever the key function returns.
EDIT: Thanks to balpha and Ruslan below for pointing out that you can just pass len
directly as the key parameter to the function, thus eliminating the need for a lambda
:
xs.sort(key=len)
And as Ruslan points out below, you can also use the built-in sorted function rather than the list.sort
method, which creates a new list rather than sorting the existing one in-place:
print(sorted(xs, key=len))
Another approach is to use ngModelChange
:
Template:
<input type="checkbox" ngModel (ngModelChange)="onChecked(obj, $event)" />
Controller:
onChecked(obj: any, isChecked: boolean){
console.log(obj, isChecked); // {}, true || false
}
I prefer this method because here you get the relevant object and true
/false
values of a checkbox.
Have you tried:
$OutputVariable = (Shell command) | Out-String
To solve this problem on Linux, you need to recompile your PHP with the --enable-mbstring
flag.
The question is what's the difference between
char *name
which points to a constant string literal, and
const char *cname
I.e. given
char *name = "foo";
and
const char *cname = "foo";
There is not much difference between the 2 and both can be seen as correct. Due to the long legacy of C code, the string literals have had a type of char[]
, not const char[]
, and there are lots of older code that likewise accept char *
instead of const char *
, even when they do not modify the arguments.
The principal difference of the 2 in general is that *cname
or cname[n]
will evaluate to lvalues of type const char
, whereas *name
or name[n]
will evaluate to lvalues of type char
, which are modifiable lvalues. A conforming compiler is required to produce a diagnostics message if target of the assignment is not a modifiable lvalue; it need not produce any warning on assignment to lvalues of type char
:
name[0] = 'x'; // no diagnostics *needed*
cname[0] = 'x'; // a conforming compiler *must* produce a diagnostic message
The compiler is not required to stop the compilation in either case; it is enough that it produces a warning for the assignment to cname[0]
. The resulting program is not a correct program. The behaviour of the construct is undefined. It may crash, or even worse, it might not crash, and might change the string literal in memory.
Had the same issue that the client_max_body_size
directive was ignored.
My silly error was, that I put a file inside /etc/nginx/conf.d
which did not end with .conf
. Nginx will not load these by default.
Below funtions worked well for me across devices.
It is taken from https://gist.github.com/laaptu/7867851
public static float convertPixelsToDp(float px){
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return Math.round(dp);
}
public static float convertDpToPixel(float dp){
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return Math.round(px);
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_margin="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<SeekBar
android:id="@+id/seekBar"
android:max="100"
android:progress="50"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Notes
max
is the highest value that the seek bar can go to. The default is 100
. The minimum is 0
. The xml min
value is only available from API 26, but you can just programmatically convert the 0-100
range to whatever you need for earlier versions.progress
is the initial position of the slider dot (called a "thumb").android:rotation="270"
.public class MainActivity extends AppCompatActivity {
TextView tvProgressLabel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set a change listener on the SeekBar
SeekBar seekBar = findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(seekBarChangeListener);
int progress = seekBar.getProgress();
tvProgressLabel = findViewById(R.id.textView);
tvProgressLabel.setText("Progress: " + progress);
}
SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// updated continuously as the user slides the thumb
tvProgressLabel.setText("Progress: " + progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// called when the user first touches the SeekBar
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// called after the user finishes moving the SeekBar
}
};
}
Notes
onStopTrackingTouch
.The following code works fine with me:
brew install zbar
pip install pyqrcode
pip install pyzbar
For QR code image creation:
import pyqrcode
qr = pyqrcode.create("test1")
qr.png("test1.png", scale=6)
For QR code decoding:
from PIL import Image
from pyzbar.pyzbar import decode
data = decode(Image.open('test1.png'))
print(data)
that prints the result:
[Decoded(data=b'test1', type='QRCODE', rect=Rect(left=24, top=24, width=126, height=126), polygon=[Point(x=24, y=24), Point(x=24, y=150), Point(x=150, y=150), Point(x=150, y=24)])]
In addition to BoshWash's answer, here is the picture generated by his code:
"hello _there_".replace(/_(.*?)_/, function(a, b){
return '<div>' + b + '</div>';
})
Oh, or you could also:
"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")
EDIT by Liran H:
For six other people including myself, $1
did not work, whereas \1
did.
When I tried to install a new ionic app, I got the same error as follows, I tried many sources and found the mistake made in User Environment and System Environment unnecessarily included the PROXY value. I removed the ```user variables http://host:port PROXY
system Variables http_proxy http://username:password@host:port ```` and now it is working fine without trouble.
[ERROR] Network connectivity error occurred, are you offline?
If you are behind a firewall and need to configure proxy settings, see: https://ion.link/cli-proxy-docs
Error: getaddrinfo ENOTFOUND host host:80
This the basic usage of allocate/DE-allocate pattern in c++
malloc
/free
, new
/delete
, new[]
/delete[]
We need to use them correspondingly. But I would like to add this particular understanding for the difference between delete
and delete[]
1) delete
is used to de-allocate memory allocated for single object
2) delete[]
is used to de-allocate memory allocated for array of objects
class ABC{}
ABC *ptr = new ABC[100]
when we say new ABC[100]
, compiler can get the information about how many objects that needs to be allocated(here it is 100) and will call the constructor for each of the objects created
but correspondingly if we simply use delete ptr
for this case, compiler will not know how many objects that ptr
is pointing to and will end up calling of destructor and deleting memory for only 1 object(leaving the invocation of destructors and deallocation of remaining 99 objects). Hence there will be a memory leak.
so we need to use delete [] ptr
in this case.
<%: DateTime.Today.ToShortDateString() %>
If you are using windows, then take a look at this link. Otherwise, you may look for your OS specific version api. I don't think C++ comes with a cross-platform way to do it. At the end, it's NOT C++'s work, it's the OS's work.
You can do it the DOM way as well:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}
I just wanted to provide the most comprehensible solution, the anti code-golf version.
from itertools import combinations
l = ["x", "y", "z", ]
def powerset(items):
combo = []
for r in range(len(items) + 1):
#use a list to coerce a actual list from the combinations generator
combo.append(list(combinations(items,r)))
return combo
l_powerset = powerset(l)
for i, item in enumerate(l_powerset):
print "All sets of length ", i
print item
The results
All sets of length 0
[()]
All sets of length 1
[('x',), ('y',), ('z',)]
All sets of length 2
[('x', 'y'), ('x', 'z'), ('y', 'z')]
All sets of length 3
[('x', 'y', 'z')]
For more see the itertools docs, also the wikipedia entry on power sets
You just have to go to your Module settings > Project
and specify a "Project compiler output" and make your modules inherit from project. (For that go to Modules > Paths > Inherit project
.
This did the trick for me.
If you don't mind using a third-party library, with cyclops-react you can mix sequential and parallel Streams within the same pipeline and provide custom ForkJoinPools. For example
ReactiveSeq.range(1, 1_000_000)
.foldParallel(new ForkJoinPool(10),
s->s.filter(i->true)
.peek(i->System.out.println("Thread " + Thread.currentThread().getId()))
.max(Comparator.naturalOrder()));
Or if we wished to continue processing within a sequential Stream
ReactiveSeq.range(1, 1_000_000)
.parallel(new ForkJoinPool(10),
s->s.filter(i->true)
.peek(i->System.out.println("Thread " + Thread.currentThread().getId())))
.map(this::processSequentially)
.forEach(System.out::println);
[Disclosure I am the lead developer of cyclops-react]
Instead of using group concat()
you can use just concat()
Select concat(Col1, ',', Col2) as Foo_Bar from Table1;
edit this only works in mySQL; Oracle concat only accepts two arguments. In oracle you can use something like select col1||','||col2||','||col3 as foobar from table1; in sql server you would use + instead of pipes.
It should be,
*/15 * * * * your_command_or_whatever
The following function worked best for my case:
public static cut(value: string, cutStart: number, cutEnd: number): string {
return value.substring(0, cutStart) + value.substring(cutEnd + 1, value.length);
}
What does truncate mean?
You have full control over the formatting by using the strftime() method and using an appropriate format string.
http://docs.python.org/library/datetime.html#strftime-strptime-behavior
If you can NOT find the .m3u8
file you will need to do a couple of steps different.
1) Go to the network tab and sort by Media
2) You will see something here and select the first item. In my example, it's an mpd
file. then copy the Request URL.
3) Next, download the file using your favorite command line tool using the URL from step 2.
youtube-dl -f bestvideo+bestaudio https://url.com/destination/stream.mpd
4) Depending on the encoding you might have to join the audio and video files together but this will depend on a video by video case.
Janky at best
<a href="file://///server/folders/x/x/filename.ext">right click </a></td>
and then right click, select "copy location" option, and then paste into url.
You need to set basicHttpBinding -> MaxReceivedMessageSize in the client configuration.
Constructors are not inherited, you must create a new, identically prototyped constructor in the subclass that maps to its matching constructor in the superclass.
Here is an example of how this works:
class Foo {
Foo(String str) { }
}
class Bar extends Foo {
Bar(String str) {
// Here I am explicitly calling the superclass
// constructor - since constructors are not inherited
// you must chain them like this.
super(str);
}
}
Keep in mind that sockets does not necessarily mean IP (and TCP or UDP). You can also use UNIX sockets (PF_UNIX), which offer a noticeable performance improvement over connecting to 127.0.0.1
From Oracle (but works in most SQL DBs):
SELECT LASTNAME, COUNT(*)
FROM STUDENTS
GROUP BY LASTNAME
HAVING COUNT(*) >= 3
P.S. it's faster one, because you have no Select withing Select methods here
Use:
db.emails.count({sent_at: null})
Which counts all emails whose sent_at property is null or is not set. The above query is same as below.
db.emails.count($or: [
{sent_at: {$exists: false}},
{sent_at: null}
])
Better to return HttpResponseMessage with StreamContent inside of it.
Here is example:
public HttpResponseMessage GetFile(string id)
{
if (String.IsNullOrEmpty(id))
return Request.CreateResponse(HttpStatusCode.BadRequest);
string fileName;
string localFilePath;
int fileSize;
localFilePath = getFileFromID(id, out fileName, out fileSize);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).
If you are still inside the vi editor, you might be in a different mode from the one you want. Hit ESC a couple of times (until it rings or flashes) and then "i" to enter INSERT mode or "a" to enter APPEND mode (they are the same, just start before or after current character).
If you are back at the command prompt, make sure you can locate the file, then navigate to that directory and perform the mentioned "vi helloWorld.txt". Once you are in the editor, you'll need to check the vi reference to know how to perform the editions you want (you may want to google "vi reference" or "vi cheat sheet").
Once the edition is done, hit ESC again, then type :wq
to save your work or :q!
to quit without saving.
For quick reference, here you have a text-based cheat sheet.
A simpler way of doing it is:
var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());
I had the same issue when I used a DockerFile. My Docker is based on the php:5.5-apache image.
I got that error when executing the command "RUN docker-php-ext-install soap"
I have solved it by adding the following command to my DockerFile
"RUN apt-get update && apt-get install -y libxml2-dev"
select field1, field2, 'example' as TempField
from table1
This should work across different SQL implementations.
What you saw in Firefox was not the actual request; note that the HTTP method is OPTIONS, not POST. It was actually the 'pre-flight' request that the browser makes to determine whether a cross-domain AJAX request should be allowed:
The Access-Control-Request-Headers header in the pre-flight request includes the list of headers in the actual request. The server is then expected to report back whether these headers are supported in this context or not, before the browser submits the actual request.
Aren't you performing the operations in the wrong order? You requirement seems to be foo[:-3].replace(" ", "").upper()
As I found this question is old and have many answers but I have an answer which is simple and working great..
#define EPSILON 0.0000001 // least minimum value for comparison
double SquareRoot(double _val) {
double low = 0;
double high = _val;
double mid = 0;
while (high - low > EPSILON) {
mid = low + (high - low) / 2; // finding mid value
if (mid*mid > _val) {
high = mid;
} else {
low = mid;
}
}
return mid;
}
I hope it will be helpful for future users.
I am sure there is a smarter way for doing what you want but this should work:
- name : Test var
hosts : all
gather_facts : no
vars:
myvariable : false
tasks:
- name: param1
set_fact:
myvariable: "{{param1}}"
when: param1 is defined
- name: param2
set_fact:
myvariable: "{{ param2 if not myvariable else myvariable + ',' + param2 }}"
when: param2 is defined
- name: param3
set_fact:
myvariable: "{{ param3 if not myvariable else myvariable + ',' + param3 }}"
when: param3 is defined
- name: default
set_fact:
myvariable: "default"
when: not myvariable
- debug:
var=myvariable
Hope that helps. I am not sure if you can construct variables dynamically and do this in an iterator. But you could also write a small python code or any other language and plug it into ansible
just :
mydict = {'A':4,'B':10,'C':0,'D':87}
max(mydict.items(), key=lambda x: x[1])