A2 Hosting permits node.js on their shared hosting accounts. I can vouch that I've had a positive experience with them.
Here are instructions in their KnowledgeBase for installing node.js using Apache/LiteSpeed as a reverse proxy: https://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-managed-hosting-accounts . It takes about 30 minutes to set up the configuration, and it'll work with npm, Express, MySQL, etc.
See a2hosting.com.
It's probably best/easiest to set up a 301 redirect. No DNS hacking required.
After installing antivirus I faced this issue and I noticed that my firewall automatically set as on, Now I just set firewall off and it solved my issue. Hope it will help someone :)
The recent openssh version deprecated DSA keys by default. You should suggest to your GIT provider to add some reasonable host key. Relying only on DSA is not a good idea.
As a workaround, you need to tell your ssh
client that you want to accept DSA host keys, as described in the official documentation for legacy usage. You have few possibilities, but I recommend to add these lines into your ~/.ssh/config
file:
Host your-remote-host
HostkeyAlgorithms +ssh-dss
Other possibility is to use environment variable GIT_SSH
to specify these options:
GIT_SSH_COMMAND="ssh -oHostKeyAlgorithms=+ssh-dss" git clone ssh://user@host/path-to-repository
try
$this->load->view('home/home_view',$data);
(and note the " ' " not the " ‘ " that you used)
All of your Laravel files should be in one location. Laravel is exposing its public folder to server. That folder represents some kind of front-controller to whole application. Depending on you server configuration, you have to point your server path to that folder. As I can see there is www site on your picture. www is default root directory on Unix/Linux machines. It is best to take a look inside you server configuration and search for root directory location. As you can see, Laravel has already file called .htaccess, with some ready Apache configuration.
I faced the same error posted by OP while trying to debug my ASP.NET website using IIS Express server. IIS Express is used by Visual Studio to run the website when we press F5.
Open solution explorer in Visual Studio -> Expand the web application project node (StudentInfo
in my case) -> Right click on the web page which you want to get loaded when your website starts(StudentPortal.aspx
in my case) -> Select Set as Start Page
option from the context menu as shown below. It started to work from the next run.
Root cause: I concluded that the start page which is the default document for the website wasn't set correctly or had got messed up somehow during development.
Handy one-liners
for D in *; do echo "$D"; done
for D in *; do find "$D" -type d; done ### Option A
find * -type d ### Option B
Option A is correct for folders with spaces in between. Also, generally faster since it doesn't print each word in a folder name as a separate entity.
# Option A
$ time for D in ./big_dir/*; do find "$D" -type d > /dev/null; done
real 0m0.327s
user 0m0.084s
sys 0m0.236s
# Option B
$ time for D in `find ./big_dir/* -type d`; do echo "$D" > /dev/null; done
real 0m0.787s
user 0m0.484s
sys 0m0.308s
The simplest (but possibly inaccurate) method is to use tk::PlaceWindow, which takes the pathname of a toplevel window as an argument. The main window's pathname is .
import tkinter
root = tkinter.Tk()
root.eval('tk::PlaceWindow . center')
second_win = tkinter.Toplevel(root)
root.eval(f'tk::PlaceWindow {str(second_win)} center')
root.mainloop()
The problem
Simple solutions ignore the outermost frame with the title bar and the menu bar, which leads to a slight offset from being truly centered.
The solution
import tkinter # Python 3
def center(win):
"""
centers a tkinter window
:param win: the main window or Toplevel window to center
"""
win.update_idletasks()
width = win.winfo_width()
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
height = win.winfo_height()
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + titlebar_height + frm_width
x = win.winfo_screenwidth() // 2 - win_width // 2
y = win.winfo_screenheight() // 2 - win_height // 2
win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
win.deiconify()
if __name__ == '__main__':
root = tkinter.Tk()
root.attributes('-alpha', 0.0)
menubar = tkinter.Menu(root)
filemenu = tkinter.Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=root.destroy)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
frm = tkinter.Frame(root, bd=4, relief='raised')
frm.pack(fill='x')
lab = tkinter.Label(frm, text='Hello World!', bd=4, relief='sunken')
lab.pack(ipadx=4, padx=4, ipady=4, pady=4, fill='both')
center(root)
root.attributes('-alpha', 1.0)
root.mainloop()
With tkinter you always want to call the update_idletasks()
method
directly before retrieving any geometry, to ensure that the values returned are accurate.
There are four methods that allow us to determine the outer-frame's dimensions.
winfo_rootx()
will give us the window's top left x coordinate, excluding the outer-frame.
winfo_x()
will give us the outer-frame's top left x coordinate.
Their difference is the outer-frame's width.
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = win.winfo_width() + (2*frm_width)
The difference between winfo_rooty()
and winfo_y()
will be our title-bar / menu-bar's height.
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = win.winfo_height() + (titlebar_height + frm_width)
You set the window's dimensions and the location with the geometry method. The first half of the geometry string is the window's width and height excluding the outer-frame,
and the second half is the outer-frame's top left x and y coordinates.
win.geometry(f'{width}x{height}+{x}+{y}')
You see the window move
One way to prevent seeing the window move across the screen is to use
.attributes('-alpha', 0.0)
to make the window fully transparent and then set it to 1.0
after the window has been centered. Using withdraw()
or iconify()
later followed by deiconify()
doesn't seem to work well, for this purpose, on Windows 7. I use deiconify()
as a trick to activate the window.
Making it optional
You might want to consider providing the user with an option to center the window, and not center by default; otherwise, your code can interfere with the window manager's functions. For example, xfwm4 has smart placement, which places windows side by side until the screen is full. It can also be set to center all windows, in which case you won't have the problem of seeing the window move (as addressed above).
Multiple monitors
If the multi-monitor scenario concerns you, then you can either look into the screeninfo project, or look into what you can accomplish with Qt (PySide2) or GTK (PyGObject), and then use one of those toolkits instead of tkinter. Combining GUI toolkits results in an unreasonably large dependency.
There are ports of flex and bison for windows here: http://gnuwin32.sourceforge.net/
flex is the free implementation of lex. bison is the free implementation of yacc.
In some cases one wants to both save and print a base r plot. I spent a bit of time and came up with this utility function:
x = 1:10
basesave = function(expr, filename, print=T) {
#extension
exten = stringr::str_match(filename, "\\.(\\w+)$")[, 2]
switch(exten,
png = {
png(filename)
eval(expr, envir = parent.frame())
dev.off()
},
{stop("filetype not recognized")})
#print?
if (print) eval(expr, envir = parent.frame())
invisible(NULL)
}
#plots, but doesn't save
plot(x)
#saves, but doesn't plot
png("test.png")
plot(x)
dev.off()
#both
basesave(quote(plot(x)), "test.png")
#works with pipe too
quote(plot(x)) %>% basesave("test.png")
Note that one must use quote
, otherwise the plot(x)
call is run in the global environment and NULL
gets passed to basesave()
.
There are couple of ways of including your python script with name abc.py
import abc
from folder import abc
from folder.internal_folder import abc
import os
import sys
scriptpath = "../Test/MyModule.py"
sys.path.append(os.path.abspath(scriptpath))
import MyModule
In case your python script gets updated and you don't want to upload - use these statements for auto refresh. Bonus :)
%load_ext autoreload
%autoreload 2
when you want to get all image from folder then use glob()
built in function which help to get all image . But when you get all then sometime need to check that all is valid so in this case this code help you. this code will also check that it is image
$all_files = glob("mytheme/images/myimages/*.*");
for ($i=0; $i<count($all_files); $i++)
{
$image_name = $all_files[$i];
$supported_format = array('gif','jpg','jpeg','png');
$ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
if (in_array($ext, $supported_format))
{
echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
} else {
continue;
}
}
for more information
Subset is your safest and easiest answer.
subset(dataframe, A==B & E!=0)
Real data example with mtcars
subset(mtcars, cyl==6 & am!=0)
This old chestnut...
In short, you should be using require and letting node handle the parsing as part of the require call, not outsourcing it to a 3rd party module. You should also be taking care that your configs are bulletproof, which means you should check the returned data carefully.
But for brevity's sake, consider the following example:
For Example, let's say I have a config file 'admins.json' in the root of my app containing the following:
admins.json[{
"userName": "tech1337",
"passSalted": "xxxxxxxxxxxx"
}]
Note the quoted keys, "userName"
, "passSalted"
!
I can do the following and get the data out of the file with ease.
let admins = require('~/app/admins.json');
console.log(admins[0].userName);
Now the data is in and can be used as a regular (or array of) object.
Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).
Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?
If you don't like writing custom converter, you could use data triggers to solve this:
<Style.Triggers>
<DataTrigger Binding="{Binding YourBinaryOption}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding YourBinaryOption}" Value="False">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
another alternative to determine orientation, based on comparison of the width/height:
var mql = window.matchMedia("(min-aspect-ratio: 4/3)");
if (mql.matches) {
orientation = 'landscape';
}
You use it on "resize" event:
window.addEventListener("resize", function() { ... });
This because every runtime.exec(..)
returns a Process
class that should be used after the execution instead that invoking other commands by the Runtime
class
If you look at Process doc you will see that you can use
getInputStream()
getOutputStream()
on which you should work by sending the successive commands and retrieving the output..
You can also try: (I tried this and it worked for me)
SELECT ISNULL((SELECT SUM(columnA) FROM my_table WHERE columnB = 1),0)) INTO res;
If you have Ruby(1.9+)
ruby -e 'Dir["*"].each{|x| File.rename(x,"PRE_"+x) }'
I went with a modification of @user1097431 's answer:
function menuPosition(){
// distance from top of footer to top of document
var footertotop = ($('.footer').position().top);
// distance user has scrolled from top, adjusted to take in height of bar (42 pixels inc. padding)
var scrolltop = $(document).scrollTop() + window.innerHeight;
// difference between the two
var difference = scrolltop-footertotop;
// if user has scrolled further than footer,
// pull sidebar up using a negative margin
if (scrolltop > footertotop) {
$('#categories-wrapper').css({
'bottom' : difference
});
}else{
$('#categories-wrapper').css({
'bottom' : 0
});
};
};
The one exception worth noting is that while you can't delete apps, the folks over at Google Play Developer Support are able to on their end if the app is both unpublished and has 0 lifetime installs. So if your app has 0 lifetime installs, you might be in luck.
First you will need unpublish the app and wait 24 hours (to allow global stats to update and ensure that no last-minute installs happened). Assuming no last-minute installs happen over those 24 hours, you can contact Google Play Developer Support and check to see if they can delete it.
Please note that their requirement for 0 installs is a hard requirement. No exceptions can be made (not even if you installed the app yourself for testing purposes).
You could output them to a .csv file and open the file in excel. Is that direct enough?
var str1 = 'abc';
var str2 = str1+' def'; // str2 is now 'abc def'
The reason why you have to modify the AppData could be:
Even after doing that, the latest LTE (4.4.4) still have problem with Windows 10, it worked for a little while then whenever I try to:
$ npm install _some_package_ --global
Node throw the "FATAL ERROR CALL_AND_RETRY_LAST Allocation failed - process out of memory" error. Still try to find a solution to that problem.
The only thing I find works is to run Vagrant or Virtual box, then run the Linux command line (must matching the path) which is quite a messy solution.
You can try https://rubygems.org/gems/dates_from_string:
Find date in structure:
text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)
=> ["2015-02-02 23:00:10"]
If you have a SharedPreferenceActivity by which you have saved your values
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");
if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.
and this is how you can retrieve the values.
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));
Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.
mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
You can try to use CDATA to put all your symbols that don't work.
An example of something that will work in XML:
<![CDATA[
function matchwo(a,b) {
if (a < b && a < 0) {
return 1;
} else {
return 0;
}
}
]]>
And of course you can use <
and >
.
I know that this is a bit of a late response, but I recently had to solve a similar problem and thought that this may be useful to others.
Background
Consider the table below called 'mytable':
The problem was to keep only latest 3 records and delete any older records whose systemid=1 (there could be many other records in the table with other systemid values)
It would be good is you could do this simply using the statement
DELETE FROM mytable WHERE id IN (SELECT id FROM `mytable` WHERE systemid=1 ORDER BY id DESC LIMIT 3)
However this is not yet supported in MySQL and if you try this then you will get an error like
...doesn't yet support 'LIMIT & IN/ALL/SOME subquery'
So a workaround is needed whereby an array of values is passed to the IN selector using variable. However, as variables need to be single values, I would need to simulate an array. The trick is to create the array as a comma separated list of values (string) and assign this to the variable as follows
SET @myvar := (SELECT GROUP_CONCAT(id SEPARATOR ',') AS myval FROM (SELECT * FROM `mytable` WHERE systemid=1 ORDER BY id DESC LIMIT 3 ) A GROUP BY A.systemid);
The result stored in @myvar is
5,6,7
Next, the FIND_IN_SET selector is used to select from the simulated array
SELECT * FROM mytable WHERE FIND_IN_SET(id,@myvar);
The combined final result is as follows:
SET @myvar := (SELECT GROUP_CONCAT(id SEPARATOR ',') AS myval FROM (SELECT * FROM `mytable` WHERE systemid=1 ORDER BY id DESC LIMIT 3 ) A GROUP BY A.systemid);
DELETE FROM mytable WHERE FIND_IN_SET(id,@myvar);
I am aware that this is a very specific case. However it can be modified to suit just about any other case where a variable needs to store an array of values.
I hope that this helps.
This can be done very elegantly with Ray.
To parallelize your example, you'd need to define your functions with the @ray.remote
decorator, and then invoke them with .remote
.
import ray
ray.init()
# Define the functions.
@ray.remote
def solve1(a):
return 1
@ray.remote
def solve2(b):
return 2
# Start two tasks in the background.
x_id = solve1.remote(0)
y_id = solve2.remote(1)
# Block until the tasks are done and get the results.
x, y = ray.get([x_id, y_id])
There are a number of advantages of this over the multiprocessing module.
These function calls can be composed together, e.g.,
@ray.remote
def f(x):
return x + 1
x_id = f.remote(1)
y_id = f.remote(x_id)
z_id = f.remote(y_id)
ray.get(z_id) # returns 4
Note that Ray is a framework I've been helping develop.
If we know there is a limitation on LEN and space, why cant we replace the space first? Then we know there is no space to confuse LEN.
len(replace(@string, ' ', '-')) - len(replace(replace(@string, ' ', '-'), ',', ''))
Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
getParameter(date2));
long diff = d2.getTime() - d1.getTime();
System.out.println("Difference between " + d1 + " and "+ d2+" is "
+ (diff / (1000 * 60 * 60 * 24)) + " days.");
print "%02d"%a
is the python 2 variant
python 3 uses a somewhat more verbose formatting system:
"{0:0=2d}".format(a)
The relevant doc link for python2 is: http://docs.python.org/2/library/string.html#format-specification-mini-language
For python3, it's http://docs.python.org/3/library/string.html#string-formatting
By the way, it's worth noting that some mobile devices, particularly Apple products like iPhone/iPad completely ignore headers like no-cache, no-store, Expires: 0, or whatever else you may try to force them to not re-use expired form pages.
This has caused us no end of headaches as we try to get the issue of a user's iPad say, being left asleep on a page they have reached through a form process, say step 2 of 3, and then the device totally ignores the store/cache directives, and as far as I can tell, simply takes what is a virtual snapshot of the page from its last state, that is, ignoring what it was told explicitly, and, not only that, taking a page that should not be stored, and storing it without actually checking it again, which leads to all kinds of strange Session issues, among other things.
I'm just adding this in case someone comes along and can't figure out why they are getting session errors with particularly iphones and ipads, which seem by far to be the worst offenders in this area.
I've done fairly extensive debugger testing with this issue, and this is my conclusion, the devices ignore these directives completely.
Even in regular use, I've found that some mobiles also totally fail to check for new versions via say, Expires: 0 then checking last modified dates to determine if it should get a new one.
It simply doesn't happen, so what I was forced to do was add query strings to the css/js files I needed to force updates on, which tricks the stupid mobile devices into thinking it's a file it does not have, like: my.css?v=1, then v=2 for a css/js update. This largely works.
User browsers also, by the way, if left to their defaults, as of 2016, as I continuously discover (we do a LOT of changes and updates to our site) also fail to check for last modified dates on such files, but the query string method fixes that issue. This is something I've noticed with clients and office people who tend to use basic normal user defaults on their browsers, and have no awareness of caching issues with css/js etc, almost invariably fail to get the new css/js on change, which means the defaults for their browsers, mostly MSIE / Firefox, are not doing what they are told to do, they ignore changes and ignore last modified dates and do not validate, even with Expires: 0 set explicitly.
This was a good thread with a lot of good technical information, but it's also important to note how bad the support for this stuff is in particularly mobile devices. Every few months I have to add more layers of protection against their failure to follow the header commands they receive, or to properly interpet those commands.
package com.server;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import org.w3c.dom.*;
import com.gwtext.client.data.XmlReader;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class XmlServlet extends HttpServlet
{
NodeList list;
Connection con=null;
Statement st=null;
ResultSet rs = null;
String xmlString ;
BufferedWriter bw;
String displayTo;
String displayFrom;
String addressto;
String addressFrom;
Date send;
String Subject;
String body;
String category;
Document doc1;
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
System.out.print("on server");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
System.out.print("on server");
try
{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
//creating a new instance of a DOM to build a DOM tree.
doc1 = docBuilder.newDocument();
new XmlServlet().createXmlTree(doc1);
System.out.print("on server");
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
public void createXmlTree(Document doc) throws Exception {
//This method creates an element node
System.out.println("ruchipaliwal111");
try
{
System.out.println("ruchi111");
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3308/plz","root","root1");
st = con.createStatement();
rs = st.executeQuery("select * from data");
Element root = doc.createElement("message");
doc.appendChild(root);
while(rs.next())
{
displayTo=rs.getString(1).toString();
System.out.println(displayTo+"getdataname");
displayFrom=rs.getString(2).toString();
System.out.println(displayFrom +"getdataname");
addressto=rs.getString(3).toString();
System.out.println(addressto +"getdataname");
addressFrom=rs.getString(4).toString();
System.out.println(addressFrom +"getdataname");
send=rs.getDate(5);
System.out.println(send +"getdataname");
Subject=rs.getString(6).toString();
System.out.println(Subject +"getdataname");
body=rs.getString(7).toString();
System.out.println(body+"getdataname");
category=rs.getString(8).toString();
System.out.println(category +"getdataname");
//adding a node after the last child node of ssthe specified node.
Element element1 = doc.createElement("Header");
root.appendChild(element1);
Element child1 = doc.createElement("To");
element1.appendChild(child1);
child1.setAttribute("displayNameTo",displayTo);
child1.setAttribute("addressTo",addressto);
Element child2 = doc.createElement("From");
element1.appendChild(child2);
child2.setAttribute("displayNameFrom",displayFrom);
child2.setAttribute("addressFrom",addressFrom);
Element child3 = doc.createElement("Send");
element1.appendChild(child3);
Text text2 = doc.createTextNode(send.toString());
child3.appendChild(text2);
Element child4 = doc.createElement("Subject");
element1.appendChild(child4);
Text text3 = doc.createTextNode(Subject);
child4.appendChild(text3);
Element child5 = doc.createElement("category");
element1.appendChild(child5);
Text text44 = doc.createTextNode(category);
child5.appendChild(text44);
Element element2 = doc.createElement("Body");
root.appendChild(element2);
Text text1 = doc.createTextNode(body);
element2.appendChild(text1);
/*
Element child1 = doc.createElement("name");
root.appendChild(child1);
Text text = doc.createTextNode(getdataname);
child1.appendChild(text);
Element element = doc.createElement("address");
root.appendChild(element);
Text text1 = doc.createTextNode( getdataaddress);
element.appendChild(text1);
*/
}
//TransformerFactory instance is used to create Transformer objects.
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD,"xml");
// transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
// create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
xmlString = sw.toString();
File file = new File("./war/ds/newxml.xml");
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(xmlString);
}
catch(Exception e)
{
System.out.print("after while loop exception"+e.toString());
}
bw.flush();
bw.close();
System.out.println("successfully done.....");
}
}
package will generate Jar/war as per POM file. install will install generated jar file to the local repository for other dependencies if any.
install phase comes after package phase
DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/Contents/"));
//Using Union
FileInfo[] files = directory.GetFiles("*.xlsx")
.Union(directory
.GetFiles("*.csv"))
.ToArray();
echo "Enter Drive letter"
set /p driveletter=
attrib -s -h -a /s /d %driveletter%:\*.*
As i have came here looking for an Android-Java-Answer i am going to do a short summary:
If you want to use java.net.URLConnection with Basic Authentication in Android try this code:
URL url = new URL("http://www.mywebsite.com/resource");
URLConnection urlConnection = url.openConnection();
String header = "Basic " + new String(android.util.Base64.encode("user:pass".getBytes(), android.util.Base64.NO_WRAP));
urlConnection.addRequestProperty("Authorization", header);
// go on setting more request headers, reading the response, etc
multipart/form-data
encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded
encoding. When using a different encoding, the request.getParameter()
calls will all return null
. When you're already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use HttpServletRequest#getParts()
instead. Also see this blog for extended examples.
Prior to Servlet 3.0, a de facto standard to parse multipart/form-data
requests would be using Apache Commons FileUpload. Just carefully read its User Guide and Frequently Asked Questions sections to learn how to use it. I've posted an answer with a code example before here (it also contains an example targeting Servlet 3.0).
Just like normal background-color: #f0f
You just need a way to target it, eg: <option id="myPinkOption">blah</option>
default.aspx code
<asp:FileUpload runat="server" id="fileUpload1" Multiple="Multiple">
</asp:FileUpload>
<asp:Button runat="server" Text="Upload Files" id="uploadBtn"/>
default.aspx.vb
Protected Sub uploadBtn_Click(sender As Object, e As System.EventArgs) Handles uploadBtn.Click
Dim ImageFiles As HttpFileCollection = Request.Files
For i As Integer = 0 To ImageFiles.Count - 1
Dim file As HttpPostedFile = ImageFiles(i)
file.SaveAs(Server.MapPath("Uploads/") & file.FileName)
Next
End Sub
How to use a clock and do assertions
This example shows how to generate a clock, and give inputs and assert outputs for every cycle. A simple counter is tested here.
The key idea is that the process
blocks run in parallel, so the clock is generated in parallel with the inputs and assertions.
library ieee;
use ieee.std_logic_1164.all;
entity counter_tb is
end counter_tb;
architecture behav of counter_tb is
constant width : natural := 2;
constant clk_period : time := 1 ns;
signal clk : std_logic := '0';
signal data : std_logic_vector(width-1 downto 0);
signal count : std_logic_vector(width-1 downto 0);
type io_t is record
load : std_logic;
data : std_logic_vector(width-1 downto 0);
count : std_logic_vector(width-1 downto 0);
end record;
type ios_t is array (natural range <>) of io_t;
constant ios : ios_t := (
('1', "00", "00"),
('0', "UU", "01"),
('0', "UU", "10"),
('0', "UU", "11"),
('1', "10", "10"),
('0', "UU", "11"),
('0', "UU", "00"),
('0', "UU", "01")
);
begin
counter_0: entity work.counter port map (clk, load, data, count);
process
begin
for i in ios'range loop
load <= ios(i).load;
data <= ios(i).data;
wait until falling_edge(clk);
assert count = ios(i).count;
end loop;
wait;
end process;
process
begin
for i in 1 to 2 * ios'length loop
wait for clk_period / 2;
clk <= not clk;
end loop;
wait;
end process;
end behav;
The counter would look like this:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all; -- unsigned
entity counter is
generic (
width : in natural := 2
);
port (
clk, load : in std_logic;
data : in std_logic_vector(width-1 downto 0);
count : out std_logic_vector(width-1 downto 0)
);
end entity counter;
architecture rtl of counter is
signal cnt : unsigned(width-1 downto 0);
begin
process(clk) is
begin
if rising_edge(clk) then
if load = '1' then
cnt <= unsigned(data);
else
cnt <= cnt + 1;
end if;
end if;
end process;
count <= std_logic_vector(cnt);
end architecture rtl;
Related: https://electronics.stackexchange.com/questions/148320/proper-clock-generation-for-vhdl-testbenches
Idk if you guys solved it but I recommend another way to do it, and it works :)
ServiceUtil = ig.Class.extend({
base_url : 'someurl',
sendRequest: function(request)
{
var url = this.base_url + request;
var requestVar = new XMLHttpRequest();
dataGet = false;
$.ajax({
url: url,
async: false,
type: "get",
success: function(data){
ServiceUtil.objDataReturned = data;
}
});
return ServiceUtil.objDataReturned;
}
})
So the main idea here is that, by adding async: false, then you make everything waits until the data is retrieved. Then you assign it to a static variable of the class, and everything magically works :)
update the server arguments from -Dhttps.protocols=SSLv3 to -Dhttps.protocols=TLSv1,SSLv3
On CentOS 6.5 with python 2.7 I needed to do: yum install python27-tkinter
In Jelly.core to test a literal string one would use:
<core:when test="${ name == 'ABC' }">
But if I have to check for string "Toy's R Us":
<core:when test="${ name == &quot;Toy's R Us&quot; }">
It would be like this, if the double quotes were allowed inside:
<core:when test="${ name == "Toy's R Us" }">
Try:
$a1=@(1,2,3,4,5)
$b1=@(1,2,3,4,5,6)
(Compare-Object $a1 $b1).InputObject
Or, you can use:
(Compare-Object $b1 $a1).InputObject
The order doesn't matter.
Looks like you forgot the @ in variable declaration. Also I remember having problems with SET
in MySql a long time ago.
Try
DECLARE @FOO varchar(7);
DECLARE @oldFOO varchar(7);
SELECT @FOO = '138';
SELECT @oldFOO = CONCAT('0', @FOO);
update mypermits
set person = @FOO
where person = @oldFOO;
Reset the index and the head to origin/master
, but do not reset the working tree:
git reset origin/master
I recommend the Boost.Random library, it's super detailed and well-documented, lets you explicitly specify what distribution you want, and in non-cryptographic scenarios can actually outperform a typical C library rand implementation.
If you think about it, a body XRay scan (at the medical center) too needs this kind of measurement for estimating size of tumors. So they place a 1 Dollar Coin on the body, to do a comparative measurement.
Even newspaper is printed with some marks on the corners.
You need a reference to measure. May be you can get your person to wear a cap which has a few bright green circles. Once you recognize the size of the circle you can comparatively measure the remaining.
Or you can create a transparent 1 inch circle which will superimpose on the face, move the camera toward/away the face, aim your superimposed circle on that bright green circle on the cap. Then on your photo will be as per scale.
You don't need jQuery for that, you can do it with normal javascript:
http://www.w3schools.com/jsref/jsref_split.asp
var str = "a,b,c,d";
var res = str.split(","); // this returns an array
toString
is a method, so you should add parenthesis ()
to make the function call.
> a = [1,2,3]
[ 1, 2, 3 ]
> a.toString()
'1,2,3'
Besides, if you want to use strings as keys, then you should consider using a Object
instead of Array
, and use JSON.stringify
to return a string.
> var aa = {}
> aa['a'] = 'aaa'
> JSON.stringify(aa)
'{"a":"aaa","b":"bbb"}'
Try this...
function urlChange(url) {
var site = url+'?toolbar=0&navpanes=0&scrollbar=0';
document.getElementById('iFrameName').src = site;
}
<a href="javascript:void(0);" onClick="urlChange('www.mypdf.com/test.pdf')">TEST </a>
The Memory Management Programming Guide from the iOS Reference Library has basics of assign, copy, and retain with analogies and examples.
copy Makes a copy of an object, and returns it with retain count of 1. If you copy an object, you own the copy. This applies to any method that contains the word copy where “copy” refers to the object being returned.
retain Increases the retain count of an object by 1. Takes ownership of an object.
release Decreases the retain count of an object by 1. Relinquishes ownership of an object.
I ran into this myself. My recommendation: If you have ownership of the datasource, don't use a List. Use a BindingList. The BindingList has events that fire when items are added or changed, and the DataGridView will automatically update itself when these events are fired.
You might be better off using os.walk()
for this.
os.listdir()
doesn't distinguish files from directories and you will quickly get into trouble trying to unlink these. There is a good example of using os.walk()
to recursively remove a directory here, and hints on how to adapt it to your circumstances.
"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"
It might be better to remove related files by using bash to read commands, like the following:
sudo python setup.py install --record files.txt
sudo bash -c "cat files.txt | xargs rm -rf"
Two things to keep in mind Content-Type and the Encoding
1) What if the file is css
if (/.(css)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data, 'utf8');
}
2) What if the file is jpg/png
if (/.(jpg)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'image/jpg'});
res.end(data,'Base64');
}
Above one is just a sample code to explain the answer and not the exact code pattern.
As @snapshoe says
flush()
sends your SQL statements to the database
commit()
commits the transaction.
When session.autocommit == False
:
commit()
will call flush()
if you set autoflush == True
.
When session.autocommit == True
:
You can't call commit()
if you haven't started a transaction (which you probably haven't since you would probably only use this mode to avoid manually managing transactions).
In this mode, you must call flush()
to save your ORM changes. The flush effectively also commits your data.
There is a dirty trick, what I have used:
I am using bootstrap, so I just added .disabled
class to the element which I want to disable. Bootstrap handles the rest of the things.
Suggestion are heartily welcome towards this.
Adding class on run time:
$('#element').addClass('disabled');
I think that your model #2 is fine, however you can take a look at the more complex model which stores questions and pre-made answers (offered answers) and allows them to be re-used in different surveys.
- One survey can have many questions; one question can be (re)used in many surveys.
- One (pre-made) answer can be offered for many questions. One question can have many answers offered. A question can have different answers offered in different surveys. An answer can be offered to different questions in different surveys. There is a default "Other" answer, if a person chooses other, her answer is recorded into Answer.OtherText.
- One person can participate in many surveys, one person can answer specific question in a survey only once.
Here are some branch naming conventions that I use and the reasons for them
Branch naming conventions
Group tokens
Use "grouping" tokens in front of your branch names.
group1/foo
group2/foo
group1/bar
group2/bar
group3/bar
group1/baz
The groups can be named whatever you like to match your workflow. I like to use short nouns for mine. Read on for more clarity.
Short well-defined tokens
Choose short tokens so they do not add too much noise to every one of your branch names. I use these:
wip Works in progress; stuff I know won't be finished soon
feat Feature I'm adding or expanding
bug Bug fix or experiment
junk Throwaway branch created to experiment
Each of these tokens can be used to tell you to which part of your workflow each branch belongs.
It sounds like you have multiple branches for different cycles of a change. I do not know what your cycles are, but let's assume they are 'new', 'testing' and 'verified'. You can name your branches with abbreviated versions of these tags, always spelled the same way, to both group them and to remind you which stage you're in.
new/frabnotz
new/foo
new/bar
test/foo
test/frabnotz
ver/foo
You can quickly tell which branches have reached each different stage, and you can group them together easily using Git's pattern matching options.
$ git branch --list "test/*"
test/foo
test/frabnotz
$ git branch --list "*/foo"
new/foo
test/foo
ver/foo
$ gitk --branches="*/foo"
Use slashes to separate parts
You may use most any delimiter you like in branch names, but I find slashes to be the most flexible. You might prefer to use dashes or dots. But slashes let you do some branch renaming when pushing or fetching to/from a remote.
$ git push origin 'refs/heads/feature/*:refs/heads/phord/feat/*'
$ git push origin 'refs/heads/bug/*:refs/heads/review/bugfix/*'
For me, slashes also work better for tab expansion (command completion) in my shell. The way I have it configured I can search for branches with different sub-parts by typing the first characters of the part and pressing the TAB key. Zsh then gives me a list of branches which match the part of the token I have typed. This works for preceding tokens as well as embedded ones.
$ git checkout new<TAB>
Menu: new/frabnotz new/foo new/bar
$ git checkout foo<TAB>
Menu: new/foo test/foo ver/foo
(Zshell is very configurable about command completion and I could also configure it to handle dashes, underscores or dots the same way. But I choose not to.)
It also lets you search for branches in many git commands, like this:
git branch --list "feature/*"
git log --graph --oneline --decorate --branches="feature/*"
gitk --branches="feature/*"
Caveat: As Slipp points out in the comments, slashes can cause problems. Because branches are implemented as paths, you cannot have a branch named "foo" and another branch named "foo/bar". This can be confusing for new users.
Do not use bare numbers
Do not use use bare numbers (or hex numbers) as part of your branch naming scheme. Inside tab-expansion of a reference name, git may decide that a number is part of a sha-1 instead of a branch name. For example, my issue tracker names bugs with decimal numbers. I name my related branches CRnnnnn rather than just nnnnn to avoid confusion.
$ git checkout CR15032<TAB>
Menu: fix/CR15032 test/CR15032
If I tried to expand just 15032, git would be unsure whether I wanted to search SHA-1's or branch names, and my choices would be somewhat limited.
Avoid long descriptive names
Long branch names can be very helpful when you are looking at a list of branches. But it can get in the way when looking at decorated one-line logs as the branch names can eat up most of the single line and abbreviate the visible part of the log.
On the other hand long branch names can be more helpful in "merge commits" if you do not habitually rewrite them by hand. The default merge commit message is Merge branch 'branch-name'
. You may find it more helpful to have merge messages show up as Merge branch 'fix/CR15032/crash-when-unformatted-disk-inserted'
instead of just Merge branch 'fix/CR15032'
.
In jQuery, check whether you have hit the bottom of page using scroll function. Once you hit that, make an ajax call (you can show a loading image here till ajax response) and get the next set of data, append it to the div. This function gets executed as you scroll down the page again.
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
// ajax call get data from server and append to the div
}
});
In Mac IntelliJ IDEA, the command is Cmd + Option + O
For some older versions it is apparently Ctrl + Option + O.
(Letter O not Zero 0) on the latest version 2019.x
CREATE FUNCTION CombineValues
(
@FK_ID INT -- The foreign key from TableA which is used
-- to fetch corresponding records
)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @SomeColumnList VARCHAR(8000);
SELECT @SomeColumnList =
COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20))
FROM TableB C
WHERE C.FK_ID = @FK_ID;
RETURN
(
SELECT @SomeColumnList
)
END
SELECT ID, Name, dbo.CombineValues(FK_ID) FROM TableA
CREATE PROCEDURE GetCombinedValues
@FK_ID int
As
BEGIN
DECLARE @SomeColumnList VARCHAR(800)
SELECT @SomeColumnList =
COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20))
FROM TableB
WHERE FK_ID = @FK_ID
Select *, @SomeColumnList as SelectedIds
FROM
TableA
WHERE
FK_ID = @FK_ID
END
Use the glob function in a foreach loop to do whatever is an option. I also used the file_exists function in the example below to check if the directory exists before going any further.
$directory = 'my_directory/';
$extension = '.txt';
if ( file_exists($directory) ) {
foreach ( glob($directory . '*' . $extension) as $file ) {
echo $file;
}
}
else {
echo 'directory ' . $directory . ' doesn\'t exist!';
}
Change the File Permission using chmod command
sudo chmod 700 keyfile.pem
for github pages I Use
ng build --prod --base-href "https://<username>.github.io/<RepoName>/" --output-path=docs
This is what that copies output into the docs folder : --output-path=docs
Username:
echo %USERNAME%
Domainname:
echo %USERDOMAIN%
You can get a complete list of environment variables by running the command set
from the command prompt.
To format all the code in NetBeans, press Alt + Shift + F. If you want to indent lines, select the lines and press Alt + Shift + right arrow key, and to unindent, press Alt + Shift + left arrow key.
You can do it using FullscreenVideoView
class. Its a small library project. It's video progress dialog is build in. it's gradle is :
compile 'com.github.rtoshiro.fullscreenvideoview:fullscreenvideoview:1.1.0'
your VideoView xml is like this
<com.github.rtoshiro.view.video.FullscreenVideoLayout
android:id="@+id/videoview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In your activity , initialize it using this way:
FullscreenVideoLayout videoLayout;
videoLayout = (FullscreenVideoLayout) findViewById(R.id.videoview);
videoLayout.setActivity(this);
Uri videoUri = Uri.parse("YOUR_VIDEO_URL");
try {
videoLayout.setVideoURI(videoUri);
} catch (IOException e) {
e.printStackTrace();
}
That's it. Happy coding :)
If want to know more then visit here
Edit: gradle path has been updated. compile it now
compile 'com.github.rtoshiro.fullscreenvideoview:fullscreenvideoview:1.1.2'
Scroll down on that page and you'll see:
Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.
That's the SQLEXPRWT_x64_ENU.exe
download.... (WT = with tools)
Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.
That's the SQLEXPRADV_x64_ENU.exe
download ... (ADV = Advanced Services)
The SQLEXPR_x64_ENU.exe
file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.
If you switch from Web to Express you will no longer be able to use the SQL Server Agent service so you need to set up a different scheduler for maintenance and backups.
I like one-line notation for GCD, it's more elegant:
DispatchQueue.main.asyncAfter(deadline: .now() + 42.0) {
// do stuff 42 seconds later
}
Also, in iOS 10 we have new Timer methods, e.g. block initializer:
(so delayed action may be canceled)
let timer = Timer.scheduledTimer(withTimeInterval: 42.0, repeats: false) { (timer) in
// do stuff 42 seconds later
}
Btw, keep in mind: by default, timer is added to the default run loop mode. It means timer may be frozen when the user is interacting with the UI of your app (for example, when scrolling a UIScrollView) You can solve this issue by adding the timer to the specific run loop mode:
RunLoop.current.add(timer, forMode: .common)
At this blog post you can find more details.
In the new Jenkins 2.0 pipeline (previously named the Workflow Plugin), this is done differently for:
Here I am specifically referring to the Multibranch Pipeline version 2.9.
Main repository
This is the repository that contains your Jenkinsfile
.
In the Configure screen for your pipeline project, enter your repository name, etc.
Do not use Additional Behaviors > Check out to a sub-directory. This will put your Jenkinsfile
in the sub-directory where Jenkins cannot find it.
In Jenkinsfile
, check out the main repository in the subdirectory using dir()
:
dir('subDir') {
checkout scm
}
Additional repositories
If you want to check out more repositories, use the Pipeline Syntax generator to automatically generate a Groovy code snippet.
In the Configure screen for your pipeline project:
env.BRANCH_NAME
contains the branch name of the main repository.Jenkinsfile
.I would mention one more thing that concerns Primefaces's p:commandButton
!
When you use a p:commandButton
for the action that needs to be done on the server, you can not use type="button"
because that is for Push buttons which are used to execute custom javascript without causing an ajax/non-ajax request to the server.
For this purpose, you can dispense the type
attribute (default value is "submit"
) or you can explicitly use type="submit"
.
Hope this will help someone!
If for some reason you don't want to use the plugin, then here's the script you can use to copy the resources to your android studio project:
echo "..:: Copying resources ::.."
echo "Enter folder:"
read srcFolder
echo "Enter filename with extension:"
read srcFile
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-xxxhdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-xxxhdpi/"$srcFile"/
echo "xxxhdpi copied"
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-xxhdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-xxhdpi/"$srcFile"/
echo "xxhdpi copied"
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-xhdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-xhdpi/"$srcFile"/
echo "xhdpi copied"
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-hdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-hdpi/"$srcFile"/
echo "hdpi copied"
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-mdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-mdpi/"$srcFile"/
echo "mdpi copied"
Thanks for the original answer here. With python 3 the following line of code:
print(json.dumps(result_dict,ensure_ascii=False))
was ok. Consider trying not writing too much text in the code if it's not imperative.
This might be good enough for the python console. However, to satisfy a server you might need to set the locale as explained here (if it is on apache2) http://blog.dscpl.com.au/2014/09/setting-lang-and-lcall-when-using.html
basically install he_IL or whatever language locale on ubuntu check it is not installed
locale -a
install it where XX is your language
sudo apt-get install language-pack-XX
For example:
sudo apt-get install language-pack-he
add the following text to /etc/apache2/envvrs
export LANG='he_IL.UTF-8'
export LC_ALL='he_IL.UTF-8'
Than you would hopefully not get python errors on from apache like:
print (js) UnicodeEncodeError: 'ascii' codec can't encode characters in position 41-45: ordinal not in range(128)
Also in apache try to make utf the default encoding as explained here:
How to change the default encoding to UTF-8 for Apache?
Do it early because apache errors can be pain to debug and you can mistakenly think it's from python which possibly isn't the case in that situation
Currently, the link dlptest is working fine.
The files will only be stored for 30 minutes before being deleted.
Can't think of a only css solution, but couldn't you just had a div between those 2 and set in the css the properties to look like a line like shown in the image? If you are using divs as they were table cells this is a pretty simple solution to the problem
Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.
Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.
You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.
To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.
A typical C++ code will be:
hVaultLib = LoadLibrary(L"vaultcli.dll");
if (hVaultLib != NULL)
{
pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");
bStatus = (pVaultEnumerateVaults != NULL)
&& (pVaultFree != NULL)
&& (pVaultGetItemW7 != NULL)
&& (pVaultGetItemW8 != NULL)
&& (pVaultOpenVault != NULL)
&& (pVaultCloseVault != NULL)
&& (pVaultEnumerateItems != NULL);
}
Then you enumerate all stored credentials by calling
VaultEnumerateVaults
Then you go over the results.
S3 does not have directories, while you can list files in a pseudo directory manner like you demonstrated, there is no directory "file" per-se.
You may of inadvertently created a data file called users/<user-id>/contacts/<contact-id>/
.
From your example it seems reasonable to assume that the siteIP
column is determined by the siteName
column (that is, each site has only one siteIP
). If this is indeed the case, then there is a simple solution using group by
:
select
sites.siteName,
sites.siteIP,
max(history.date)
from sites
inner join history on
sites.siteName=history.siteName
group by
sites.siteName,
sites.siteIP
order by
sites.siteName;
However, if my assumption is not correct (that is, it is possible for a site to have multiple siteIP
), then it is not clear from you question which siteIP
you want the query to return in the second column. If just any siteIP
, then the following query will do:
select
sites.siteName,
min(sites.siteIP),
max(history.date)
from sites
inner join history on
sites.siteName=history.siteName
group by
sites.siteName
order by
sites.siteName;
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
<input type="text" name="num1" id="num1" onkeyup="sum()">
<input type="text" name="num2" id="num2" onkeyup="sum()">
<input type="text" name="num2" id="result">
<script>
function sum()
{
var number1 = document.getElementById('num1').value;
var number2 = document.getElementById('num2').value;
if (number1 == '') {
number1 = 0
var num3 = parseInt(number1) + parseInt(number2);
document.getElementById('result').value = num3;
}
else if(number2 == '')
{
number2 = 0;
var num3 = parseInt(number1) + parseInt(number2);
document.getElementById('result').value = num3;
}
else
{
var num3 = parseInt(number1) + parseInt(number2);
document.getElementById('result').value = num3;
}
}
</script>
Getting SOAP working usually does not require compiling PHP from source. I would recommend trying that only as a last option.
For good measure, check to see what your phpinfo says, if anything, about SOAP extensions:
$ php -i | grep -i soap
to ensure that it is the PHP extension that is missing.
Assuming you do not see anything about SOAP in the phpinfo, see what PHP SOAP packages might be available to you.
In Ubuntu/Debian you can search with:
$ apt-cache search php | grep -i soap
or in RHEL/Fedora you can search with:
$ yum search php | grep -i soap
There are usually two PHP SOAP packages available to you, usually php-soap
and php-nusoap
. php-soap
is typically what you get with configuring PHP with --enable-soap
.
In Ubuntu/Debian you can install with:
$ sudo apt-get install php-soap
Or in RHEL/Fedora you can install with:
$ sudo yum install php-soap
After the installation, you might need to place an ini file and restart Apache.
private void datagrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
string test = this.datagrid.Columns[e.ColumnIndex].HeaderText;
}
This code will get the HeaderText
value.
The downside of NULL in C++ is that it is a define for 0. This is a value that can be silently converted to pointer, a bool value, a float/double, or an int.
That is not very type safe and has lead to actual bugs in an application I worked on.
Consider this:
void Foo(int i);
void Foo(Bar* b);
void Foo(bool b);
main()
{
Foo(0);
Foo(NULL); // same as Foo(0)
}
C++11 defines a nullptr
that is convertible to a null pointer but not to other scalars. This is supported in all modern C++ compilers, including VC++ as of 2008. In older versions of GCC there is a similar feature, but then it was called __null
.
A see a lot of good answers, but I decide to put my 5 cents just to have good example:
iterates over all enumerable props
let nodes = document.documentElement.childNodes;_x000D_
_x000D_
for (var key in nodes) {_x000D_
console.log( key );_x000D_
}
_x000D_
iterates over all iterable values
let nodes = document.documentElement.childNodes;_x000D_
_x000D_
for (var node of nodes) {_x000D_
console.log( node.toString() );_x000D_
}
_x000D_
This is my class : Path is fine and properties is loaded.
package com.fiserv.dl.idp.logging;
import java.io.File;
import java.io.FileInputStream;
import java.util.MissingResourceException;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class LoggingCapsule {
private static Logger logger = Logger.getLogger(LoggingCapsule.class);
public static void info(String message) {
try {
String configDir = System.getProperty("config.path");
if (configDir == null) {
throw new MissingResourceException("System property: config.path not set", "", "");
}
Properties properties = new Properties();
properties.load(new FileInputStream(configDir + File.separator + "log4j" + ".properties"));
PropertyConfigurator.configure(properties);
} catch (Exception e) {
e.printStackTrace();
}
logger.info(message);
}
public static void error(String message){
System.out.println(message);
}
}
new Guid(string)
You could also look at using a TypeConverter
.
iText is a great Java PDF library. They also have an API for creating barcodes. You don't need to be creating a PDF to use it.
This page has the details on creating barcodes. Here is an example from that site:
BarcodeEAN codeEAN = new BarcodeEAN();
codeEAN.setCodeType(codeEAN.EAN13);
codeEAN.setCode("9780201615883");
Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);
The biggest thing you will need to determine is what type of barcode you need. There are many different barcode formats and iText does support a lot of them. You will need to know what format you need before you can determine if this API will work for you.
If you run into this issue in a fairly complex app it can be cumbersome to refactor all your imports. PyCharm offers a quickfix for this that will automatically change all usage of the imported symbols as well.
This has happened to me. My issue was caused when I didn't mount Docker file system correctly, so I configured the Disk Image Location and re-bind File sharing mount, and this now worked correctly. For reference, I use Docker Desktop in Windows.
Handy with error_log() if you're outputting multiple lines.
I've found a lot of debug statements look weird on my windows install since the developers have assumed unix endings when breaking up strings.
Yes you can insert but not as similar to SQL.
In SQL we can insert the row level data, but here you can insert by fields (columns).
During this you have to make sure target table and the query should have same datatype and same number of columns.
eg:
CREATE TABLE test(stu_name STRING,stu_id INT,stu_marks INT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
STORED AS TEXTFILE;
INSERT OVERWRITE TABLE test SELECT lang_name, lang_id, lang_legacy_id FROM export_table;
The most rapid option is to hand out MS Access or SQL Sever Management Studio (there's a free express edition) along with a read only account.
PHP is simple and has a well earned reputation for getting stuff done. PHP is excellent for copying and pasting code, and you can iterate insanely fast in PHP. PHP can lead to hard-to-maintain applications, and it can be difficult to set up a visual debugger.
Given that you use SQL Server, ASP.NET is also a good option. This is somewhat harder to setup; you'll need an IIS server, with a configured application. Iterations are a bit slower. ASP.NET is easier to maintain and Visual Studio is the best visual debugger around.
just a little hack that works
echo "$(awk '{awk code}' file)" > file
I had this problem because I forgot to select "Visual C++" when I was installing Visual Studio.
To add it, see: https://stackoverflow.com/a/31568246/1054322
def countvowels(string):
num_vowels=0
for char in string:
if char in "aeiouAEIOU":
num_vowels = num_vowels+1
return num_vowels
(remember the spacing s)
For those who use Data Binding:
Add the following static method to any class
@BindingAdapter("app:thumbTintCompat")
public static void setThumbTint(SeekBar seekBar, @ColorInt int color) {
seekBar.getThumb().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
Add app:thumbTintCompat
attribute to your SeekBar
<SeekBar
android:id="@+id/seek_bar"
style="@style/Widget.AppCompat.SeekBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:thumbTintCompat="@{@android:color/white}"
/>
That's it. Now you can use app:thumbTintCompat
with any SeekBar
. The progress tint can be configured in the same way.
Note: this method is also compatble with pre-lollipop devices.
Linux shared library minimal runnable ABI example
In the context of shared libraries, the most important implication of "having a stable ABI" is that you don't need to recompile your programs after the library changes.
So for example:
if you are selling a shared library, you save your users the annoyance of recompiling everything that depends on your library for every new release
if you are selling closed source program that depends on a shared library present in the user's distribution, you could release and test less prebuilts if you are certain that ABI is stable across certain versions of the target OS.
This is specially important in the case of the C standard library, which many many programs in your system link to.
Now I want to provide a minimal concrete runnable example of this.
main.c
#include <assert.h>
#include <stdlib.h>
#include "mylib.h"
int main(void) {
mylib_mystruct *myobject = mylib_init(1);
assert(myobject->old_field == 1);
free(myobject);
return EXIT_SUCCESS;
}
mylib.c
#include <stdlib.h>
#include "mylib.h"
mylib_mystruct* mylib_init(int old_field) {
mylib_mystruct *myobject;
myobject = malloc(sizeof(mylib_mystruct));
myobject->old_field = old_field;
return myobject;
}
mylib.h
#ifndef MYLIB_H
#define MYLIB_H
typedef struct {
int old_field;
} mylib_mystruct;
mylib_mystruct* mylib_init(int old_field);
#endif
Compiles and runs fine with:
cc='gcc -pedantic-errors -std=c89 -Wall -Wextra'
$cc -fPIC -c -o mylib.o mylib.c
$cc -L . -shared -o libmylib.so mylib.o
$cc -L . -o main.out main.c -lmylib
LD_LIBRARY_PATH=. ./main.out
Now, suppose that for v2 of the library, we want to add a new field to mylib_mystruct
called new_field
.
If we added the field before old_field
as in:
typedef struct {
int new_field;
int old_field;
} mylib_mystruct;
and rebuilt the library but not main.out
, then the assert fails!
This is because the line:
myobject->old_field == 1
had generated assembly that is trying to access the very first int
of the struct, which is now new_field
instead of the expected old_field
.
Therefore this change broke the ABI.
If, however, we add new_field
after old_field
:
typedef struct {
int old_field;
int new_field;
} mylib_mystruct;
then the old generated assembly still accesses the first int
of the struct, and the program still works, because we kept the ABI stable.
Here is a fully automated version of this example on GitHub.
Another way to keep this ABI stable would have been to treat mylib_mystruct
as an opaque struct, and only access its fields through method helpers. This makes it easier to keep the ABI stable, but would incur a performance overhead as we'd do more function calls.
API vs ABI
In the previous example, it is interesting to note that adding the new_field
before old_field
, only broke the ABI, but not the API.
What this means, is that if we had recompiled our main.c
program against the library, it would have worked regardless.
We would also have broken the API however if we had changed for example the function signature:
mylib_mystruct* mylib_init(int old_field, int new_field);
since in that case, main.c
would stop compiling altogether.
Semantic API vs Programming API
We can also classify API changes in a third type: semantic changes.
The semantic API, is usually a natural language description of what the API is supposed to do, usually included in the API documentation.
It is therefore possible to break the semantic API without breaking the program build itself.
For example, if we had modified
myobject->old_field = old_field;
to:
myobject->old_field = old_field + 1;
then this would have broken neither programming API, nor ABI, but main.c
the semantic API would break.
There are two ways to programmatically check the contract API:
formal verification. Harder to do, but produces mathematical proof of correctness, essentially unifying documentation and tests into a "human" / machine verifiable manner! As long as there isn't a bug in your formal description of course ;-)
This concept is closely related to the formalization of Mathematics itself: https://math.stackexchange.com/questions/53969/what-does-formal-mean/3297537#3297537
List of everything that breaks C / C++ shared library ABIs
TODO: find / create the ultimate list:
Java minimal runnable example
What is binary compatibility in Java?
Tested in Ubuntu 18.10, GCC 8.2.0.
Looking at the Jasmine source code sheds more light on the issue.
toBe
is very simple and just uses the identity/strict equality operator, ===
:
function(actual, expected) {
return {
pass: actual === expected
};
}
toEqual
, on the other hand, is nearly 150 lines long and has special handling for built in objects like String
, Number
, Boolean
, Date
, Error
, Element
and RegExp
. For other objects it recursively compares properties.
This is very different from the behavior of the equality operator, ==
. For example:
var simpleObject = {foo: 'bar'};
expect(simpleObject).toEqual({foo: 'bar'}); //true
simpleObject == {foo: 'bar'}; //false
var castableObject = {toString: function(){return 'bar'}};
expect(castableObject).toEqual('bar'); //false
castableObject == 'bar'; //true
Simply using re.sub
might also work instead of str.maketrans
. And this would also work in python 2.x
>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1
Another (albeit non-free) option is to install VMware Fusion or Parallels Desktop on the Mac and run Windows with Visual Studio in a VM.
This works really pretty well. The downsides are:
The upside is that you and the student don't need to hassle with differences in the IDE that may not be accounted for in your instruction materials.
Do it this way (make necessary changes in code)..
SqlConnection con = new SqlConnection(GetConnectionString());
con.Open();
SqlCommand cmd = new SqlCommand("CheckUser", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("username", username.Text);
SqlParameter p2 = new SqlParameter("password", password.Text);
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
SqlDataReader rd = cmd.ExecuteReader();
if(rd.HasRows)
{
//do the things
}
else
{
lblinfo.Text = "abc";
}
There is a new library called ipyvolume that may do what you want, the documentation shows live demos. The current version doesn't do meshes and lines, but master from the git repo does (as will version 0.4). (Disclaimer: I'm the author)
A regex splitting on word boundary \b
isn't the best solution for this:
var prefix = "prefix";
var classes = el.className.split(" ").filter(function(c) {
return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = classes.join(" ");
or as a jQuery mixin:
$.fn.removeClassPrefix = function(prefix) {
this.each(function(i, el) {
var classes = el.className.split(" ").filter(function(c) {
return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = classes.join(" ");
});
return this;
};
To extend Rodrigo's solution a little - for requests that are executed frequently, you may only want to display the loading image if the request takes more than a minimum time interval, otherwise the image will be continually popping up and quickly disappearing
var loading = false;
$.ajaxSetup({
beforeSend: function () {
// Display loading icon if AJAX call takes >1 second
loading = true;
setTimeout(function () {
if (loading) {
// show loading image
}
}, 1000);
},
complete: function () {
loading = false;
// hide loading image
}
});
You can not serialize a Python 3 'string' to bytes without explict conversion to some encoding.
outfile.write(plaintext.encode('utf-8'))
is possibly what you want. Also this works for both python 2.x and 3.x.
More readable way:
class A {
void foo() throws MyException() {
...
}
}
Just hide it in a RuntimeException
to get it past forEach()
void bar() throws MyException {
Stream<A> as = ...
try {
as.forEach(a -> {
try {
a.foo();
} catch(MyException e) {
throw new RuntimeException(e);
}
});
} catch(RuntimeException e) {
throw (MyException) e.getCause();
}
}
Although at this point I won't hold against someone if they say skip the streams and go with a for loop, unless:
Collection.stream()
, i.e. not straight forward translation to a for loop.parallelstream()
The z-index
property only works on elements with a position
value other than static
(e.g. position: absolute;
, position: relative;
, or position: fixed
).
There is also position: sticky;
that is supported in Firefox, is prefixed in Safari, worked for a time in older versions of Chrome under a custom flag, and is under consideration by Microsoft to add to their Edge browser.
Important
For regular positioning, be sure to include position: relative
on the elements where you also set the z-index
. Otherwise, it won't take effect.
Android Studio 2.2 came out with the ability to use ndk-build and cMake. Though, we had to wait til 2.2.3 for the Application.mk support. I've tried it, it works...though, my variables aren't showing up in the debugger. I can still query them via command line though.
You need to do something like this:
externalNativeBuild{
ndkBuild{
path "Android.mk"
}
}
defaultConfig {
externalNativeBuild{
ndkBuild {
arguments "NDK_APPLICATION_MK:=Application.mk"
cFlags "-DTEST_C_FLAG1" "-DTEST_C_FLAG2"
cppFlags "-DTEST_CPP_FLAG2" "-DTEST_CPP_FLAG2"
abiFilters "armeabi-v7a", "armeabi"
}
}
}
See http://tools.android.com/tech-docs/external-c-builds
NB: The extra nesting of externalNativeBuild
inside defaultConfig
was a breaking change introduced with Android Studio 2.2 Preview 5 (July 8, 2016). See the release notes at the above link.
you can convert the integer dataframe into string first and then do the operation e.g.
df3['nID']=df3['nID'].astype(str)
grp = df3.groupby('userID')['nID'].aggregate(lambda x: '->'.join(tuple(x)))
I ended up coding a custom solution (Firefox extension) that does this. I think by the time I developed it, the commandline mentioned in enreas wasn't there.
The Firefox extension is CmdShots. It's a good option if you need finer degree of control over the process of taking the screenshot (or you want to do some HTML/JS modifications and image processing).
You can use it and abuse it. I decided to keep it unlicensed, so you are free to play with it as you want.
It is easy you need to echo the value you need to return and then capture it like below
demofunc(){
local variable="hellow"
echo $variable
}
val=$(demofunc)
echo $val
I'm using Juno 4.2 with latest spring, maven plugin and JDK1.6.0_25.
I faced same issue and here is my fix that make default after each Eclipse restart:
I had the same problem and have solved it in the following way:
const fetch = (url) => {
return node-fetch(url)
.then(result => result.json())
.catch((e) => {
return new Promise((resolve) => setTimeout(() => resolve(fetch(url)), timeout));
});
};
tasks = [fetch(url1), fetch(url2) ....];
Promise.all(tasks).then(......)
In that case Promise.all
will wait for every Promise will come into resolved
or rejected
state.
And having this solution we are "stopping catch
execution" in a non-blocking way. In fact, we're not stopping anything, we just returning back the Promise
in a pending state which returns another Promise
when it's resolved after the timeout.
The way for loop is processed is as follows
1 First, initialization is performed (i=0)
2 the check is performed (i < n)
3 the code in the loop is executed.
4 the value is incremented
5 Repeat steps 2 - 4
This is the reason why, there is no difference between i++ and ++i in the for loop which has been used.
If you use bootstrap 4 Alpha and you have an error with the height of the images in chrome, I have a solution: The documentation of bootstrap 4 says this:
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="carousel-item active">
<img class="d-block img-fluid" src="..." alt="First slide">
</div>
<div class="carousel-item">
<img class="d-block img-fluid" src="..." alt="Second slide">
</div>
<div class="carousel-item">
<img class="d-block img-fluid" src="..." alt="Third slide">
</div>
</div>
</div>
Solution:
The solution is to put "div" around the image, with the class ".container", like this:
<div class="carousel-item active">
<div class="container">
<img src="images/proyecto_0.png" alt="First slide" class="d-block img-fluid">
</div>
</div>
This isn't exactly what's asked, but here's an important note: When running Java on a Windows machine, the Oracle installer puts a "java.exe" into C:\Windows\system32, and this is what acts as the launcher for the Java application (UNLESS there's a java.exe earlier in the PATH, and the Java app is run from the command-line). This is why File(".") keeps returning C:\Windows\system32, and why running examples from macOS or *nix implementations keep coming back with different results from Windows.
Unfortunately, there's really no universally correct answer to this one, as far as I have found in twenty years of Java coding unless you want to create your own native launcher executable using JNI Invocation, and get the current working directory from the native launcher code when it's launched. Everything else is going to have at least some nuance that could break under certain situations.
This may be work.
Find the CATALINA_HOME/webapps/manager/META-INF/context.xml
file and add the comment markers around the Valve.
<Context antiResourceLocking="false" privileged="true" >
<!--
<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
-->
</Context>
You have two typing errors in your code:
struct timeval,
should be
struct timeval
and after the printf()
parenthesis you need a semicolon.
Also, depending on the compiler, so simple a cycle might just be optimized out, giving you a time of 0 microseconds whatever you do.
Finally, the time calculation is wrong. You only take into accounts the seconds, ignoring the microseconds. You need to get the difference between seconds, multiply by one million, then add "after" tv_usec
and subtract "before" tv_usec
. You gain nothing by casting an integer number of seconds to a float.
I'd suggest checking out the man page for struct timeval
.
This is the code:
#include <stdio.h>
#include <sys/time.h>
int main (int argc, char** argv) {
struct timeval tvalBefore, tvalAfter; // removed comma
gettimeofday (&tvalBefore, NULL);
int i =0;
while ( i < 10000) {
i ++;
}
gettimeofday (&tvalAfter, NULL);
// Changed format to long int (%ld), changed time calculation
printf("Time in microseconds: %ld microseconds\n",
((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
+tvalAfter.tv_usec) - tvalBefore.tv_usec
); // Added semicolon
return 0;
}
tl;dr
cp -R "/src/project 1/App" "/src/project 2"
Explanation:
Using quotes will cater for spaces in the directory names
cp -R "/src/project 1/App" "/src/project 2"
If the App directory is specified in the destination directory:
cp -R "/src/project 1/App" "/src/project 2/App"
and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"
Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.
Inside a bash script:
cp -R "${1}/App" "${2}"
$ENV{FOO}
for usage, where FOO
is being picked up from the environment variable. otherwise use as ${FOO}
, where FOO
is some other variable. For setting, SET(FOO "foo")
would be used in CMake.
To see if a dataframe is empty, I argue that one should test for the length of a dataframe's columns index:
if len(df.columns) == 0: 1
According to the Pandas Reference API, there is a distinction between:
NaN
hence at least 1 columnArguably, they are not the same. The other answers are imprecise in that df.empty
, len(df)
, or len(df.index)
make no distinction and return index is 0 and empty is True in both cases.
Example 1: An empty dataframe with 0 rows and 0 columns
In [1]: import pandas as pd
df1 = pd.DataFrame()
df1
Out[1]: Empty DataFrame
Columns: []
Index: []
In [2]: len(df1.index) # or len(df1)
Out[2]: 0
In [3]: df1.empty
Out[3]: True
Example 2: A dataframe which is emptied to 0 rows but still retains n
columns
In [4]: df2 = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
df2
Out[4]: AA BB
0 1 11
1 2 22
2 3 33
In [5]: df2 = df2[df2['AA'] == 5]
df2
Out[5]: Empty DataFrame
Columns: [AA, BB]
Index: []
In [6]: len(df2.index) # or len(df2)
Out[6]: 0
In [7]: df2.empty
Out[7]: True
Now, building on the previous examples, in which the index is 0 and empty is True. When reading the length of the columns index for the first loaded dataframe df1, it returns 0 columns to prove that it is indeed empty.
In [8]: len(df1.columns)
Out[8]: 0
In [9]: len(df2.columns)
Out[9]: 2
Critically, while the second dataframe df2 contains no data, it is not completely empty because it returns the amount of empty columns that persist.
Let's add a new column to these dataframes to understand the implications:
# As expected, the empty column displays 1 series
In [10]: df1['CC'] = [111, 222, 333]
df1
Out[10]: CC
0 111
1 222
2 333
In [11]: len(df1.columns)
Out[11]: 1
# Note the persisting series with rows containing `NaN` values in df2
In [12]: df2['CC'] = [111, 222, 333]
df2
Out[12]: AA BB CC
0 NaN NaN 111
1 NaN NaN 222
2 NaN NaN 333
In [13]: len(df2.columns)
Out[13]: 3
It is evident that the original columns in df2 have re-surfaced. Therefore, it is prudent to instead read the length of the columns index with len(pandas.core.frame.DataFrame.columns)
to see if a dataframe is empty.
# New dataframe df
In [1]: df = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
df
Out[1]: AA BB
0 1 11
1 2 22
2 3 33
# This data manipulation approach results in an empty df
# because of a subset of values that are not available (`NaN`)
In [2]: df = df[df['AA'] == 5]
df
Out[2]: Empty DataFrame
Columns: [AA, BB]
Index: []
# NOTE: the df is empty, BUT the columns are persistent
In [3]: len(df.columns)
Out[3]: 2
# And accordingly, the other answers on this page
In [4]: len(df.index) # or len(df)
Out[4]: 0
In [5]: df.empty
Out[5]: True
# SOLUTION: conditionally check for empty columns
In [6]: if len(df.columns) != 0: # <--- here
# Do something, e.g.
# drop any columns containing rows with `NaN`
# to make the df really empty
df = df.dropna(how='all', axis=1)
df
Out[6]: Empty DataFrame
Columns: []
Index: []
# Testing shows it is indeed empty now
In [7]: len(df.columns)
Out[7]: 0
Adding a new data series works as expected without the re-surfacing of empty columns (factually, without any series that were containing rows with only NaN
):
In [8]: df['CC'] = [111, 222, 333]
df
Out[8]: CC
0 111
1 222
2 333
In [9]: len(df.columns)
Out[9]: 1
Yes, use gzip for this. The best way is to read data as input and redirect the compressed to output file i.e.
cat test.csv | gzip > test.csv.gz
cat test.csv
will send the data as stdout and using pipe-sign gzip will read that data as stdin. Make sure to redirect the gzip output to some file as compressed data will not be written to the terminal.
Tips from 2020:
From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:
$ pip install -U flask
If you are using flask run
instead of app.run()
with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads
):
$ flask run --with-threads
It's same as app.run(threaded=True)
I know its been a while since the original post but I like using CTE's and this worked for me:
WITH cte_table_a
AS
(
SELECT [id] [id]
, MAX([value]) [value]
FROM table_a
GROUP BY [id]
)
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN cte_table_a
ON table_b.id = cte_table_a.id
RUN
and ENTRYPOINT
are two different ways to execute a script.
RUN
means it creates an intermediate container, runs the script and freeze the new state of that container in a new intermediate image. The script won't be run after that: your final image is supposed to reflect the result of that script.
ENTRYPOINT
means your image (which has not executed the script yet) will create a container, and runs that script.
In both cases, the script needs to be added, and a RUN chmod +x /bootstrap.sh
is a good idea.
It should also start with a shebang (like #!/bin/sh
)
Considering your script (bootstrap.sh
: a couple of git config --global
commands), it would be best to RUN
that script once in your Dockerfile
, but making sure to use the right user (the global git config
file is %HOME%/.gitconfig
, which by default is the /root
one)
Add to your Dockerfile:
RUN /bootstrap.sh
Then, when running a container, check the content of /root/.gitconfig
to confirm the script was run.
xcopy "your-source-path" "your-destination-path" /D /y /s /r /exclude:path-to-txt- file\ExcludedFilesList.txt
Notice the quotes in source path and destination path, but not in path to exludelist txt file.
Content of ExcludedFilesList.txt is the following: .cs\
I'm using this command to copy file from one project in my solution, to another and excluding .cs files.
/D Copy only files that are modified in sourcepath
/y Suppresses prompting to confirm you want to overwrite an existing destination file.
/s Copies directories and subdirectories except empty ones.
/r Overwrites read-only files.
I think atof is exactly what you want. This function parses a string and converts it into a double. If the string does not start with a number (non-numerical) a 0.0 is returned.
However, it does try to parse as much of the string as it can. In other words, the string "3abc" would be interpreted as 3.0. If you want a function that will return 0.0 in these cases, you will need to write a small wrapper yourself.
Also, this function works with the C-style string of a null terminated array of characters. If you're using a string object, it will need to be converted to a char* before you use this function.
As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:
xlrd has explicitly removed support for anything other than xls files.
In your case, the solution is to:
openpyxl
: https://openpyxl.readthedocs.io/en/stable/df1 = pd.read_excel(
os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
engine='openpyxl',
)
Quick fix for CGRectMake , CGPointMake, CGSizeMake in Swift3 & iOS10
Add these extensions :
extension CGRect{
init(_ x:CGFloat,_ y:CGFloat,_ width:CGFloat,_ height:CGFloat) {
self.init(x:x,y:y,width:width,height:height)
}
}
extension CGSize{
init(_ width:CGFloat,_ height:CGFloat) {
self.init(width:width,height:height)
}
}
extension CGPoint{
init(_ x:CGFloat,_ y:CGFloat) {
self.init(x:x,y:y)
}
}
Then go to "Find and Replace in Workspace" Find CGRectMake , CGPointMake, CGSizeMake and Replace them with CGRect , CGPoint, CGSize
These steps might save all the time as Xcode right now doesn't give us quick conversion from Swift 2+ to Swift 3
You probably want to use the assets_base_urls
configuration.
framework:
templating:
assets_base_urls:
http: [http://www.website.com]
ssl: [https://www.website.com]
http://symfony.com/doc/current/reference/configuration/framework.html#assets
Note that the configuration is different since Symfony 2.7:
framework:
# ...
assets:
base_urls:
- 'http://cdn.example.com/'
Here's what I did:
After building Macvim I copied mvim to one of my $PATH destinations (In this case I chose /usr/local/bin)
cp -v [MacVim_source_folder]/src/MacVim/mvim /usr/local/bin
Then when you invoke mvim it is now recognised but there is an annoying thing. It opens the visual MacVim window, not the one in terminal. To do that, you have to invoke
mvim -v
To make sure every time you call mvim you don't have to remember to add the '-v' you can create an alias:
alias mvim='mvim -v'
However, this alias will only persist for this session of the Terminal. To have this alias executed every time you open a Terminal window, you have to include it in your .profile The .profile should be in your home directory. If it's not, create it.
cd ~
mvim -v .profile
include the alias command in there and save it.
That's it.
document.querySelector("iframe").addEventListener( "load", function(e) {_x000D_
_x000D_
this.style.backgroundColor = "red";_x000D_
alert(this.nodeName);_x000D_
_x000D_
console.log(e.target);_x000D_
_x000D_
} );
_x000D_
<iframe src="example.com" ></iframe>
_x000D_
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
ColumnName = column.ColumnName;
ColumnData = row[column].ToString();
}
}
When I have added/modified/deleted many files (since the last commit), I like to look at those modifications in chronological order.
For that I use:
To list all non-staged files:
git ls-files --other --modified --exclude-standard
To get the last modified date for each file:
while read filename; do echo -n "$(stat -c%y -- $filename 2> /dev/null) "; echo $filename; done
Although ruvim suggests in the comments:
xargs -0 stat -c '%y %n' --
To sort them from oldest to more recent:
sort
An alias makes it easier to use:
alias gstlast='git ls-files --other --modified --exclude-standard|while read filename; do echo -n "$(stat -c%y -- $filename 2> /dev/null) "; echo $filename; done|sort'
Or (shorter and more efficient, thanks to ruvim)
alias gstlast='git ls-files --other --modified --exclude-standard|xargs -0 stat -c '%y %n' --|sort'
For example:
username@hostname:~> gstlast
2015-01-20 11:40:05.000000000 +0000 .cpl/params/libelf
2015-01-21 09:02:58.435823000 +0000 .cpl/params/glib
2015-01-21 09:07:32.744336000 +0000 .cpl/params/libsecret
2015-01-21 09:10:01.294778000 +0000 .cpl/_deps
2015-01-21 09:17:42.846372000 +0000 .cpl/params/npth
2015-01-21 12:12:19.002718000 +0000 sbin/git-rcd
I now can review my modifications, from oldest to more recent.
This is an old question, but I want to add an answer from logistical point of view (i.e not from algorithm correctness point of view or performance point of view).
I use Java for work, and Java doesn't support nested function. As such, if I want to do recursion, I might have to define an external function (which exists only because my code bumps against Java's bureaucratic rule), or I might have to refactor the code altogether (which I really hate to do).
Thus, I often avoid recursion, and use stack operation instead, because recursion itself is essentially a stack operation.
I solved this on my WAMP setup by enabling the php_openssl
extension, since the URL I was loading from used https://
.
It says all the requests to go through WicketFilter
Also, if you use wicket WicketApplication for application level settings. Like URL patterns and things that are true at app level
This is what you need really, http://wicket.apache.org/learn/examples/helloworld.html
Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource
property, not its DataContext
.
<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}" AutoGenerateColumns="False" CanUserResizeColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
</DataGrid.Columns>
</DataGrid>
(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list
collection. The DataGrid is derived from ItemsControl
, which relies on its ItemsSource
property to define the collection it binds its rows to. Hence, if list
isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list}
and ItemsSource={Binding list}
on the DataGrid...)
Any JS code which executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as layed out in the HTML. So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page.
So, in your case, you can put your DOM interacting code inside a function so that only function is defined but not executed.
Then you can add an event listener for document load to execute the function.
That will give you something like:
<script>
function init() {
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
}
}
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
document.addEventListener('readystatechange', function() {
if (document.readyState === "complete") {
init();
}
});
</script>
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="button" id="myButton" value="Go" />
</form>
Fiddle at - http://jsfiddle.net/poonia/qQMEg/4/
Add this code on values anim
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:duration="@android:integer/config_longAnimTime"
android:fromXScale="0.2"
android:fromYScale="0.2"
android:toXScale="1.0"
android:toYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"/>
<alpha
android:fromAlpha="0.1"
android:toAlpha="1.0"
android:duration="@android:integer/config_longAnimTime"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"/>
</set>
call on styles.xml
<style name="DialogScale">
<item name="android:windowEnterAnimation">@anim/scale_in</item>
<item name="android:windowExitAnimation">@anim/scale_out</item>
</style>
In Java code: set Onclick
public void onClick(View v) {
fab_onclick(R.style.DialogScale, "Scale" ,(Activity) context,getWindow().getDecorView().getRootView());
// Dialogs.fab_onclick(R.style.DialogScale, "Scale");
}
setup on method:
alertDialog.getWindow().getAttributes().windowAnimations = type;
You should set async = false in head. Use post/get instead of ajax.
jQuery.ajaxSetup({ async: false });
$.post({
url: 'api.php',
data: 'id1=' + q + '',
dataType: 'json',
success: function (data) {
id = data[0];
vname = data[1];
}
});
The Color
structure is immutable (as all structures should really be), meaning that the values of its properties cannot be changed once that particular instance has been created.
Instead, you need to create a new instance of the structure with the property values that you want. Since you want to create a color using its component RGB values, you need to use the FromArgb
method:
Color myColor = Color.FromArgb(100, 150, 75);
Not exactly. But you can create a list of lists:
var ll = new List<List<int>>();
for(int i = 0; i < 10; ++i) {
var l = new List<int>();
ll.Add(l);
}
Apache Commons SFTP library
Common java properties file for all the examples
serverAddress=111.222.333.444
userId=myUserId
password=myPassword
remoteDirectory=products/
localDirectory=import/
Upload file to remote server using SFTP
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
public class SendMyFiles {
static Properties props;
public static void main(String[] args) {
SendMyFiles sendMyFiles = new SendMyFiles();
if (args.length < 1)
{
System.err.println("Usage: java " + sendMyFiles.getClass().getName()+
" Properties_file File_To_FTP ");
System.exit(1);
}
String propertiesFile = args[0].trim();
String fileToFTP = args[1].trim();
sendMyFiles.startFTP(propertiesFile, fileToFTP);
}
public boolean startFTP(String propertiesFilename, String fileToFTP){
props = new Properties();
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
props.load(new FileInputStream("properties/" + propertiesFilename));
String serverAddress = props.getProperty("serverAddress").trim();
String userId = props.getProperty("userId").trim();
String password = props.getProperty("password").trim();
String remoteDirectory = props.getProperty("remoteDirectory").trim();
String localDirectory = props.getProperty("localDirectory").trim();
//check if the file exists
String filepath = localDirectory + fileToFTP;
File file = new File(filepath);
if (!file.exists())
throw new RuntimeException("Error. Local file not found");
//Initializes the file manager
manager.init();
//Setup our SFTP configuration
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
opts, "no");
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
//Create the SFTP URI using the host name, userid, password, remote path and file name
String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" +
remoteDirectory + fileToFTP;
// Create local file object
FileObject localFile = manager.resolveFile(file.getAbsolutePath());
// Create remote file object
FileObject remoteFile = manager.resolveFile(sftpUri, opts);
// Copy local file to sftp server
remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
System.out.println("File upload successful");
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
finally {
manager.close();
}
return true;
}
}
Download file from remote server using SFTP
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
public class GetMyFiles {
static Properties props;
public static void main(String[] args) {
GetMyFiles getMyFiles = new GetMyFiles();
if (args.length < 1)
{
System.err.println("Usage: java " + getMyFiles.getClass().getName()+
" Properties_filename File_To_Download ");
System.exit(1);
}
String propertiesFilename = args[0].trim();
String fileToDownload = args[1].trim();
getMyFiles.startFTP(propertiesFilename, fileToDownload);
}
public boolean startFTP(String propertiesFilename, String fileToDownload){
props = new Properties();
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
props.load(new FileInputStream("properties/" + propertiesFilename));
String serverAddress = props.getProperty("serverAddress").trim();
String userId = props.getProperty("userId").trim();
String password = props.getProperty("password").trim();
String remoteDirectory = props.getProperty("remoteDirectory").trim();
String localDirectory = props.getProperty("localDirectory").trim();
//Initializes the file manager
manager.init();
//Setup our SFTP configuration
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
opts, "no");
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
//Create the SFTP URI using the host name, userid, password, remote path and file name
String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" +
remoteDirectory + fileToDownload;
// Create local file object
String filepath = localDirectory + fileToDownload;
File file = new File(filepath);
FileObject localFile = manager.resolveFile(file.getAbsolutePath());
// Create remote file object
FileObject remoteFile = manager.resolveFile(sftpUri, opts);
// Copy local file to sftp server
localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
System.out.println("File download successful");
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
finally {
manager.close();
}
return true;
}
}
Delete a file on remote server using SFTP
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
public class DeleteRemoteFile {
static Properties props;
public static void main(String[] args) {
DeleteRemoteFile getMyFiles = new DeleteRemoteFile();
if (args.length < 1)
{
System.err.println("Usage: java " + getMyFiles.getClass().getName()+
" Properties_filename File_To_Delete ");
System.exit(1);
}
String propertiesFilename = args[0].trim();
String fileToDownload = args[1].trim();
getMyFiles.startFTP(propertiesFilename, fileToDownload);
}
public boolean startFTP(String propertiesFilename, String fileToDownload){
props = new Properties();
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
props.load(new FileInputStream("properties/" + propertiesFilename));
String serverAddress = props.getProperty("serverAddress").trim();
String userId = props.getProperty("userId").trim();
String password = props.getProperty("password").trim();
String remoteDirectory = props.getProperty("remoteDirectory").trim();
//Initializes the file manager
manager.init();
//Setup our SFTP configuration
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
opts, "no");
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
//Create the SFTP URI using the host name, userid, password, remote path and file name
String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" +
remoteDirectory + fileToDownload;
//Create remote file object
FileObject remoteFile = manager.resolveFile(sftpUri, opts);
//Check if the file exists
if(remoteFile.exists()){
remoteFile.delete();
System.out.println("File delete successful");
}
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
finally {
manager.close();
}
return true;
}
}
Note to under
connetionString =@"server=XXX;Trusted_Connection=yes;database=yourDB;";
Note: XXX = . OR .\SQLEXPRESS OR .\MSSQLSERVER OR (local)\SQLEXPRESS OR (localdb)\v11.0 &...
you can replace 'server' with 'Data Source'
too you can replace 'database' with 'Initial Catalog'
Sample:
connetionString =@"server=.\SQLEXPRESS;Trusted_Connection=yes;Initial Catalog=books;";
Run CMD as administrator
and on CMD screen type ipconfig and the screen will appear with text
as this photo
and you can access your localhost using this ip you have to be connected to same network as your pc connected to
The only solution that worked for me and $.each
was definitely causing the error. so i used for loop
and it's not throwing error anymore.
Example code
$.ajax({
type: 'GET',
url: 'https://example.com/api',
data: { get_param: 'value' },
success: function (data) {
for (var i = 0; i < data.length; ++i) {
console.log(data[i].NameGerman);
}
}
});
Both of these classes are smart pointers, which means that they automatically (in most cases) will deallocate the object that they point at when that object can no longer be referenced. The difference between the two is how many different pointers of each type can refer to a resource.
When using unique_ptr
, there can be at most one unique_ptr
pointing at any one resource. When that unique_ptr
is destroyed, the resource is automatically reclaimed. Because there can only be one unique_ptr
to any resource, any attempt to make a copy of a unique_ptr
will cause a compile-time error. For example, this code is illegal:
unique_ptr<T> myPtr(new T); // Okay
unique_ptr<T> myOtherPtr = myPtr; // Error: Can't copy unique_ptr
However, unique_ptr
can be moved using the new move semantics:
unique_ptr<T> myPtr(new T); // Okay
unique_ptr<T> myOtherPtr = std::move(myPtr); // Okay, resource now stored in myOtherPtr
Similarly, you can do something like this:
unique_ptr<T> MyFunction() {
unique_ptr<T> myPtr(/* ... */);
/* ... */
return myPtr;
}
This idiom means "I'm returning a managed resource to you. If you don't explicitly capture the return value, then the resource will be cleaned up. If you do, then you now have exclusive ownership of that resource." In this way, you can think of unique_ptr
as a safer, better replacement for auto_ptr
.
shared_ptr
, on the other hand, allows for multiple pointers to point at a given resource. When the very last shared_ptr
to a resource is destroyed, the resource will be deallocated. For example, this code is perfectly legal:
shared_ptr<T> myPtr(new T); // Okay
shared_ptr<T> myOtherPtr = myPtr; // Sure! Now have two pointers to the resource.
Internally, shared_ptr
uses reference counting to track how many pointers refer to a resource, so you need to be careful not to introduce any reference cycles.
In short:
unique_ptr
when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed.shared_ptr
when you want multiple pointers to the same resource.Hope this helps!
Since you are on Windows, instead of \n use \r\n (carriage return + line feed).
C# has a few more features than Java. Take delegates for example: Many very simple C# applications use delegates, while the Java folks figures that the observer pattern was sufficient. So, in order for a tool to convert a C# application which uses delegates it would have to translate the structure from using delegates to an implementation of the observer pattern. Another problem is the fact that C# methods are not virtual by default while Java methods are. Additionally, Java doesn't have a way to make methods non virtual. This creates another problem: an application in C# could leverage non virtual method behavior through polymorphism in a way the does not translate directly to Java. If you look around you will probably find that there are lots of tools to convert Java to C# since it is a simpler language (please don't flame me I didn't say worse I said simpler); however, you will find very few if any decent tools that convert C# to Java.
I would recommend changing your approach to converting from Java to C# as it will create fewer headaches in the long run. Db4Objects recently released their internal tool which they use to convert Db4o into C# to the public. It is called Sharpen. If you register with their site you can view this link with instructions on how to use Sharpen: http://developer.db4o.com/Resources/view.aspx/Reference/Sharpen/How_To_Setup_Sharpen
(I've been registered with them for a while and they're good about not spamming)
Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.
This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127, whichever is bigger.(We can set top level value upto which Integer values should get cached by using java.lang.Integer.IntegerCache.high).
For example:
If we set java.lang.Integer.IntegerCache.high=500;
then values from -128 to 500 will get cached and
Integer a=498;
Integer b=499;
System.out.println(a==b)
Output will be "true".
Float and Double objects never gets cached.
Character will get cache from 0 to 127
You are comparing two objects. so == operator will check equality of object references. There are following ways to do it.
1) type cast both objects into primitive values and compare
(long)val3 == (long)val4
2) read value of object and compare
val3.longValue() == val4.longValue()
3) Use equals() method on object comparison.
val3.equals(val4);
You should try this one:
$("selector").prop("classList")
It returns an array of all current classes of the element.
Try:
s = filter(str.isalnum, s)
in Python3:
s = ''.join(filter(str.isalnum, s))
Edit: realized that the OP wants to replace non-chars with '*'. My answer does not fit
Looks like problem is based on a server side.
Im my case I worked with paypal server and neither of suggested answers helped, but http://forums.iis.net/t/1217360.aspx?HTTP+403+Forbidden+error
I was facing this issue and just got the reply from Paypal technical. Add this will fix the 403 issue.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UserAgent = "[any words that is more than 5 characters]";
The --add-host
could be a more cleaner solution (but without the port part, only the host can be handled with this solution). So, in your docker run
command, do something like:
docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print $3}'` [my container]
If you have the name of the remote, you will be able with git 2.7 (Q4 2015), to use the new git remote get-url
command:
git remote get-url origin
(nice pendant of git remote set-url origin <newurl>
)
See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf
).
(Merged by Junio C Hamano -- gitster
-- in commit e437cbd, 05 Oct 2015)
remote: add get-url subcommand
Expanding
insteadOf
is a part ofls-remote --url
and there is no way to expandpushInsteadOf
as well.
Add aget-url
subcommand to be able to query both as well as a way to get all configured urls.
Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.
If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like
double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);
(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)
$("#ValuationName").bind("keypress", function (event) {
if (event.charCode!=0) {
var regex = new RegExp("^[a-zA-Z ]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
});
Just a slightly cleaned up way of doing this. This is no more or less performant than ATOzTOA's answer, but there's no reason to do two separate with statements.
with open(path_1, 'a') as file_1, open(path_2, 'r') as file_2:
for line in file_2:
if 'tests/file/myword' in line:
file_1.write(line)
The for
attribute of the <label>
tag should be equal to the id
attribute of the related element to bind them together.
Type Services.msc in run panel of windows run window. It will list all the windows services in our system. Now we need to start Asp .net State service as show in the image.
Your issue will get resolved.
Further modification from JC_VA, take what he has, and replace the MyModelConverter with...
public class MyModelConverter : JsonConverter
{
//objectType is the type as specified for List<myModel> (i.e. myModel)
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader); //json from myModelList > model
var list = Activator.CreateInstance(objectType) as System.Collections.IList; // new list to return
var itemType = objectType.GenericTypeArguments[0]; // type of the list (myModel)
if (token.Type.ToString() == "Object") //Object
{
var child = token.Children();
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(token.CreateReader(), newObject);
list.Add(newObject);
}
else //Array
{
foreach (var child in token.Children())
{
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(child.CreateReader(), newObject);
list.Add(newObject);
}
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
This should work for json that is either
myModelList{
model: [{ ... object ... }]
}
or
myModelList{
model: { ... object ... }
}
they will both end up being parsed as if they were
myModelList{
model: [{ ... object ... }]
}
I should be like this:
$.post(submitAddress, { 'yourArrayName' : javaScriptArrayToSubmitToServer },
function(response, status, xhr) {
alert("POST returned: \n" + response + "\n\n");
})
In PowerShell 5 and PowerShell 5 ISE, it is also possible to use just Shift + Enter for multiline editing (instead of standard backticks `
at the end of each line):
PS> &"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" # Shift+Enter
>>> -verb:sync # Shift+Enter
>>> -source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" # Shift+Enter
>>> -dest:contentPath="c:\websites\xxx\wwwroot,computerName=192.168.1.1,username=administrator,password=xxx"
It's a "precompiled header file" -- any headers you include in stdafx.h are pre-processed to save time during subsequent compilations. You can read more about it here on MSDN.
If you're building a cross-platform application, check "Empty project" when creating your project and Visual Studio won't put any files at all in your project.
You are trying to run bash
, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d
, but you can do this by adding -it
to the command line, which ensures that the container has a valid tty associated with it and that stdin
remains connected:
docker run -it -d -p 52022:22 basickarl/docker-git-test
You would more commonly run some sort of long-lived non-interactive process (like sshd
, or a web server, or a database server, or a process manager like systemd
or supervisor
) when starting detached containers.
If you are trying to run a service like sshd
, you cannot simply run service ssh start
. This will -- depending on the distribution you're running inside your container -- do one of two things:
It will try to contact a process manager like systemd
or upstart
to start the service. Because there is no service manager running, this will fail.
It will actually start sshd
, but it will be started in the background. This means that (a) the service sshd start
command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.
If you want to run just ssh in a container, consider an example like this.
If you want to run sshd
and other processes inside the container, you will need to investigate some sort of process supervisor.
Running Eclipse v4.3 (Kepler), the steps outlined by AlvaroCachoperro do the trick for the Java text editor and console window text.
Many of the text font options, including the Java Editor Text Font note, are "set to default: Text Font". The 'default' can be found and configured as follows:
On the Eclipse toolbar, select Window ? Preferences. Drill down to: (General ? Appearance ? Colors and Fonts ? Basic ? Text Font) (at the bottom)
Eclipse will remember your settings for your current workspace.
I teach programming and use the larger font for the students in the back.
Have you tried using @JsonProperty?
@Entity
public class City {
@id
Long id;
String name;
@JsonProperty("label")
public String getName() { return name; }
public void setName(String name){ this.name = name; }
@JsonProperty("value")
public Long getId() { return id; }
public void setId(Long id){ this.id = id; }
}
String input = "2,1,3,4,5,10,100";
String[] strings = input.split(",");
int[] numbers = new int[strings.length];
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = Integer.parseInt(strings[i]);
}
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
Your question already has been answered well, but I recommend using isinstance(d, collections.Mapping)
instead of isinstance(d, dict)
. It works for dict()
, collections.OrderedDict()
, and collections.UserDict()
.
The generally correct version is:
def myprint(d):
for k, v in d.items():
if isinstance(v, collections.Mapping):
myprint(v)
else:
print("{0} : {1}".format(k, v))
You can use -b to specify a cookie file to read the cookies from as well.
In many situations using -c and -b to the same file is what you want:
curl -b cookies.txt -c cookies.txt http://example.com
Further
Using only -c will make curl start with no cookies but still parse and understand cookies and if redirects or multiple URLs are used, it will then use the received cookies within the single invoke before it writes them all to the output file in the end.
The -b option feeds a set of initial cookies into curl so that it knows about them at start, and it activates curl's cookie parser so that it'll parse and use incoming cookies as well.
See Also
The cookies chapter in the Everything curl book.
Just right click on the ConstrainLayout and select the "convert view" and then "RelativeLayout":
My answer is basically very similar to that of Rubzen. I use the image as the object value, btw. Two versions work for me:
{
"name": "Silver Card",
"logo": require('./golden-card.png'),
or
const goldenCard = require('./golden-card.png');
{ "name": "Silver Card",
"logo": goldenCard,
Without wrappers - but that is different application, too.
I have checked also "import" solution and in few cases it works (what is not surprising, that is applied in pattern App.js in React), but not in case as mine above.
You can't do this with jQuery ajax, but with native XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is what you're looking for
handler(this.response);
console.log(this.response, typeof this.response);
var img = document.getElementById('img');
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
}
}
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();
EDIT
So revisiting this topic, it seems it is indeed possible to do this with jQuery 3
jQuery.ajax({_x000D_
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
cache:false,_x000D_
xhr:function(){// Seems like the only way to get access to the xhr object_x000D_
var xhr = new XMLHttpRequest();_x000D_
xhr.responseType= 'blob'_x000D_
return xhr;_x000D_
},_x000D_
success: function(data){_x000D_
var img = document.getElementById('img');_x000D_
var url = window.URL || window.webkitURL;_x000D_
img.src = url.createObjectURL(data);_x000D_
},_x000D_
error:function(){_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
or
use xhrFields to set the responseType
jQuery.ajax({_x000D_
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
cache:false,_x000D_
xhrFields:{_x000D_
responseType: 'blob'_x000D_
},_x000D_
success: function(data){_x000D_
var img = document.getElementById('img');_x000D_
var url = window.URL || window.webkitURL;_x000D_
img.src = url.createObjectURL(data);_x000D_
},_x000D_
error:function(){_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
@Jonathan Sampson i think your solution is wrong if you use multiple @media.
You should use (min-width first):
@media screen and (min-width:400px) and (max-width:900px){
...
}
If you just want to set the same color to every separator and it is opaque you can use:
self.tableView.separatorColor = UIColor.redColor()
If you want to use different colors for the separators or clear the separator color or use a color with alpha.
BE CAREFUL: You have to know that there is a backgroundView in the separator that has a default color.
To change it you can use this functions:
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if(view.isKindOfClass(UITableViewHeaderFooterView)){
var headerView = view as! UITableViewHeaderFooterView;
headerView.backgroundView?.backgroundColor = myColor
//Other colors you can change here
// headerView.backgroundColor = myColor
// headerView.contentView.backgroundColor = myColor
}
}
func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
if(view.isKindOfClass(UITableViewHeaderFooterView)){
var footerView = view as! UITableViewHeaderFooterView;
footerView.backgroundView?.backgroundColor = myColor
//Other colors you can change here
//footerView.backgroundColor = myColor
//footerView.contentView.backgroundColor = myColor
}
}
Hope it helps!
We had this problem multiple times in the company I work at. Deleting the node_modules
folder from the .nvm folder fixed the problem:
rm -rf ~/.nvm/versions/node/v8.6.0/lib/node_modules
ptomato's code can also be written in a cleaner manner like:
ifeq ($(TARGET_CPU),x86) TARGET_CPU_IS_X86 := 1 else ifeq ($(TARGET_CPU),x86_64) TARGET_CPU_IS_X86 := 1 else TARGET_CPU_IS_X86 := 0 endif
This doesn't answer OP's question but as it's the top result on google, I'm adding it here in case it's useful to anyone else.
Find your binaries file where it is saved. get the path in terminal mine is
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin
then find your local user data path, it is in mostly
C:\usr\local\pgsql\data
now all we have to hit the following command in the binary terminal path:
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin>pg_ctl -D "C:\usr\local\pgsql\data" start
done!
Going back to the __getattribute__ function; if the default implementation was not overridden; the following checks are done when executing the method:
This is the actual implementation of the object.__getattribute__ method:
.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) Generic attribute getter function that is meant to be put into a type object's tp_getattro slot. It looks for a descriptor in the dictionary of classes in the object's MRO as well as an attribute in the object's :attr:~object.dict (if present). As outlined in :ref:descriptors, data descriptors take preference over instance attributes, while non-data descriptors don't. Otherwise, an :exc:AttributeError is raised.
A good example of real time found from here:-
A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it". Instead, you see a dog or a cat or a pig... all animals. The point is, that you can never see an animal walking around that isn't more specifically something else (duck, pig, etc.). The Animal is the abstract class and Duck/Pig/Cat are all classes that derive from that base class. Animals might provide a function called "Age" that adds 1 year of life to the animals. It might also provide an abstract method called "IsDead" that, when called, will tell you if the animal has died. Since IsDead is abstract, each animal must implement it. So, a Cat might decide it is dead after it reaches 14 years of age, but a Duck might decide it dies after 5 years of age. The abstract class Animal provides the Age function to all classes that derive from it, but each of those classes has to implement IsDead on their own.
A business example:
I have a persistance engine that will work against any data sourcer (XML, ASCII (delimited and fixed-length), various JDBC sources (Oracle, SQL, ODBC, etc.) I created a base, abstract class to provide common functionality in this persistance, but instantiate the appropriate "Port" (subclass) when persisting my objects. (This makes development of new "Ports" much easier, since most of the work is done in the superclasses; especially the various JDBC ones; since I not only do persistance but other things [like table generation], I have to provide the various differences for each database.) The best business examples of Interfaces are the Collections. I can work with a java.util.List without caring how it is implemented; having the List as an abstract class does not make sense because there are fundamental differences in how anArrayList works as opposed to a LinkedList. Likewise, Map and Set. And if I am just working with a group of objects and don't care if it's a List, Map, or Set, I can just use the Collection interface.
@zhutoulala -- FWIW your links worked for me with Hadoop 2.4.0 with one exception I had to tell maven not to build the javadocs. I also used the patch in the first link for 2.4.0 and it worked fine. Here's the maven command I had to issue
mvn package -Dmaven.javadoc.skip=true -Pdist,native -DskipTests -Dtar
After building this and moving the libraries, don't forget to update hadoop-env.sh :)
Thought this might help someone who ran into the same roadblocks as me
It's quite simple actually if you're using PostgreSQL, just use distinct(columns)
(documentation).
Productorder.objects.all().distinct('category')
Note that this feature has been included in Django since 1.4
Perhaps not what the OP was after, but for those searching the URL to simply access a readable object on S3 is more like:
https://<region>.amazonaws.com/<bucket-name>/<key>
Where <region>
is something like s3-ap-southeast-2
.
Click on the item in the S3 GUI to get the link for your bucket.
Specific Solution to the example problem:-
Try [A-Z]*123$
will match 123
, AAA123
, ASDFRRF123
. In case you need at least a character before 123
use [A-Z]+123$
.
General Solution to the question (How to match "any character" in the regular expression):
[\w|\W]{min_char_to_match,}
.[\S]{min_char_to_match,}
.Hope this helps. I was able to open pdf files from all subfolders of a folder and copy content to the macro enabled workbook using shell as recommended above.Please see below the code .
Sub ConsolidateWorkbooksLTD()
Dim adobeReaderPath As String
Dim pathAndFileName As String
Dim shellPathName As String
Dim fso, subFldr, subFlodr
Dim FolderPath
Dim Filename As String
Dim Sheet As Worksheet
Dim ws As Worksheet
Dim HK As String
Dim s As String
Dim J As String
Dim diaFolder As FileDialog
Dim mFolder As String
Dim Basebk As Workbook
Dim Actbk As Workbook
Application.ScreenUpdating = False
Set Basebk = ThisWorkbook
' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
MsgBox diaFolder.SelectedItems(1) & "\"
mFolder = diaFolder.SelectedItems(1) & "\"
Set diaFolder = Nothing
Set fso = CreateObject("Scripting.FileSystemObject")
Set FolderPath = fso.GetFolder(mFolder)
For Each subFldr In FolderPath.SubFolders
subFlodr = subFldr & "\"
Filename = Dir(subFldr & "\*.csv*")
Do While Len(Filename) > 0
J = Filename
J = Left(J, Len(J) - 4) & ".pdf"
Workbooks.Open Filename:=subFldr & "\" & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Set Actbk = ActiveWorkbook
s = ActiveWorkbook.Name
HK = Left(s, Len(s) - 4)
If InStrRev(HK, "_S") <> 0 Then
HK = Right(HK, Len(HK) - InStrRev(HK, "_S"))
Else
HK = Right(HK, Len(HK) - InStrRev(HK, "_L"))
End If
Sheet.Copy After:=ThisWorkbook.Sheets(1)
ActiveSheet.Name = HK
' Open pdf file to copy SIC Decsription
pathAndFileName = subFlodr & J
adobeReaderPath = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"
shellPathName = adobeReaderPath & " """ & pathAndFileName & """"
Call Shell( _
pathname:=shellPathName, _
windowstyle:=vbNormalFocus)
Application.Wait Now + TimeValue("0:00:2")
SendKeys "%vpc"
SendKeys "^a", True
Application.Wait Now + TimeValue("00:00:2")
' send key to copy
SendKeys "^c"
' wait 2 secs
Application.Wait Now + TimeValue("00:00:2")
' activate this workook and paste the data
ThisWorkbook.Activate
Set ws = ThisWorkbook.Sheets(HK)
Range("O1:O5").Select
ws.Paste
Application.Wait Now + TimeValue("00:00:3")
Application.CutCopyMode = False
Application.Wait Now + TimeValue("00:00:3")
Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)
' send key to close pdf file
SendKeys "^q"
Application.Wait Now + TimeValue("00:00:3")
Next Sheet
Workbooks(Filename).Close SaveAs = True
Filename = Dir()
Loop
Next
Application.ScreenUpdating = True
End Sub
I wrote the piece of code to copy from pdf and csv to the macro enabled workbook and you may need to fine tune as per your requirement
Regards, Hema Kasturi
If you use IIS, I'd suggest trying IIS CORS module.
It's easy to configure and works for all types of controllers.
Here is an example of configuration:
<system.webServer>
<cors enabled="true" failUnlistedOrigins="true">
<add origin="*" />
<add origin="https://*.microsoft.com"
allowCredentials="true"
maxAge="120">
<allowHeaders allowAllRequestedHeaders="true">
<add header="header1" />
<add header="header2" />
</allowHeaders>
<allowMethods>
<add method="DELETE" />
</allowMethods>
<exposeHeaders>
<add header="header1" />
<add header="header2" />
</exposeHeaders>
</add>
<add origin="http://*" allowed="false" />
</cors>
</system.webServer>
setSelectedItem("banana")
. You could have found it yourself by just reading the javadoc.
Edit: since you changed the question, I'll change my answer.
If you want to select the item having the "banana" label, then you have two solutions:
setSelectedItem(theFoundItem)
(or setSelectedIndex(theFoundIndex)
)equals
and hashCode
in ComboItem
so that two ComboItem
instances having the same name are equal, and simply use setSelectedItem(new ComboItem(anyNumber, "banana"))
;s[0:"s".index("&")]
what does this do:
In Standard SQL, no. A WHERE
clause implies a table expression.
From the SQL-92 spec:
7.6 "where clause"
Function
Specify a table derived by the application of a "search condition" to the result of the preceding "from clause".
In turn:
7.4 "from clause"
Function
Specify a table derived from one or more named tables.
A Standard way of doing it (i.e. should work on any SQL product):
SELECT DISTINCT 'Hello world' AS new_value
FROM AnyTableWithOneOrMoreRows
WHERE 1 = 1;
...assuming you want to change the WHERE
clause to something more meaningful, otherwise it can be omitted.
You can simply put "." the dot sign. I've had a cmd application that was requiring the path and I was already in the needed directory and I used the dot symbol.
Hope it helps.
I found this reference:
create trigger myTrigger
on SomeTable
for insert
as
if (select count(*)
from SomeTable, inserted
where IsNumeric(SomeField) = 1) <> 0
/* Cancel the insert and print a message.*/
begin
rollback transaction
print "You can't do that!"
end
/* Otherwise, allow it. */
else
print "Added successfully."
I haven't tested it, but logically it looks like it should dp what you're after...rather than deleting the inserted data, prevent the insertion completely, thus not requiring you to have to undo the insert. It should perform better and should therefore ultimately handle a higher load with more ease.
Edit: Of course, there is the potential that if the insert happened inside of an otherwise valid transaction that the wole transaction could be rolled back so you would need to take that scenario into account and determine if the insertion of an invalid data row would constitute a completely invalid transaction...
If it's not a literal, you have to use \\\\
so that you get \\
which means an escaped backslash.
That's because there are two representations. In the string representation of your regex, you have "\\\\"
, Which is what gets sent to the parser. The parser will see \\
which it interprets as a valid escaped-backslash (which matches a single backslash).
It's no join since the relationship will only be evaluated when needed. A join (in a SQL database) on the other hand will resolve relationships and return them as if they were a single table (you "join two tables into one").
You can read more about DBRef here: http://docs.mongodb.org/manual/applications/database-references/
There are two possible solutions for resolving references. One is to do it manually, as you have almost described. Just save a document's _id in another document's other_id, then write your own function to resolve the relationship. The other solution is to use DBRefs as described on the manual page above, which will make MongoDB resolve the relationship client-side on demand. Which solution you choose does not matter so much because both methods will resolve the relationship client-side (note that a SQL database resolves joins on the server-side).
Try writing it in a new file..
f = open(filename, 'r+')
f2= open(filename2,'a+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.close()
f2.write(text)
fw.close()
I was seeing this issue when I was creating a bundle to react-native. Things I tried and didn't work:
node --max_old_space_size
, intrestingly this worked locally for me but failed on jenkins and I'm still not sure what goes wrong with jenkinsThing that did work for me:
I was importing a really big file in the code. The way I resolved it was by including it in the ignore
list in .babelrc
something like this:
{
"presets": ["react-native"],
"plugins": ["transform-inline-environment-variables"],
"ignore": ["*.json","filepathToIgnore.ext"]
}
It was a .js
file which did not really needed transpiling and adding it to the ignore list did help.
I tried below line as per @Andrie answer but didn't work,
op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
so after hunting more, I did work around to get it work successfully.
Here is my code snip.
AFHTTPRequestOperationManager *operation = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
AFJSONResponseSerializer *jsonResponseSerializer = [AFJSONResponseSerializer serializer];
NSMutableSet *jsonAcceptableContentTypes = [NSMutableSet setWithSet:jsonResponseSerializer.acceptableContentTypes];
[jsonAcceptableContentTypes addObject:@"text/plain"];
jsonResponseSerializer.acceptableContentTypes = jsonAcceptableContentTypes;
operation.responseSerializer = jsonResponseSerializer;
Hope this will help someone out there.
You can use a lambda:
Collectors.toMap(p -> p.getLast(), Function.identity())
or, more concisely, you can use a method reference using ::
:
Collectors.toMap(Person::getLast, Function.identity())
and instead of Function.identity
, you can simply use the equivalent lambda:
Collectors.toMap(Person::getLast, p -> p)
If you use Netbeans you should get hints whenever an anonymous class can be replaced by a lambda.