In short,
Struts is for Front-end development of website
Hibernate is for back-end development of website
Spring is for full stack development of website in which Spring MVC(Model-View-Controller) is for Front-end. ORM, JDBC for Data Access / Integration(backend). etc
I've got the same problem here. I have an UTF-8 Page an need to post to an ISO-8859-1 server.
Looks like IE can't handle ISO-8859-1. But it can handle ISO-8859-15.
<form accept-charset="ISO-8859-15">
...
</form>
So this worked for me, since ISO-8859-1 and ISO-8859-15 are almost the same.
Put this in the <head>
section:
<link rel="icon" href="http://www.domain.com/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.domain.com/favicon.ico" type="image/x-icon" />
Keep the picture file named "favicon.ico". You'll have to look online to get a .ico file generator.
What about this solution? It does not rely on knowledge of @staticmethod
decorator implementation. Inner class StaticMethod plays as a container of static initialization functions.
class Klass(object):
class StaticMethod:
@staticmethod # use as decorator
def _stat_func():
return 42
_ANS = StaticMethod._stat_func() # call the staticmethod
def method(self):
ret = self.StaticMethod._stat_func() + Klass._ANS
return ret
Tried everything mentioned (browser preferences, hsts, etc.) but nothing worked for me.
I solved it by adding a trailing .localhost
to the host aliases.
Like this:
127.0.0.1 myproject.localhost
127.0.0.1 dev.project.localhost
Generally people pull the official image of Ubuntu/CentOS but they don't realize that these images are minimal and doesn't have any thing on the top of that.
For Ubuntu, this image is built from official rootfs tarballs provided by Canonical. Given that it is a minimal install of Ubuntu, this image only includes the C, C.UTF-8, and POSIX locales by default.
One can install net-tools (includes ifconfig, netstat), ip-utils(includes ping) andy other likes curl etc on container and can create image from container or can write Dockerfile that will install these tool while creating image.
Below is Dockerfile example, while creating image from this it will include these tools:
FROM vkitpro/ubuntu16.04
RUN apt-get update -y \
&& apt-get upgrade -y \
&& apt-get install iputils-ping -y \
&& apt-get install net-tools -y \
CMD bash
or launch container from base image and install these utilities on container and then commit to image. docker commit -m "any descriptive message" container_id image_name:lattest
That image will have all thing installed.
The MultiCell
is used for print text with multiple lines. It has the same atributes of Cell
except for ln
and link
.
$pdf->MultiCell( 200, 40, $reportSubtitle, 1);
What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).
MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])
You can read the full documentation here.
The easiest way to check if given date is valid probably converting it to unixtime using strtotime
, formatting it to the given date's format, then comparing it:
function isValidDate($date) {
return date('Y-m-d', strtotime($date)) === $date;
}
Of course you can use regular expression to check for validness, but it will be limited to given format, every time you will have to edit it to satisfy another formats, and also it will be more than required. Built-in functions is the best way (in most cases) to achieve jobs.
As long as you specify a width on the element, it should wrap itself without needing anything else.
I got the commit ID from bitbucket
and then did:
git checkout commitID .
Example:
git checkout 7991072 .
And it reverted it back up to that working copy of that commit.
Go to Start
→ Control Panel
→ System
→ Advanced system settings
→ advanced(tab)
→ Environment Variables
→ System Variables
→ New
:
Variable name: _JAVA_OPTIONS
Variable value: -Xmx512M
I had this problem on windows 10. "--secure-file-priv in MySQL" To solve this I did the following.
The server started up as expected.
It's not exactly copy and paste but you can import data from Excel using Oracle SQL Developer.
Navigate to the table you want to import the data into and click on the Data
tab.
After clicking on the data tab you should notice a drop down that says Actions...
Click Actions...
and select the bottom option Import Data...
Then just follow the wizard to select the correct sheet, and columns that you want to import.
EDIT : To view the data tab :
SCHEMA
where your table is created.(Choose from the Connections tab on the left pane).SCHEMA
and choose SCHEMA BROWSER
.DATA
tab. Actions
and Import Data...
Same solution via Jquery. Works if you have more than one file input in the page.
$j(".filebutton").click(function() {
var input = $j(this).next().find('input');
input.click();
});
$j(".fileinput").change(function(){
var file = $j(this).val();
var fileName = file.split("\\");
var pai =$j(this).parent().parent().prev();
pai.html(fileName[fileName.length-1]);
event.preventDefault();
});
This worked for me:
$('input[name="sort_order"]').attr('value','XXX');
You can't use @android:style/TextAppearance
as the parent for the whole app's theme; that's why koopaking3's solution seems quite broken.
To change default text colour everywhere in your app using a custom theme, try something like this. Works at least on Android 4.0+ (API level 14+).
res/values/themes.xml
:
<resources>
<style name="MyAppTheme" parent="android:Theme.Holo.Light">
<!-- Change default text colour from dark grey to black -->
<item name="android:textColor">@android:color/black</item>
</style>
</resources>
Manifest:
<application
...
android:theme="@style/MyAppTheme">
A shortcoming with the above is that also disabled Action Bar overflow menu items use the default colour, instead of being greyed out. (Of course, if you don't use disabled menu items anywhere in your app, this may not matter.)
As I learned by asking this question, a better way is to define the colour using a drawable:
<item name="android:textColor">@drawable/default_text_color</item>
...with res/drawable/default_text_color.xml
specifying separate state_enabled="false"
colour:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@android:color/darker_gray"/>
<item android:color="@android:color/black"/>
</selector>
Look at the ScriptManager.RegisterStartupScript method if you're using a ScriptManager or any Ajax controls/asynchronous postbacks.
Edit:
Actually, the function you want is probably ScriptManager.RegisterClientScriptBlock
You can also use a fadeIn/FadeOut Combo, too....
$('.test').bind('click', function(){
$('.div1').fadeIn(500);
$('.div2').fadeOut(500);
$('.div3').fadeOut(500);
return false;
});
I have had a similar issue before trying to determine if something is a string or any sort of number whatsoever. I have tried using a regular expression, but that is not reliable for my use case. Instead, you can check the variable's class to see if it is a descendant of the Numeric class.
if column.class < Numeric
number_to_currency(column)
else
column.html_safe
end
In this situation, you could also substitute for any of the Numeric descendants: BigDecimal, Date::Infinity, Integer, Fixnum, Float, Bignum, Rational, Complex
Actually VBA can be used to compile DLLs. The Office 2000 and Office XP Developer editions included a VBA editor that could be used for making DLLs for use as COM Addins.
This functionality was removed in later versions (2003 and 2007) with the advent of the VSTO (VS Tools for Office) software, although obviously you could still create COM addins in a similar fashion without the use of VSTO (or VS.Net) by using VB6 IDE.
git revert
simply creates a new commit that is the opposite of an existing commit.
It leaves the files in the same state as if the commit that has been reverted never existed. For example, consider the following simple example:
$ cd /tmp/example
$ git init
Initialized empty Git repository in /tmp/example/.git/
$ echo "Initial text" > README.md
$ git add README.md
$ git commit -m "initial commit"
[master (root-commit) 3f7522e] initial commit
1 file changed, 1 insertion(+)
create mode 100644 README.md
$ echo "bad update" > README.md
$ git commit -am "bad update"
[master a1b9870] bad update
1 file changed, 1 insertion(+), 1 deletion(-)
In this example the commit history has two commits and the last one is a mistake. Using git revert:
$ git revert HEAD
[master 1db4eeb] Revert "bad update"
1 file changed, 1 insertion(+), 1 deletion(-)
There will be 3 commits in the log:
$ git log --oneline
1db4eeb Revert "bad update"
a1b9870 bad update
3f7522e initial commit
So there is a consistent history of what has happened, yet the files are as if the bad update never occured:
cat README.md
Initial text
It doesn't matter where in the history the commit to be reverted is (in the above example, the last commit is reverted - any commit can be reverted).
do you have to do something else after?
A git revert
is just another commit, so e.g. push to the remote so that other users can pull/fetch/merge the changes and you're done.
Do you have to commit the changes revert made or does revert directly commit to the repo?
git revert
is a commit - there are no extra steps assuming reverting a single commit is what you wanted to do.
Obviously you'll need to push again and probably announce to the team.
Indeed - if the remote is in an unstable state - communicating to the rest of the team that they need to pull to get the fix (the reverting commit) would be the right thing to do :).
You could just write to the file as you would write any normal file.
with open('csvfile.csv','wb') as file:
for l in text:
file.write(l)
file.write('\n')
If just in case, it is a list of lists, you could directly use built-in csv
module
import csv
with open("csvfile.csv", "wb") as file:
writer = csv.writer(file)
writer.writerows(text)
If you are using Linearlayout. its params should be "wrap_content" to add dynamic data in your layout xml. if you use match or fill parent then you cannot see the output.
It Should be like this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
This will get all files in a directory and remove them.
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
dir = os.path.join(BASE_DIR, "foldername")
for root, dirs, files in os.walk(dir):
for file in files:
path = os.path.join(dir, file)
os.remove(path)
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
I always use a Form Close method in my applications that catches alt + x from my exit Button, alt + f4 or another form closing event was initiated. All my classes have the class name defined as Private string mstrClsTitle = "grmRexcel"
in this case, an Exit method that calls the Form Closing Method and a Form Closing Method. I also have a statement for the Form Closing Method - this.FormClosing = My Form Closing Form Closing method name
.
The code for this:
namespace Rexcel_II
{
public partial class frmRexcel : Form
{
private string mstrClsTitle = "frmRexcel";
public frmRexcel()
{
InitializeComponent();
this.FormClosing += frmRexcel_FormClosing;
}
/// <summary>
/// Handles the Button Exit Event executed by the Exit Button Click
/// or Alt + x
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// Handles the Form Closing event
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void frmRexcel_FormClosing(object sender, FormClosingEventArgs e)
{
// ---- If windows is shutting down,
// ---- I don't want to hold up the process
if (e.CloseReason == CloseReason.WindowsShutDown) return;
{
// ---- Ok, Windows is not shutting down so
// ---- either btnExit or Alt + x or Alt + f4 has been clicked or
// ---- another form closing event was intiated
// *) Confirm user wants to close the application
switch (MessageBox.Show(this,
"Are you sure you want to close the Application?",
mstrClsTitle + ".frmRexcel_FormClosing",
MessageBoxButtons.YesNo, MessageBoxIcon.Question))
{
// ---- *) if No keep the application alive
//---- *) else close the application
case DialogResult.No:
e.Cancel = true;
break;
default:
break;
}
}
}
}
}
Use title
attribute.
It is a standard HTML attribute and is by default rendered in a tooltip by most desktop browsers.
:: short answer :
:: perl -MCPAN -e "install PAR::Packer"
pp -o <<DesiredExeName>>.exe <<MyFancyPerlScript>>
:: long answer - create the following cmd , adjust vars to your taste ...
:: next_line_is_templatized
:: file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
:: disable the echo
@echo off
:: this is part of the name of the file - not used
set _Action=run
:: the name of the Product next_line_is_templatized
set _ProductName=morphus
:: the version of the current Product next_line_is_templatized
set _ProductVersion=1.2.3
:: could be dev , test , dev , prod next_line_is_templatized
set _ProductType=dev
:: who owns this Product / environment next_line_is_templatized
set _ProductOwner=ysg
:: identifies an instance of the tool ( new instance for this version could be created by simply changing the owner )
set _EnvironmentName=%_ProductName%.%_ProductVersion%.%_ProductType%.%_ProductOwner%
:: go the run dir
cd %~dp0
:: do 4 times going up
for /L %%i in (1,1,5) do pushd ..
:: The BaseDir is 4 dirs up than the run dir
set _ProductBaseDir=%CD%
:: debug echo BEFORE _ProductBaseDir is %_ProductBaseDir%
:: remove the trailing \
IF %_ProductBaseDir:~-1%==\ SET _ProductBaseDir=%_ProductBaseDir:~0,-1%
:: debug echo AFTER _ProductBaseDir is %_ProductBaseDir%
:: debug pause
:: The version directory of the Product
set _ProductVersionDir=%_ProductBaseDir%\%_ProductName%\%_EnvironmentName%
:: the dir under which all the perl scripts are placed
set _ProductVersionPerlDir=%_ProductVersionDir%\sfw\perl
:: The Perl script performing all the tasks
set _PerlScript=%_ProductVersionPerlDir%\%_Action%_%_ProductName%.pl
:: where the log events are stored
set _RunLog=%_ProductVersionDir%\data\log\compile-%_ProductName%.cmd.log
:: define a favorite editor
set _MyEditor=textpad
ECHO Check the variables
set _
:: debug PAUSE
:: truncate the run log
echo date is %date% time is %time% > %_RunLog%
:: uncomment this to debug all the vars
:: debug set >> %_RunLog%
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pl /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pm /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: now open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: this is the call without debugging
:: old
echo CFPoint1 OK The run cmd script %0 is executed >> %_RunLog%
echo CFPoint2 OK compile the exe file STDOUT and STDERR to a single _RunLog file >> %_RunLog%
cd %_ProductVersionPerlDir%
pp -o %_Action%_%_ProductName%.exe %_PerlScript% | tee -a %_RunLog% 2>&1
:: open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: uncomment this line to wait for 5 seconds
:: ping localhost -n 5
:: uncomment this line to see what is happening
:: PAUSE
::
:::::::
:: Purpose:
:: To compile every *.pl file into *.exe file under a folder
:::::::
:: Requirements :
:: perl , pp , win gnu utils tee
:: perl -MCPAN -e "install PAR::Packer"
:: text editor supporting <<textEditor>> <<FileNameToOpen>> cmd call syntax
:::::::
:: VersionHistory
:: 1.0.0 --- 2012-06-23 12:05:45 --- ysg --- Initial creation from run_morphus.cmd
:::::::
:: eof file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
According to Wikipedia:
5222 TCP XMPP client connection (RFC 6120) Official 5223 TCP XMPP client connection over SSL Unofficial 5269 TCP XMPP server connection (RFC 6120) Official 5298 TCP UDP XMPP JEP-0174: Link-Local Messaging / Official XEP-0174: Serverless Messaging 8010 TCP XMPP File transfers Unofficial
The port numbers are defined in RFC 6120 § 14.7.
The API does not support that directly. You can use the for(int i..) loop and count the elements or use subLists(0, size - 1) and handle the last element explicitly:
if(x.isEmpty()) return;
int last = x.size() - 1;
for(Integer i : x.subList(0, last)) out.println(i);
out.println("last " + x.get(last));
This is only useful if it does not introduce redundancy. It performs better than the counting version (after the subList overhead is amortized). (Just in case you cared after the boxing anyway).
use checked
: true, false property of the checkbox.
jQuery:
if($('input[type=checkbox]').is(':checked')) {
$(this).prop('checked',true);
} else {
$(this).prop('checked',false);
}
I'm a PHP developer and to be able to work on my development environment with a certificate, I was able to do the same by finding the real SSL HTTPS/HTTP Certificate and deleting it.
The steps are :
You can find more information at : http://classically.me/blogs/how-clear-hsts-settings-major-browsers
Although this solution is not the best, Chrome currently does not have any good solution for the moment. I have escalated this situation with their support team to help improve user experience.
Edit : you have to repeat the steps every time you will go on the production site.
RUN git clone http://username:password@url/example.git
WORKDIR /folder
RUN make
In clean Ubuntu 16.04 LTS, MariaDB root login for localhost changed from password style to sudo login style...
so, just do
sudo mysql -u root
since we want to login with password, create another user 'user'
in MariaDB console... (you get in MariaDB console with 'sudo mysql -u root')
use mysql
CREATE USER 'user'@'localhost' IDENTIFIED BY 'yourpassword';
\q
then in bash shell prompt,
mysql-workbench
and you can login with 'user' with 'yourpassword' on localhost
You can write like this:
span{
margin-left:10px;
}
span:first-child{
margin-left:0;
}
prop.table is a nice friendly way of obtaining proportions of tables.
m <- matrix(1:4,2)
m
[,1] [,2]
[1,] 1 3
[2,] 2 4
Leaving margin blank gives you proportions of the whole table
prop.table(m, margin=NULL)
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
Giving it 1 gives you row proportions
prop.table(m, 1)
[,1] [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667
And 2 is column proportions
prop.table(m, 2)
[,1] [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286
Your sql is incorrect.
$sql = mysql_query("UPDATE anstalld....
only
$sql = "UPDATE anstalld...
Clear your browser cache. Started getting this error in Chrome and then I created a new client id and was still getting the issue. Opened firefox and it worked, so I cleared the cache on Chrome and it started working.
There's no supported way to do this, but won't you have to examine the files related to each installer to figure out how to actually install them after extracting them? Assuming you can spend the time to figure out which command-line applies, here are some candidate parameters that normally allow you to extract an installation.
MSI Based (may not result in a usable image for an InstallScript MSI installation):
setup.exe /a /s /v"/qn TARGETDIR=\"choose-a-location\""
or, to also extract prerequisites (for versions where it works),
setup.exe /a"choose-another-location" /s /v"/qn TARGETDIR=\"choose-a-location\""
InstallScript based:
setup.exe /s /extract_all
Suite based (may not be obvious how to install the resulting files):
setup.exe /silent /stage_only ISRootStagePath="choose-a-location"
I use 3 lines to do this job, so consider $s as your "stuff"...
$s=str_replace(chr(10),'',$s);
$s=str_replace(chr(13),'',$s);
$s=str_replace("\r\n"),'',$s);
My solution to fix that problem was the following:
Start > search > cmd.exe (Run as administrator)
Inside the Command Prompt (cmd.exe) type:
cd c:/wamp/bin/apache/ApacheX.X.X/bin
httpd.exe -e debug
**Note that the ApacheX.X.X is the version of the Apache wamp is running.
This should output what the apache server is doing. The error that causes Apache from loading should be in there. My problem was that httpd.conf was trying to load a DLL that was missing or was corrupted (php5apache2_4.dll). As soon as I overwrote this file, I restarted Wamp and everything ran smooth.
I think this example will definitely help you overlay a transparent image on top of another image. This is made possible by drawing both the images on canvas and returning a bitmap image.
Read more or download demo here
private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){
Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(firstImage, 0f, 0f, null);
canvas.drawBitmap(secondImage, 10, 10, null);
return result;
}
and call the above function on button click and pass the two images to our function as shown below
public void buttonMerge(View view) {
Bitmap bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
Bitmap smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.img2);
Bitmap mergedImages = createSingleImageFromMultipleImages(bigImage, smallImage);
img.setImageBitmap(mergedImages);
}
For more than two images, you can follow this link, how to merge multiple images programmatically on android
✗
✗
✘
✘
✕
✕
✖
✖
Using onBackPressed()
method:
@Override
public void onBackPressed() {
android.os.Process.killProcess(android.os.Process.myPid());
}
or use the finish()
method, I have something like
//Password Error, I call function
Quit();
protected void Quit() {
super.finish();
}
With super.finish() you close the super class's activity.
If you are using a GUI and you are still getting the same problem. Just leave the size value empty, the primary key defaults the value to 11, you should be fine with this. Worked with Bitnami phpmyadmin.
Implement your own extension of DataGridViewTextBoxCell and override Paint method like this:
class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
DataGridViewElementStates cellState, object value, object formattedValue, string errorText,
DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
if (value != null)
{
if ((bool) value)
{
cellStyle.BackColor = Color.LightGreen;
}
else
{
cellStyle.BackColor = Color.OrangeRed;
}
}
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}
}
Then in the code set CellTemplate property of your column to instance of your class
columns.Add(new DataGridViewTextBoxColumn() {CellTemplate = new MyDataGridViewTextBoxCell()});
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
. "$PSScriptRoot\MyFunctions.ps1"
MyA1Func
Availalbe starting in v3, before that see How can I get the file system location of a PowerShell script?. It is VERY common.
P.S. I don't subscribe to the 'everything is a module' rule. My scripts are used by other developers out of GIT, so I don't like to put stuff in specific a place or modify system environment variables before my script will run. It's just a script (or two, or three).
Try using the WebConfigurationManager class instead. For example:
string userName = WebConfigurationManager.AppSettings["PFUserName"]
Interesting problem. I'm guessing you just want to trigger some process or action on the other server, but don't care what the results are and want your script to continue. There is probably something in cURL that can make this happen, but you may want to consider using exec()
to run another script on the server that does the call if cURL can't do it. (Typically people want the results of the script call so I'm not sure if PHP has the ability to just trigger the process.) With exec()
you could run a wget
or even another PHP script that makes the request with file_get_conents()
.
I saw a presentation on mongodb yesterday. I can definitely say that setup was "simple", as simple as unpacking it and firing it up. Done.
I believe that both mongodb and cassandra will run on virtually any regular linux hardware so you should not find to much barrier in that area.
I think in this case, at the end of the day, it will come down to which do you personally feel more comfortable with and which has a toolset that you prefer. As far as the presentation on mongodb, the presenter indicated that the toolset for mongodb was pretty light and that there werent many (they said any really) tools similar to whats available for MySQL. This was of course their experience so YMMV. One thing that I did like about mongodb was that there seemed to be lots of language support for it (Python, and .NET being the two that I primarily use).
The list of sites using mongodb is pretty impressive, and I know that twitter just switched to using cassandra.
private List<Item> cloneItemList(final List<Item> items)
{
Item[] itemArray = new Item[items.size()];
itemArray = items.toArray(itemArray);
return Arrays.asList(itemArray);
}
Please enter domain nginx file :
nano /etc/nginx/sites-available/domain.set
Add to file this code
client_max_body_size 24000M;
If you get error use this command
nginx -t
According to Oracle integration of OpenJDK & javaFX will be on Q1-2014 ( see roadmap : http://www.oracle.com/technetwork/java/javafx/overview/roadmap-1446331.html ). So, for the 1st question the answer is that you have to wait until then. For the 2nd question there is no other way. So, for now go with java swing or start javaFX and wait
The non-greedy ?
works perfectly fine. It's just that you need to select dot matches all option in the regex engines (regexpal, the engine you used, also has this option) you are testing with. This is because, regex engines generally don't match line breaks when you use .
. You need to tell them explicitly that you want to match line-breaks too with .
For example,
<img\s.*?>
works fine!
Check the results here.
Also, read about how dot behaves in various regex flavours.
Just return an object literal
function newCodes(){
var dCodes = fg.codecsCodes.rs; // Linked ICDs
var dCodes2 = fg.codecsCodes2.rs; //Linked CPTs
return {
dCodes: dCodes,
dCodes2: dCodes2
};
}
var result = newCodes();
alert(result.dCodes);
alert(result.dCodes2);
You can execute the following commands
lsof / |grep deleted
kill the process id's, which free up the disk space.
Since PHP 7.3 the hrtime function should be used for any timing.
$start = hrtime(true);
// execute...
$end = hrtime(true);
echo ($end - $start); // Nanoseconds
echo ($end - $start) / 1000000000; // Seconds
The mentioned microtime function relies on the system clock. Which can be modified e.g. by the ntpd program on ubuntu or just the sysadmin.
The problem is your angular material version, I have the same, and I have resolved this when I have installed the good version of angular material in local.
Hope it solve yours too.
Map
is an interface; HashMap
is a particular implementation of that interface.
HashMap uses a collection of hashed key values to do its lookup. TreeMap will use a red-black tree as its underlying data store.
I have resolved it , this way
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateParser {
public static void main(String args[]) throws Exception {
DateParser dateParser = new DateParser();
String str = dateParser.getparsedDate("2012-11-17T00:00:00.000-05:00");
System.out.println(str);
}
private String getparsedDate(String date) throws Exception {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
String s1 = date;
String s2 = null;
Date d;
try {
d = sdf.parse(s1);
s2 = (new SimpleDateFormat("MM/yyyy")).format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return s2;
}
}
You could try scraping whatever you need with PHP or another server side language, then put the iframe to the scraped content. Here's an example with PHP:
scrapedcontent.php:
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
index.html:
<iframe src="scrapedcontent.php"></iframe>
yourarray.shape
or np.shape()
or np.ma.shape()
returns the shape of your ndarray as a tuple; And you can get the (number of) dimensions of your array using yourarray.ndim
or np.ndim()
. (i.e. it gives the n
of the ndarray
since all arrays in NumPy are just n-dimensional arrays (shortly called as ndarray
s))
For a 1D array, the shape would be (n,)
where n
is the number of elements in your array.
For a 2D array, the shape would be (n,m)
where n
is the number of rows and m
is the number of columns in your array.
Please note that in 1D case, the shape would simply be (n, )
instead of what you said as either (1, n)
or (n, 1)
for row and column vectors respectively.
This is to follow the convention that:
For 1D array, return a shape tuple with only 1 element (i.e. (n,)
)
For 2D array, return a shape tuple with only 2 elements (i.e. (n,m)
)
For 3D array, return a shape tuple with only 3 elements (i.e. (n,m,k)
)
For 4D array, return a shape tuple with only 4 elements (i.e. (n,m,k,j)
)
and so on.
Also, please see the example below to see how np.shape()
or np.ma.shape()
behaves with 1D arrays and scalars:
# sample array
In [10]: u = np.arange(10)
# get its shape
In [11]: np.shape(u) # u.shape
Out[11]: (10,)
# get array dimension using `np.ndim`
In [12]: np.ndim(u)
Out[12]: 1
In [13]: np.shape(np.mean(u))
Out[13]: () # empty tuple (to indicate that a scalar is a 0D array).
# check using `numpy.ndim`
In [14]: np.ndim(np.mean(u))
Out[14]: 0
P.S.: So, the shape tuple is consistent with our understanding of dimensions of space, at least mathematically.
You can use urllib2
import urllib2
content = urllib2.urlopen(some_url).read()
print content
Also you can use httplib
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK
or the requests library
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200
check if tun/tap enabled:
cat /dev/net/tun
if ok will see something :
cat: /dev/net/tun: File descriptor in bad state
To find a very long list of words in big files, it can be more efficient to use egrep:
remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B
The following works on 2008R2+ to produce 'HH:MM':
select
case
when len(replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')) = 4
then '0'+ replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')
else replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','') end as [Time]
You can use a serialize() function of JQuery:
var datastring = $("#preview_form").serialize();
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
success: function(data) {
alert('Data send');
}
});
And read in PHP:
echo $_POST['datastring']['dialog_box_textarea_1'];
echo $_POST['datastring']['radiobutton_1'];
........
And get ***data-**** to tag HTML5 you can see this example:
<div id="texto" data-author="Ricardo Miranda" data-date="2012-06-21">
<h4>Lorem ipsum</h4>
<p>
Lorem ipsum dolor sit amet, ius integre eligendi et,
sea ut expetendis conclusionemque,
mel at ornatus invenire. His ad moderatius definiebas omittantur,
liber saepe albucius sea cu.
Audire tamquam dolores vis ne, mediocrem consulatu eum ex.
Duo te agam saepe convenire, et fugit iisque his.
</p>
<script type="text/javascript">
$(function() {
alert("The text is write " + $('#texto').data('author'));
});
And
<div id="texto" data-author='{"nombre":"Ricardo","apellido":"Miranda"}' data-date="2012-06-21">
...
</div>
<script type="text/javascript">
$(function() {
alert("The text is write " + $('#texto').data('author').apellido + ", " +
('#texto').data('author').nombre);
});
</script>
Get a handle to the root layout used, then set the background color on that. The root layout is whatever you called setContentView with.
setContentView(R.layout.main);
// Now get a handle to any View contained
// within the main layout you are using
View someView = findViewById(R.id.randomViewInMainLayout);
// Find the root view
View root = someView.getRootView();
// Set the color
root.setBackgroundColor(getResources().getColor(android.R.color.red));
To get the separator vertically centered relative to the menu text,
.menustyle li + li:before {
content: ' | ';
padding: 0;
position: relative;
top: -2px;
}
Try this way:
<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>
select
helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options
.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select
All upvoted answers above are correct. This is just simplest version:
private string Serialize(Object o)
{
using (var writer = new StringWriter())
{
new XmlSerializer(o.GetType()).Serialize(writer, o);
return writer.ToString();
}
}
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
String localFormat = android.text.format.DateFormat.getBestDateTimePattern(Locale.getDefault(), "EEEE MMMM d");
return new SimpleDateFormat(localFormat, Locale.getDefault()).format(localMidnight);
will return a format based on device's language. Note that getBestDateTimePattern() returns "the best possible localized form of the given skeleton for the given locale"
I had the same issue with numeral, a JS library. The fix was to install the typings again with this command:
npm install --save @types/numeral
For a field separator of any number 2
through 5
or letter a
or #
or a space, where the separating character must be repeated at least 2 times and not more than 6 times, for example:
awk -F'[2-5a# ]{2,6}' ...
I am sure variations of this exist using ( ) and parameters
Simplest solution would be -
$('.selectpicker').trigger('change');
For anyone stumbling across the same issue:
I fixed the problem by cloning the repo again at another location. I then copied my whole src dir (without .git dir obviously) from the corrupted repo into the freshly cloned repo. Thus I had all the recent changes and a clean and working repository.
<input id="typeahead-input" type="text" data-provide="typeahead" />
<script type="text/javascript">
var data = ["Aamir", "Amol", "Ayesh", "Sameera", "Sumera", "Kajol", "Kamal",
"Akash", "Robin", "Roshan", "Aryan"];
$(function() {
$('#typeahead-input').typeahead({
source: function (query, process) {
process(data);
});
}
});
});
</script>
Another form that works with Postgres 9.1+ is combining a Common Table Expression with the USING statement for the join.
WITH prod AS (select m_product_id, upc from m_product where upc='7094')
DELETE FROM m_productprice B
USING prod C
WHERE B.m_product_id = C.m_product_id
AND B.m_pricelist_version_id = '1000020';
If you want the powershell errormessage for a cmdlet suppressed, but still want to catch the error, use "-erroraction 'silentlyStop'"
For me it was under:
/Users/{your username}/Library/Developer/Xcode/DerivedData...
and NOT in /Library/Developer/Xcode/DerivedData...
You can do this today in Java with the Red5 media server from Flash. If you want to also decode and encode video in Java, you can use the Xuggler project.
I also encountered this issue, for my case, it's because I upgrade my IntelliJ IDEA without upgrading the Lombok plugin. So they are incompatible.
%>%
is similar to pipe in Unix. For example, in
a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()
the output of combined_data_set
will go into group_by
and its output will go into tally
, then the final output is assigned to a
.
This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.
Lets say ClassOne
is defined as:
public class ClassOne
{
protected $arg1;
protected $arg2;
//Contructor
public function __construct($arg1, $arg2)
{
$this->arg1 = $arg1;
$this->arg2 = $arg2;
}
public function echoArgOne
{
echo $this->arg1;
}
}
Using PHP Reflection;
$str = "One";
$className = "Class".$str;
$class = new \ReflectionClass($className);
Create a new Instance:
$instance = $class->newInstanceArgs(["Banana", "Apple")]);
Call a method:
$instance->echoArgOne();
//prints "Banana"
Use a variable as a method:
$method = "echoArgOne";
$instance->$method();
//prints "Banana"
Using Reflection instead of just using the raw string to create an object gives you better control over your object and easier testability (PHPUnit relies heavily on Reflection)
If you don't want to install MySQL workbench, and are looking for an online tool, this might help: http://ondras.zarovi.cz/sql/demo/
I use it quite often to create simple DB schemas for various apps I build.
I assume that there exist some internal psql command for this, but you could also run the script
command from util-linux-ng package:
DESCRIPTION Script makes a typescript of everything printed on your terminal.
No, it will not be faster on most architectures. You didn't specify, but on x86, all of the integral comparisons will be typically implemented in two machine instructions:
test
or cmp
instruction, which sets EFLAGS
Jcc
(jump) instruction, depending on the comparison type (and code layout):
jne
- Jump if not equal --> ZF = 0
jz
- Jump if zero (equal) --> ZF = 1
jg
- Jump if greater --> ZF = 0 and SF = OF
Example (Edited for brevity) Compiled with $ gcc -m32 -S -masm=intel test.c
if (a < b) {
// Do something 1
}
Compiles to:
mov eax, DWORD PTR [esp+24] ; a
cmp eax, DWORD PTR [esp+28] ; b
jge .L2 ; jump if a is >= b
; Do something 1
.L2:
And
if (a <= b) {
// Do something 2
}
Compiles to:
mov eax, DWORD PTR [esp+24] ; a
cmp eax, DWORD PTR [esp+28] ; b
jg .L5 ; jump if a is > b
; Do something 2
.L5:
So the only difference between the two is a jg
versus a jge
instruction. The two will take the same amount of time.
I'd like to address the comment that nothing indicates that the different jump instructions take the same amount of time. This one is a little tricky to answer, but here's what I can give: In the Intel Instruction Set Reference, they are all grouped together under one common instruction, Jcc
(Jump if condition is met). The same grouping is made together under the Optimization Reference Manual, in Appendix C. Latency and Throughput.
Latency — The number of clock cycles that are required for the execution core to complete the execution of all of the µops that form an instruction.
Throughput — The number of clock cycles required to wait before the issue ports are free to accept the same instruction again. For many instructions, the throughput of an instruction can be significantly less than its latency
The values for Jcc
are:
Latency Throughput
Jcc N/A 0.5
with the following footnote on Jcc
:
7) Selection of conditional jump instructions should be based on the recommendation of section Section 3.4.1, “Branch Prediction Optimization,” to improve the predictability of branches. When branches are predicted successfully, the latency of
jcc
is effectively zero.
So, nothing in the Intel docs ever treats one Jcc
instruction any differently from the others.
If one thinks about the actual circuitry used to implement the instructions, one can assume that there would be simple AND/OR gates on the different bits in EFLAGS
, to determine whether the conditions are met. There is then, no reason that an instruction testing two bits should take any more or less time than one testing only one (Ignoring gate propagation delay, which is much less than the clock period.)
Edit: Floating Point
This holds true for x87 floating point as well: (Pretty much same code as above, but with double
instead of int
.)
fld QWORD PTR [esp+32]
fld QWORD PTR [esp+40]
fucomip st, st(1) ; Compare ST(0) and ST(1), and set CF, PF, ZF in EFLAGS
fstp st(0)
seta al ; Set al if above (CF=0 and ZF=0).
test al, al
je .L2
; Do something 1
.L2:
fld QWORD PTR [esp+32]
fld QWORD PTR [esp+40]
fucomip st, st(1) ; (same thing as above)
fstp st(0)
setae al ; Set al if above or equal (CF=0).
test al, al
je .L5
; Do something 2
.L5:
leave
ret
Try this :
$('body, html').css('overflow', 'hidden');
var screenWidth1 = $(window).width();
$('body, html').css('overflow', 'visible');
var screenWidth2 = $(window).width();
alert(screenWidth1); // Gives the screenwith without scrollbar
alert(screenWidth2); // Gives the screenwith including scrollbar
You can get the screen width by with and without scroll bar by using this code.
Here, I have changed the overflow value of body
and get the width with and without scrollbar.
Swift 5.2
The only method I found to work and refresh a view dynamically where the visibility of buttons had changed was:-
viewWillAppear(true)
This may be a bad practice but hopefully somebody will leave a comment.
In the html file:
<input type="text" placeholder="placeholder" class="redPlaceHolder">
In the css file:
.redPlaceHolder{
color: #ff0000;
}
Yup, this is possible of course. Here are several examples.
-- one way to do this
DECLARE @Cnt int
SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn
-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)
-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double
SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable
One line working answer:
$url = "http://www.yoursite/one/two/three/drink";
echo $end = end((explode('/', $url)));
Output: drink
This is useful when you have your own origin
which is not upstream
. In other words, you might have your own origin
repo that you do development and local changes in and then occasionally merge upstream
changes. The difference between your example and the highlighted text is that your example assumes you're working with a clone of the upstream repo directly. The highlighted text assumes you're working on a clone of your own repo that was, presumably, originally a clone of upstream.
Wanna a list of folder in xampp?
Just delete or change the file index.php to index.txt. And you will get the list just typing url: localhost.
Try This
SELECT f.*
FROM first_table f LEFT JOIN second_table s ON f.key=s.key
WHERE s.key is NULL
For more please read this article : Joins in Sql Server
If you really want to handle with HTTP using Python, I highly recommend Requests: HTTP for Humans. The POST quickstart adapted to your question is:
>>> import requests
>>> r = requests.post("http://bugs.python.org", data={'number': 12524, 'type': 'issue', 'action': 'show'})
>>> print(r.status_code, r.reason)
200 OK
>>> print(r.text[:300] + '...')
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Issue 12524: change httplib docs POST example - Python tracker
</title>
<link rel="shortcut i...
>>>
You'll want to include double quotes (") before and after the imageUrl like this:
$('myOjbect').css('background-image', 'url("' + imageUrl + '")');
This way, if the image has spaces it will still be set as a property.
Does this work without alternation?
^((part)1(, \22)?)?(part2)?$
or why not this?
^((part)1(, (\22))?)?(\4)?$
The first works for all conditions the second for all but part2
(using GNU sed 4.1.5)
ActionBar actionBar = getActionBar();
actionBar.setTitle("");
Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.
Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.
In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.
Option Explicit
Sub test()
Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A1:IV65536"
' If you know the data will only be in a smaller range, reduce the size of the ranges above.
Debug.Print Now
varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
Debug.Print Now
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
' Cells are identical.
' Do nothing.
Else
' Cells are different.
' Code goes here for whatever it is you want to do.
End If
Next iCol
Next iRow
End Sub
To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:
Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need
You can try to restore your previous state by doing the following:
Different Ways to Print Arrays in Java:
Simple Way
List<String> list = new ArrayList<String>();
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
// Print the list in console
System.out.println(list);
Output: [One, Two, Three, Four]
Using toString()
String[] array = new String[] { "One", "Two", "Three", "Four" };
System.out.println(Arrays.toString(array));
Output: [One, Two, Three, Four]
Printing Array of Arrays
String[] arr1 = new String[] { "Fifth", "Sixth" };
String[] arr2 = new String[] { "Seventh", "Eight" };
String[][] arrayOfArray = new String[][] { arr1, arr2 };
System.out.println(arrayOfArray);
System.out.println(Arrays.toString(arrayOfArray));
System.out.println(Arrays.deepToString(arrayOfArray));
Output: [[Ljava.lang.String;@1ad086a [[Ljava.lang.String;@10385c1, [Ljava.lang.String;@42719c] [[Fifth, Sixth], [Seventh, Eighth]]
Resource: Access An Array
Here's a list of keycodes that includes a way to look them up interactively.
You probably have a forward declaration of the class, but haven't included the header:
#include <sstream>
//...
QString Stats_Manager::convertInt(int num)
{
std::stringstream ss; // <-- also note namespace qualification
ss << num;
return ss.str();
}
Try this:
window.open(this.url+'/create-account')
No need to use '_blank'
. window.open
by default opens a link in a new tab.
Easy as this, that worked for my project
composer install
php artisan serve
datas.Where((data, index) =>
{
//Your Logic
return false;
}).Any();
In some simple case,my way is using where + false + any
.
It is fater a little than foreach + select((data,index)=>new{data,index})
,and without custom Foreach method.
MyLogic:
- use statement body run your logic.
- because return false,new Enumrable data count is zero.
- use Any() let yeild run.
[RPlotExporter, RankColumn]
public class BenchmarkTest
{
public static IEnumerable<dynamic> TestDatas = Enumerable.Range(1, 10).Select((data, index) => $"item_no_{index}");
[Benchmark]
public static void ToArrayAndFor()
{
var datats = TestDatas.ToArray();
for (int index = 0; index < datats.Length; index++)
{
var result = $"{datats[index]}{index}";
}
}
[Benchmark]
public static void IEnumrableAndForach()
{
var index = 0;
foreach (var item in TestDatas)
{
index++;
var result = $"{item}{index}";
}
}
[Benchmark]
public static void LinqSelectForach()
{
foreach (var item in TestDatas.Select((data, index) => new { index, data }))
{
var result = $"{item.data}{item.index}";
}
}
[Benchmark]
public static void LinqSelectStatementBodyToList()
{
TestDatas.Select((data, index) =>
{
var result = $"{data}{index}";
return true;
}).ToList();
}
[Benchmark]
public static void LinqSelectStatementBodyToArray()
{
TestDatas.Select((data, index) =>
{
var result = $"{data}{index}";
return true;
}).ToArray();
}
[Benchmark]
public static void LinqWhereStatementBodyAny()
{
TestDatas.Where((data, index) =>
{
var result = $"{data}{index}";
return false;
}).Any();
}
}
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<BenchmarkTest>();
System.Console.Read();
}
}
Method | Mean | Error | StdDev | Rank |
------------------------------- |---------:|----------:|----------:|-----:|
ToArrayAndFor | 4.027 us | 0.0797 us | 0.1241 us | 4 |
IEnumrableAndForach | 3.494 us | 0.0321 us | 0.0285 us | 1 |
LinqSelectForach | 3.842 us | 0.0503 us | 0.0471 us | 3 |
LinqSelectStatementBodyToList | 3.822 us | 0.0416 us | 0.0389 us | 3 |
LinqSelectStatementBodyToArray | 3.857 us | 0.0764 us | 0.0785 us | 3 |
LinqWhereStatementBodyAny | 3.643 us | 0.0693 us | 0.0712 us | 2 |
I wanted to use JavaScript to change a form's action, so I could have different submit inputs within the same form linking to different pages.
I also had the added complication of using Apache rewrite to change example.com/page-name
into example.com/index.pl?page=page-name
. I found that changing the form's action caused example.com/index.pl
(with no page parameter) to be rendered, even though the expected URL (example.com/page-name
) was displayed in the address bar.
To get around this, I used JavaScript to insert a hidden field to set the page parameter. I still changed the form's action, just so the address bar displayed the correct URL.
function setAction (element, page)
{
if(checkCondition(page))
{
/* Insert a hidden input into the form to set the page as a parameter.
*/
var input = document.createElement("input");
input.setAttribute("type","hidden");
input.setAttribute("name","page");
input.setAttribute("value",page);
element.form.appendChild(input);
/* Change the form's action. This doesn't chage which page is displayed,
* it just make the URL look right.
*/
element.form.action = '/' + page;
element.form.submit();
}
}
In the form:
<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />
Here are my Apache rewrite rules:
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}
I'd be interested in any explanation as to why just setting the action didn't work.
React Portals can let you render to elements outside the root React node (such at <title>
), as if they were actual React nodes. So now you can set the title cleanly and without any additional dependencies:
Here's an example:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Title extends Component {
constructor(props) {
super(props);
this.titleEl = document.getElementsByTagName("title")[0];
}
render() {
let fullTitle;
if(this.props.pageTitle) {
fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
} else {
fullTitle = this.props.siteTitle;
}
return ReactDOM.createPortal(
fullTitle || "",
this.titleEl
);
}
}
Title.defaultProps = {
pageTitle: null,
siteTitle: "Your Site Name Here",
};
export default Title;
Just put the component in the page and set pageTitle
:
<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />
i made my own utils. it is handy. :)
package samples.utils;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.ui.context.Theme;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.support.RequestContextUtils;
/**
* SpringMVC????
*
* @author ??([email protected])
*
*/
public final class WebContextHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(WebContextHolder.class);
private static WebContextHolder INSTANCE = new WebContextHolder();
public WebContextHolder get() {
return INSTANCE;
}
private WebContextHolder() {
super();
}
// --------------------------------------------------------------------------------------------------------------
public HttpServletRequest getRequest() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return attributes.getRequest();
}
public HttpSession getSession() {
return getSession(true);
}
public HttpSession getSession(boolean create) {
return getRequest().getSession(create);
}
public String getSessionId() {
return getSession().getId();
}
public ServletContext getServletContext() {
return getSession().getServletContext(); // servlet2.3
}
public Locale getLocale() {
return RequestContextUtils.getLocale(getRequest());
}
public Theme getTheme() {
return RequestContextUtils.getTheme(getRequest());
}
public ApplicationContext getApplicationContext() {
return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
}
public ApplicationEventPublisher getApplicationEventPublisher() {
return (ApplicationEventPublisher) getApplicationContext();
}
public LocaleResolver getLocaleResolver() {
return RequestContextUtils.getLocaleResolver(getRequest());
}
public ThemeResolver getThemeResolver() {
return RequestContextUtils.getThemeResolver(getRequest());
}
public ResourceLoader getResourceLoader() {
return (ResourceLoader) getApplicationContext();
}
public ResourcePatternResolver getResourcePatternResolver() {
return (ResourcePatternResolver) getApplicationContext();
}
public MessageSource getMessageSource() {
return (MessageSource) getApplicationContext();
}
public ConversionService getConversionService() {
return getBeanFromApplicationContext(ConversionService.class);
}
public DataSource getDataSource() {
return getBeanFromApplicationContext(DataSource.class);
}
public Collection<String> getActiveProfiles() {
return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());
}
public ClassLoader getBeanClassLoader() {
return ClassUtils.getDefaultClassLoader();
}
private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
try {
return getApplicationContext().getBean(requiredType);
} catch (NoUniqueBeanDefinitionException e) {
LOGGER.error(e.getMessage(), e);
throw e;
} catch (NoSuchBeanDefinitionException e) {
LOGGER.warn(e.getMessage());
return null;
}
}
}
I used something that resembles singleton pattern:
function myclass() = {
var instance = this;
this.Days = function() {
var days = ["Piatek", "Sobota", "Niedziela"];
return days;
}
this.EventTime = function(day, hours, minutes) {
this.Day = instance.Days()[day];
this.Hours = hours;
this.minutes = minutes;
this.TotalMinutes = day*24*60 + 60*hours + minutes;
}
}
You have to enable mod_rewrite in apache to make clean urls to work
if mod_rewrite is not in phpinfo you have to install it by
sudo a2enmod rewrite
sudo apache2ctl -l
You need to replace the occurrence of AllowOverride none
to AllowOverride all
( in /etc/apache2/sites-enabled/000-default)
Restart Apache
sudo service apache2 restart
In Magento’s admin go to System > Configuration > Web > search engine Optimization
and change “Use Web Server Rewrites
” to Yes
Yet another way in Python 3:
s.__iter__().__next__()
You could use the CSS calc
parameter to calculate the height dynamically like so:
.dynamic-height {_x000D_
color: #000;_x000D_
font-size: 12px;_x000D_
margin-top: calc(100% - 10px);_x000D_
text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
If you are getting this error on GitLab CI like me: Just change from latest to 5.7 version ;)
# .gitlab-ci.yml
rspec:
services:
# - mysql:latest (I'm using latest version and it causes error)
- mysql:5.7 #(then I've changed to this specific version and fix!)
In C and C++ and many languages, %
is the remainder NOT the modulus operator.
For example in the operation -21 / 4
the integer part is -5
and the decimal part is -.25
. The remainder is the fractional part times the divisor, so our remainder is -1
. JavaScript uses the remainder operator and confirms this
console.log(-21 % 4 == -1);
_x000D_
The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.
Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.
I found this extension for VS 2013 Vitevic GAC Reference.
There would be another way to do this:
var begin = moment().format("YYYY-MM-01");
var end = moment().format("YYYY-MM-") + moment().daysInMonth();
It happens because of not very straight forward Servlet specification. If you are working with a native HttpServletRequest
implementation you cannot get both the URL encode body and the parameters. Spring does some workarounds, which make it even more strange and nontransparent.
In such cases Spring (version 3.2.4) re-renders a body for you using data from the getParameterMap()
method. It mixes GET and POST parameters and breaks the parameter order. The class, which is responsible for the chaos is ServletServerHttpRequest
. Unfortunately it cannot be replaced, but the class StringHttpMessageConverter
can be.
The clean solution is unfortunately not simple:
StringHttpMessageConverter
. Copy/Overwrite the original class adjusting method readInternal()
.HttpServletRequest
overwriting getInputStream()
, getReader()
and getParameter*()
methods.In the method StringHttpMessageConverter#readInternal following code must be used:
if (inputMessage instanceof ServletServerHttpRequest) {
ServletServerHttpRequest oo = (ServletServerHttpRequest)inputMessage;
input = oo.getServletRequest().getInputStream();
} else {
input = inputMessage.getBody();
}
Then the converter must be registered in the context.
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true/false">
<bean class="my-new-converter-class"/>
</mvc:message-converters>
</mvc:annotation-driven>
The step two is described here: Http Servlet request lose params from POST body after read it once
Personally, I couldn't use try/except KeyboardInterrupt because I was using standard socket (IPC) mode which is blocking. So the SIGINT was cueued, but came only after receiving data on the socket.
Setting a signal handler behaves the same.
On the other hand, this only works for an actual terminal. Other starting environments might not accept Ctrl+C, or pre-handle the signal.
Also, there are "Exceptions" and "BaseExceptions" in Python, which differ in the sense that interpreter needs to exit cleanly itself, so some exceptions have a higher priority than others (Exceptions is derived from BaseException)
I have written a simple component using jQuery and bootstrap. Give it a try: https://github.com/mahpour/bootstrap-input-clear-button
Is there a reason you're using Nullable
?
If you want to use Nullable
then you can write variable.Value.TotalHours
.
Or you can just write: (datevalue1 - datevalue2).TotalHours
.
You can use momentjs duration object
Example:
const diff = moment.duration(Date.now() - new Date(2010, 1, 1))
console.log(`${diff.years()} years ${diff.months()} months ${diff.days()} days ${diff.hours()} hours ${diff.minutes()} minutes and ${diff.seconds()} seconds`)
Infinite view pager by overriding 4 adapter methods in your existing adapter class
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public CharSequence getPageTitle(int position) {
String title = mTitleList.get(position % mActualTitleListSize);
return title;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
int virtualPosition = position % mActualTitleListSize;
return super.instantiateItem(container, virtualPosition);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
int virtualPosition = position % mActualTitleListSize;
super.destroyItem(container, virtualPosition, object);
}
I'm unable to reproduce your problem but have you tried converting it to an integer first?
image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
Then, regarding your more general question you could use map
(as in this answer). In your case:
image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)
List<WebElement> myElements = driver.findElements(By.xpath("some/path//a"));
System.out.println("Size of List: "+myElements.size());
for(WebElement e : myElements)
{
System.out.print("Text within the Anchor tab"+e.getText()+"\t");
System.out.println("Anchor: "+e.getAttribute("href"));
}
//NOTE: "//a" will give you all the anchors there on after the point your XPATH has reached.
The other answers seemed more complicated than necessary so I adapted their answers to this short and sweet function.
function allowOnlyNumbers(event) {
if (event.key.length === 1 && /\D/.test(event.key)) {
event.preventDefault();
}
}
It won't do change the behavior of any arrow, enter, shift, ctrl or tab keys because the length of the key property for those events is longer than a single character. It also uses a simple regular expressions to look for any non digit character.
I use
chartRange = xlWorkSheet.Rows[1];
chartRange.Font.Bold = true;
to turn the first-row-cells-font into bold. And it works, and I am using also Excel 2007.
You can call in VBA directly
ActiveCell.Font.Bold = True
With this code I create a timestamp in the active cell, with bold font and yellow background
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveCell.Value = Now()
ActiveCell.Font.Bold = True
ActiveCell.Interior.ColorIndex = 6
End Sub
switch (device_id)
{
#ifndef PROD_1
#ifndef PROD_2
#ifdef PROD_3
case ID_1:
#endif
#ifdef PROD_4
#ifdef PROD_5
case ID_2:
case ID_3:
case ID_4:
#elif defined(PROD_4)
#ifndef PROD_6
case ID_1:
#endif // PROD_6
case ID_5:
#endif
case ID_6:
#endif
#ifdef PROD_7
#ifndef PROD_8
case ID_7:
#endif
#endif
(names changed to protect the not so innocent)
Notice that we haven't even gotten to any code yet, this is just to get to the first actual bit of code. This actually happens (in almost, but not exactly the same way) for several functions, each of which, in the end only have 4 possible variations (which are also mostly copy/paste with slight variations and #ifdefs of their own).
you can use jQuery selectbox replacement. It's a jQuery plugin.
http://cssglobe.com/post/8802/custom-styling-of-the-select-elements
The Pure-css http://bavotasan.com/2011/style-select-box-using-only-css/
How do I print a
double
value with full precision using cout?
Use hexfloat
or
use scientific
and set the precision
std::cout.precision(std::numeric_limits<double>::max_digits10 - 1);
std::cout << std::scientific << 1.0/7.0 << '\n';
// C++11 Typical output
1.4285714285714285e-01
Too many answers address only one of 1) base 2) fixed/scientific layout or 3) precision. Too many answers with precision do not provide the proper value needed. Hence this answer to a old question.
A double
is certainly encoded using base 2. A direct approach with C++11 is to print using std::hexfloat
.
If a non-decimal output is acceptable, we are done.
std::cout << "hexfloat: " << std::hexfloat << exp (-100) << '\n';
std::cout << "hexfloat: " << std::hexfloat << exp (+100) << '\n';
// output
hexfloat: 0x1.a8c1f14e2af5dp-145
hexfloat: 0x1.3494a9b171bf5p+144
fixed
or scientific
?A double
is a floating point type, not fixed point.
Do not use std::fixed
as that fails to print small double
as anything but 0.000...000
. For large double
, it prints many digits, perhaps hundreds of questionable informativeness.
std::cout << "std::fixed: " << std::fixed << exp (-100) << '\n';
std::cout << "std::fixed: " << std::fixed << exp (+100) << '\n';
// output
std::fixed: 0.000000
std::fixed: 26881171418161356094253400435962903554686976.000000
To print with full precision, first use std::scientific
which will "write floating-point values in scientific notation". Notice the default of 6 digits after the decimal point, an insufficient amount, is handled in the next point.
std::cout << "std::scientific: " << std::scientific << exp (-100) << '\n';
std::cout << "std::scientific: " << std::scientific << exp (+100) << '\n';
// output
std::scientific: 3.720076e-44
std::scientific: 2.688117e+43
A double
encoded using the binary base 2 encodes the same precision between various powers of 2. This is often 53 bits.
[1.0...2.0) there are 253 different double
,
[2.0...4.0) there are 253 different double
,
[4.0...8.0) there are 253 different double
,
[8.0...10.0) there are 2/8 * 253 different double
.
Yet if code prints in decimal with N
significant digits, the number of combinations [1.0...10.0) is 9/10 * 10N.
Whatever N
(precision) is chosen, there will not be a one-to-one mapping between double
and decimal text. If a fixed N
is chosen, sometimes it will be slightly more or less than truly needed for certain double
values. We could error on too few (a)
below) or too many (b)
below).
3 candidate N
:
a) Use an N
so when converting from text-double
-text we arrive at the same text for all double
.
std::cout << dbl::digits10 << '\n';
// Typical output
15
b) Use an N
so when converting from double
-text-double
we arrive at the same double
for all double
.
// C++11
std::cout << dbl::max_digits10 << '\n';
// Typical output
17
When max_digits10
is not available, note that due to base 2 and base 10 attributes, digits10 + 2 <= max_digits10 <= digits10 + 3
, we can use digits10 + 3
to insure enough decimal digits are printed.
c) Use an N
that varies with the value.
This can be useful when code wants to display minimal text (N == 1
) or the exact value of a double
(N == 1000-ish
in the case of denorm_min
). Yet since this is "work" and not likely OP's goal, it will be set aside.
It is usually b) that is used to "print a double
value with full precision". Some applications may prefer a) to error on not providing too much information.
With .scientific
, .precision()
sets the number of digits to print after the decimal point, so 1 + .precision()
digits are printed. Code needs max_digits10
total digits so .precision()
is called with a max_digits10 - 1
.
typedef std::numeric_limits< double > dbl;
std::cout.precision(dbl::max_digits10 - 1);
std::cout << std::scientific << exp (-100) << '\n';
std::cout << std::scientific << exp (+100) << '\n';
// Typical output
3.7200759760208361e-44
2.6881171418161356e+43
//1234567890123456 17 total digits
The right way for Select2 3.x is:
$('select').select2("enable", false)
This works fine.
I had the same problem with Visual Studio 2008 and solved adding the following event handler to the textbox:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 'a') && (e.KeyChar <= 'z'))
{
int iPos = textBox1.SelectionStart;
int iLen = textBox1.SelectionLength;
textBox1.Text = textBox1.Text.Remove(iPos, iLen).Insert(iPos, Char.ToUpper(e.KeyChar).ToString());
textBox1.SelectionStart = iPos + 1;
e.Handled = true;
}
}
It works even if you type a lowercase character in a textbox where some characters are selected. I don't know if the code works with a Multiline textbox.
If you're using oh-my-zsh
Type
omz update
in the terminal
Note: upgrade_oh_my_zsh
is deprecated
You can clean up a zombie process by killing its parent process with the following command:
kill -HUP $(ps -A -ostat,ppid | awk '{/[zZ]/{ print $2 }')
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
Quoting from the specification:
The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.
You should actually check against null
.
if (localStorage.getItem("username") === null) {
//...
}
You can add an alias
or a function
in your startup script file. Usually this is .bashrc
, .bash_login
or .profile
file in your home directory.
Since these files are hidden you will have to do an ls -a
to list them. If you don't have one you can create one.
If I remember correctly, when I had bought my Mac, the .bash_login
file wasn't there. I had to create it for myself so that I could put prompt info
, alias
, functions
, etc. in it.
Here are the steps if you would like to create one:
cd ~/
to go to your home foldertouch .bash_profile
to create your new file..bash_profile
with your favorite editor (or you can just type open -e .bash_profile
to open it in TextEdit.. .bash_profile
to reload .bash_profile
and update any alias you add.If you are using PostgreSQL, then it looks in ~/.pgpass
for passwords automatically. See the manual for more information.
Because the application crashes. For whom saving time on this exception!
And the error code says it throws an exception because it can't find a file in the initial phase. See the Environment Settings section. In my scenario, it worked when I changed the following code
var environment = whb.GetSetting("environment");
to
var environment = "Development";// whb.GetSetting("environment");
Because I have appsettings.development.json but I didn't have appsettings.production.json. Why it can't find any file because it's looking for different thing on right place.
Here is the simplest code for extracting text
code:
# importing required modules
import PyPDF2
# creating a pdf file object
pdfFileObj = open('filename.pdf', 'rb')
# creating a pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# printing number of pages in pdf file
print(pdfReader.numPages)
# creating a page object
pageObj = pdfReader.getPage(5)
# extracting text from page
print(pageObj.extractText())
# closing the pdf file object
pdfFileObj.close()
You can use Contains()
for that. It will feel a little backwards when you're really trying to produce an IN
clause, but this should do it:
var userProfiles = _dataContext.UserProfile
.Where(t => idList.Contains(t.Id));
I'm also assuming that each UserProfile
record is going to have an int
Id
field. If that's not the case you'll have to adjust accordingly.
I would use the BackgroundWorker approach and return the result in e.Result.
EDIT:
This is commonly associated with WinForms and WPF, but can be used by any type of .NET application. Here's sample code for a console app that uses BackgroundWorker:
using System;
using System.Threading;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
namespace BGWorker
{
class Program
{
static bool done = false;
static void Main(string[] args)
{
BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
bg.RunWorkerAsync();
while (!done)
{
Console.WriteLine("Waiting in Main, tid " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(100);
}
}
static void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("Completed, tid " + Thread.CurrentThread.ManagedThreadId);
done = true;
}
static void bg_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Work Line: " + i + ", tid " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
}
}
}
}
Output:
Waiting in Main, tid 10
Work Line: 1, tid 6
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Work Line: 2, tid 6
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Work Line: 3, tid 6
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Work Line: 4, tid 6
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Work Line: 5, tid 6
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Waiting in Main, tid 10
Completed, tid 6
2014 UPDATE
See @Roger's answer below.
https://stackoverflow.com/a/24916747/141172
He points out that you can use a Task that returns a Task<T>
, and check Task<T>.Result
.
Inline style only for clarity here. Use a real CSS stylesheet.
<!-- First, your background image is a DIV with a background
image style applied, not a IMG tag. -->
<div style="background-image:url(YourBackgroundImage);">
<!-- Second, create a placeholder div to assist in positioning
the other images. This is relative to the background div. -->
<div style="position: relative; left: 0; top: 0;">
<!-- Now you can place your IMG tags, and position them relative
to the container we just made -->
<img src="YourForegroundImage" style="position: relative; top: 0; left: 0;"/>
</div>
</div>
Here is the full code example I have show on browser, Hope you also helpful thanks.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker" ).datepicker({
minDate: -100,
maxDate: "+0D",
dateFormat: 'yy-dd-mm',
onSelect: function(datetext){
$(this).val(datetext);
},
});
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Date: <input type="text" id="datepicker"></p>
</body>
</html>
To archive the necessary result with double constructor you need to round the BigDecimal before convert it to String e.g.
new java.math.BigDecimal(10.0001).round(new java.math.MathContext(6, java.math.RoundingMode.HALF_UP)).toString()
will print the "10.0001"
If you want to wait for jobs to finish, use wait
. This will make the shell wait until all background jobs complete. However, if any of your jobs daemonize themselves, they are no longer children of the shell and wait will have no effect (as far as the shell is concerned, the child is already done. Indeed, when a process daemonizes itself, it does so by terminating and spawning a new process that inherits its role).
#!/bin/sh
{ sleep 5; echo waking up after 5 seconds; } &
{ sleep 1; echo waking up after 1 second; } &
wait
echo all jobs are done!
I found this here:
On windows (win xp), the parent process will not finish until the longtask.py
has finished its work. It is not what you want in CGI-script. The problem is not specific to Python, in PHP community the problems are the same.
The solution is to pass DETACHED_PROCESS
Process Creation Flag to the underlying CreateProcess
function in win API. If you happen to have installed pywin32 you can import the flag from the win32process module, otherwise you should define it yourself:
DETACHED_PROCESS = 0x00000008
pid = subprocess.Popen([sys.executable, "longtask.py"],
creationflags=DETACHED_PROCESS).pid
You can try This way
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itclanbd.spaceusers">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".Login_Activity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
This:
int fillarr(int arr[])
is actually treated the same as:
int fillarr(int *arr)
Now if you really want to return an array you can change that line to
int * fillarr(int arr[]){
// do something to arr
return arr;
}
It's not really returning an array. you're returning a pointer to the start of the array address.
But remember when you pass in the array, you're only passing in a pointer. So when you modify the array data, you're actually modifying the data that the pointer is pointing at. Therefore before you passed in the array, you must realise that you already have on the outside the modified result.
e.g.
int fillarr(int arr[]){
array[0] = 10;
array[1] = 5;
}
int main(int argc, char* argv[]){
int arr[] = { 1,2,3,4,5 };
// arr[0] == 1
// arr[1] == 2 etc
int result = fillarr(arr);
// arr[0] == 10
// arr[1] == 5
return 0;
}
I suggest you might want to consider putting a length into your fillarr function like this.
int * fillarr(int arr[], int length)
That way you can use length to fill the array to it's length no matter what it is.
To actually use it properly. Do something like this:
int * fillarr(int arr[], int length){
for (int i = 0; i < length; ++i){
// arr[i] = ? // do what you want to do here
}
return arr;
}
// then where you want to use it.
int arr[5];
int *arr2;
arr2 = fillarr(arr, 5);
// at this point, arr & arr2 are basically the same, just slightly
// different types. You can cast arr to a (char*) and it'll be the same.
If all you're wanting to do is set the array to some default values, consider using the built in memset function.
something like: memset((int*)&arr, 5, sizeof(int));
While I'm on the topic though. You say you're using C++. Have a look at using stl vectors. Your code is likely to be more robust.
There are lots of tutorials. Here is one that gives you an idea of how to use them. http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html
You get a unix timestamp in C# by using DateTime.UtcNow
and subtracting the epoch time of 1970-01-01.
e.g.
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
DateTime.UtcNow
can be replaced with any DateTime
object that you would like to get the unix timestamp for.
There is also a field, DateTime.UnixEpoch
, which is very poorly documented by MSFT, but may be a substitute for new DateTime(1970, 1, 1)
You need to use arguments unpacking..
def wrapper(func, *args):
func(*args)
def func1(x):
print(x)
def func2(x, y, z):
print x+y+z
wrapper(func1, 1)
wrapper(func2, 1, 2, 3)
Couldn't find a working answer here; but on linux you can run "umount.nfs4 /volume -f" and it definitely unmounts it.
Try using a simple HttpResponseMessage
with its Content
property set to a StreamContent
:
// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;
public HttpResponseMessage Post(string version, string environment,
string filetype)
{
var path = @"C:\Temp\test.exe";
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
A few things to note about the stream
used:
You must not call stream.Dispose()
, since Web API still needs to be able to access it when it processes the controller method's result
to send data back to the client. Therefore, do not use a using (var stream = …)
block. Web API will dispose the stream for you.
Make sure that the stream has its current position set to 0 (i.e. the beginning of the stream's data). In the above example, this is a given since you've only just opened the file. However, in other scenarios (such as when you first write some binary data to a MemoryStream
), make sure to stream.Seek(0, SeekOrigin.Begin);
or set stream.Position = 0;
With file streams, explicitly specifying FileAccess.Read
permission can help prevent access rights issues on web servers; IIS application pool accounts are often given only read / list / execute access rights to the wwwroot.
In css you can't set table-cells max height, and if you white-space nowrap then you can't break it with max width, so the solution is javascript working in all browsers.
So, this can work for you.
For Limiting max-height of all cells or rows in table with Javascript:
This script is good for horizontal overflow tables.
This script increase the table width 300px each time, maximum 4000px until rows shrinks to max-height(160px) , and you can also edit numbers as your need.
var i = 0, row, table = document.getElementsByTagName('table')[0], j = table.offsetWidth;
while (row = table.rows[i++]) {
while (row.offsetHeight > 160 && j < 4000) {
j += 300;
table.style.width = j + 'px';
}
}
Source: HTML Table Solution Max Height Limit For Rows Or Cells By Increasing Table Width, Javascript
SQL Server does not track licensing. Customers are responsible for tracking the assignment of licenses to servers, following the rules in the Licensing Guide.
The JSON C# class generator on codeplex generates classes which work well with NewtonSoftJS.
From what I know when I look at this question here
It said there that "in PHP, there is a distinct difference in Header output. In the examples below I chose to use a different header but for sake of showing the difference between exit() and die() that doesn't matter", and tested (personally)
As the answer said above, CSS PIE makes things like border-radius and box-shadow work in IE6-IE8: http://css3pie.com/
That said I have still found things to be somewhat flaky when using PIE and now just accept that people using older browsers aren't going to see rounded corners and dropshadows.
There was auto generated Copyright message in XML
and a blank line before <resources>
tag, once I removed it my build was successful.
No guarantee, but I suspect IE uses the older Protected Storage API.
You are to use something like this:
start /d C:\Windows\System32\calc.exe
start /d "C:\Program Files\Mozilla
Firefox" firefox.exe start /d
"C:\Program Files\Microsoft
Office\Office12" EXCEL.EXE
Also I advice you to use special batch files editor - Dr.Batcher
Here's a version that doesn't create a new thread every n
seconds:
from threading import Event, Thread
def call_repeatedly(interval, func, *args):
stopped = Event()
def loop():
while not stopped.wait(interval): # the first call is in `interval` secs
func(*args)
Thread(target=loop).start()
return stopped.set
The event is used to stop the repetitions:
cancel_future_calls = call_repeatedly(5, print, "Hello, World")
# do something else here...
cancel_future_calls() # stop future calls
Query would be like this:
SELECT ID, AccountID, Quantity,
SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT
FROM #Empl ORDER BY AccountID
Partition by works like group by. Here we are grouping by AccountID so sum would be corresponding to AccountID.
First first case, AccountID = 1 , then sum(quantity) = 10 + 5 + 2 => 17 & For AccountID = 2, then sum(Quantity) = 7+3 => 10
so result would appear like attached snapshot.
Assuming your json object from your GET request looks like the one you posted above simply do:
let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});
Or am I missing something that prevents you from doing it this way?
You can also get them with pure javascript.
For example:
new URL(location.href).searchParams.get('page')
For this url: websitename.com/user/?page=1, it would return a value of 1
There's a strong chance that the privileges to select from table1 have been granted to a role, and the role has been granted to you. Privileges granted to a role are not available to PL/SQL written by a user, even if the user has been granted the role.
You see this a lot for users that have been granted the dba role on objects owned by sys. A user with dba role will be able to, say, SELECT * from V$SESSION
, but will not be able to write a function that includes SELECT * FROM V$SESSION
.
The fix is to grant explicit permissions on the object in question to the user directly, for example, in the case above, the SYS user has to GRANT SELECT ON V_$SESSION TO MyUser;
If you would like to stop jenkins and all its services on the server using Linux console (e.g. Ubuntu), run:
service jenkins start/stop/restart
This is useful when you need to make an image/volume snapshot and you want all services to stop writing to the disk/volume.
You have to override your ;
delimiter with something like $$
to avoid this kind of error.
After your function definition, you can set the delimiter back to ;
.
This should work:
DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal)
RETURNS decimal
DETERMINISTIC
BEGIN
DECLARE dist decimal;
SET dist = SQRT(x1 - y1);
RETURN dist;
END$$
DELIMITER ;
The easiest way is to not use <object>. Instead use an <img> tag and the anchor should work just fine.
i Use this for the week start from SUNDAY:
SELECT id FROM tbl
WHERE
date >= curdate() - INTERVAL DAYOFWEEK(curdate())+5 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-2 DAY
You can of course make it a little more advanced. Non-blocking, writing bits and pieces, not writing the whole file at once:
var fs = require('fs');
var stream = fs.createWriteStream("my_file.txt");
stream.once('open', function(fd) {
stream.write("My first row\n");
stream.write("My second row\n");
stream.end();
});
You can create a subprocess using Windows cmd.exe
that restarts yourself:
Process process = new Process();
process.StartInfo.FileName = "cmd";
process.StartInfo.Arguments = "/c net stop \"servicename\" & net start \"servicename\"";
process.Start();
Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.
This error can appear on the client if there is a problem on the server side. For example, if the SOAP server is a PHP script with a parse error, the client will fail with this message.
If you are in control of the server, tail your Apache error_log on the machine that hosts the SOAP server. On CentOS you will find this in /var/log/httpd/error_log, so the command is:
tail -f /var/log/httpd/error_log
Now refresh the client and watch for the error message. Any PHP errors with the server script will be shown.
Hope that helps someone.
Why not just:
$('#b').click(function () {
var val = $(this).val();
})
Or if you don't click it (and I guess you won't) and you will use submit button, you can use prev()
function either.
You still can run it from File explorer on Windows 10 with the proper path. You just need to go to C:\Users\user\AppData\Local\Android\Sdk\tools\lib\monitor-x86_64
and double click the file monitor.
If you want to use in the cmd just the 'monitor' command you have to add this folder (in my case with android studio 3.4.1 and win10) to your Environment variables. So, press the start button and then type Edit the system environment variabes
click it and System properties window should open. Then go to
Environment variables => System variables => path
press the Edit
button for path and add the new value
C:\Users\user\AppData\Local\Android\Sdk\tools\lib\monitor-x86_64
click 'Ok', 'Ok' and 'Ok' and restart the cmd window if you had it opened and type 'monitor' and it should open the monitor as well.
Hope it helps!
PD: This answer was based on this answer https://stackoverflow.com/a/55077068/5360905 from Tiago Martins Peres
I would prefer generally foreach
when I don't need making arithmetic operations with their indices.
for (int[] x : array)
{
for (int y : x)
{
System.out.print(y + " ");
}
System.out.println();
}
Even when considering all answers above you might still run into issues that will terminate your maven offline build with an error. Especially, you may experience a warning as follwos:
[WARNING] The POM for org.apache.maven.plugins:maven-resources-plugin:jar:2.6 is missing, no dependency information available
The warning will be immediately followed by further errors and maven will terminate.
For us the safest way to build offline with a maven offline cache created following the hints above is to use following maven offline parameters:
mvn -o -llr -Dmaven.repo.local=<path_to_your_offline_cache> ...
Especially, option -llr prevents you from having to tune your local cache as proposed in answer #4.
Also take care that that the localRepository parameter in settings.xml is set as follows:
<localRepository>${user.home}/.m2/repository</localRepository>
TL;DR
def square_list(n):
the_list = [] # Replace
for x in range(n):
y = x * x
the_list.append(y) # these
return the_list # lines
def square_yield(n):
for x in range(n):
y = x * x
yield y # with this one.
Whenever you find yourself building a list from scratch, yield
each piece instead.
This was my first "aha" moment with yield.
yield
is a sugary way to say
build a series of stuff
Same behavior:
>>> for square in square_list(4):
... print(square)
...
0
1
4
9
>>> for square in square_yield(4):
... print(square)
...
0
1
4
9
Different behavior:
Yield is single-pass: you can only iterate through once. When a function has a yield in it we call it a generator function. And an iterator is what it returns. Those terms are revealing. We lose the convenience of a container, but gain the power of a series that's computed as needed, and arbitrarily long.
Yield is lazy, it puts off computation. A function with a yield in it doesn't actually execute at all when you call it. It returns an iterator object that remembers where it left off. Each time you call next()
on the iterator (this happens in a for-loop) execution inches forward to the next yield. return
raises StopIteration and ends the series (this is the natural end of a for-loop).
Yield is versatile. Data doesn't have to be stored all together, it can be made available one at a time. It can be infinite.
>>> def squares_all_of_them():
... x = 0
... while True:
... yield x * x
... x += 1
...
>>> squares = squares_all_of_them()
>>> for _ in range(4):
... print(next(squares))
...
0
1
4
9
If you need multiple passes and the series isn't too long, just call list()
on it:
>>> list(square_yield(4))
[0, 1, 4, 9]
Brilliant choice of the word yield
because both meanings apply:
yield — produce or provide (as in agriculture)
...provide the next data in the series.
yield — give way or relinquish (as in political power)
...relinquish CPU execution until the iterator advances.
You may get some information viewing it in assembly, but I think the easiest thing to do is fire up a virtual machine and see what it does. Make sure you have no open shares or anything like that that it can jump through though ;)
Newer versions of pandas do allow you to pass extra arguments (see the new documentation). So now you can do:
my_series.apply(your_function, args=(2,3,4), extra_kw=1)
The positional arguments are added after the element of the series.
For older version of pandas:
The documentation explains this clearly. The apply method accepts a python function which should have a single parameter. If you want to pass more parameters you should use functools.partial
as suggested by Joel Cornett in his comment.
An example:
>>> import functools
>>> import operator
>>> add_3 = functools.partial(operator.add,3)
>>> add_3(2)
5
>>> add_3(7)
10
You can also pass keyword arguments using partial
.
Another way would be to create a lambda:
my_series.apply((lambda x: your_func(a,b,c,d,...,x)))
But I think using partial
is better.
You can use
<li ng-repeat="(name, age) in items">{{name}}: {{age}}</li>
See ngRepeat documentation. Example: http://jsfiddle.net/WRtqV/1/
There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.
1. To create it via the IDE:
In the solution explorer pane, right click on the project that you would like to add the Service to:
Then, you can enter the path to your service WSDL and hit go:
2. To create it via the command line:
Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:
WSDL /verbose C:\path\to\wsdl
WSDL.exe will then output a .cs file for your consumption.
If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:
WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd
If you need VB output, use /language:VB
in addition to the /verbose
.
With HTML5 you can do
<input type="number">
You can also use a regex pattern to limit the input text.
<input type="text" pattern="^[0-9]*$" />
You could upload via $resource
by assigning data to params attribute of resource actions
like so:
$scope.uploadFile = function(files) {
var fdata = new FormData();
fdata.append("file", files[0]);
$resource('api/post/:id', { id: "@id" }, {
postWithFile: {
method: "POST",
data: fdata,
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}
}).postWithFile(fdata).$promise.then(function(response){
//successful
},function(error){
//error
});
};
You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula
=$B2>$C2
by using that "relative" version rather than your "absolute" one Excel (implicitly) adjusts the formula for each row in the range, as if you were copying the formula down
How about:
function filterObj(keys, obj) {
const newObj = {};
for (let key in obj) {
if (keys.includes(key)) {
newObj[key] = obj[key];
}
}
return newObj;
}
Or...
function filterObj(keys, obj) {
const newObj = {};
Object.keys(obj).forEach(key => {
if (keys.includes(key)) {
newObj[key] = obj[key];
}
});
return newObj;
}
If you ARE using SQL Server, you can just simply wrap the square brackets around the column or table name.
select [select]
from [table]
window.onload = function() {
var el = document.documentElement,
rfs = el.requestFullScreen
|| el.webkitRequestFullScreen
|| el.mozRequestFullScreen;
rfs.call(el);
};
You can't do this: {this.state.arrayFromJson}
As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map
to do that.
I am pasting a link from where you can learn how to render elements from an array with React.
http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/
Hope it helps!
@Singleton
@AccessTimeout(value=120000)
public class StatusSingletonBean {
private String status;
@Lock(LockType.WRITE)
public void setStatus(String new Status) {
status = newStatus;
}
@Lock(LockType.WRITE)
@AccessTimeout(value=360000)
public void doTediousOperation {
//...
}
}
//The following singleton has a default access timeout value of 60 seconds, specified //using the TimeUnit.SECONDS constant:
@Singleton
@AccessTimeout(value=60, timeUnit=SECONDS)
public class StatusSingletonBean {
//...
}
//The Java EE 6 Tutorial
//https://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html
I experienced a similar problem lately after i created a maven project, the maven dependencies folder did not appear in the project structure.To solve this simply add any dependency in the pom file, such as in code below, or right-click on the project and go to maven and select add dependency, search for any dependency such as junit
add this, and the maven dependency should appear on your project structure now.
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.9.RELEASE</version>
<scope>runtime</scope>
</dependency>
</dependencies>
One key thing to remember that message.max.bytes
attribute must be in sync with the consumer's fetch.message.max.bytes
property. the fetch size must be at least as large as the maximum message size otherwise there could be situation where producers can send messages larger than the consumer can consume/fetch. It might worth taking a look at it.
Which version of Kafka you are using? Also provide some more details trace that you are getting. is there some thing like ... payload size of xxxx larger
than 1000000
coming up in the log?
Please Find below code
select trim(string_agg(value,' ')) from STRING_SPLIT(' single spaces only ',' ')
where value<>' '
This worked for me.. Hope this helps...
I'm using jackson-xxx 2.8.5.Maven Dependency like:
<dependencies>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.5</version>
</dependency>
</dependencies>
First,If you want ignore unknown properties globally.you can config ObjectMapper
.
Like below:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
If you want ignore some class,you can add annotation @JsonIgnoreProperties(ignoreUnknown = true)
on your class like:
@JsonIgnoreProperties(ignoreUnknown = true)
public class E1 {
private String t1;
public String getT1() {
return t1;
}
public void setT1(String t1) {
this.t1 = t1;
}
}
Where is x found?
x is not found as you haven't defined it. :-) It could be found in code1 (global) or code3 (local) if you put it there.
code2 (class members) aren't visible to code inside methods of the same class — you would usually access them using self. code4/code5 (loops) live in the same scope as code3, so if you wrote to x in there you would be changing the x instance defined in code3, not making a new x.
Python is statically scoped, so if you pass ‘spam’ to another function spam will still have access to globals in the module it came from (defined in code1), and any other containing scopes (see below). code2 members would again be accessed through self.
lambda is no different to def. If you have a lambda used inside a function, it's the same as defining a nested function. In Python 2.2 onwards, nested scopes are available. In this case you can bind x at any level of function nesting and Python will pick up the innermost instance:
x= 0
def fun1():
x= 1
def fun2():
x= 2
def fun3():
return x
return fun3()
return fun2()
print fun1(), x
2 0
fun3 sees the instance x from the nearest containing scope, which is the function scope associated with fun2. But the other x instances, defined in fun1 and globally, are not affected.
Before nested_scopes — in Python pre-2.1, and in 2.1 unless you specifically ask for the feature using a from-future-import — fun1 and fun2's scopes are not visible to fun3, so S.Lott's answer holds and you would get the global x:
0 0
To easily shift by 5 values for example and also get rid of the NaN rows, without having to keep track of the number of values you shifted by:
d['gdp'] = df['gdp'].shift(-5)
df = df.dropna()