In the bash shell, try cat -v <filename>
. This should display carriage-returns for windows files.
(This worked for me in rxvt via Cygwin on Windows XP).
Editor's note: cat -v
visualizes \r
(CR) chars. as ^M
. Thus, line-ending \r\n
sequences will display as ^M
at the end of each output line. cat -e
will additionally visualize \n
, namely as $
. (cat -et
will additionally visualize tab chars. as ^I
.)
If you are using WebStorm and you are on Windows i would recommend you to click settings/editor/code style/general tab and select "windows(\r\n) from the dropdown menu.These steps will also apply for Rider.
\r is Carriage Return; \n is New Line (Line Feed) ... depends on the OS as to what each means. Read this article for more on the difference between '\n' and '\r\n' ... in C.
File.foreach(filename).with_index do |line, line_num|
puts "#{line_num}: #{line}"
end
This will execute the given block for each line in the file without slurping the entire file into memory. See: IO::foreach.
Don't know who looks at your file, but if you open it in wordpad instead of notepad, the linebreaks will show correct. In case you're using a special file extension, associate it with wordpad and you're done with it. Or use any other more advanced text editor.
Are you really sure that you selected the .csv file and not the .xls file? I can only reproduce the error if I try to read in an .xls file. If I try to read in a .csv file or any other text file, it's impossible to recreate the error you get.
> Data <- read.table("test.csv",header=T,sep=",")
> Data <- read.table("test.xlsx",header=T,sep=",")
Warning message:
In read.table("test.xlsx", header = T, sep = ",") :
incomplete final line found by readTableHeader on 'test.xlsx'
readTableHead
is the c-function that gives the error. It tries to read in the first n lines (standard the first 5 ) to determine the type of the data. The rest of the data is read in using scan()
. So the problem is the format of the file.
One way of finding out, is to set the working directory to the directory where the file is. That way you see the extension of the file you read in. I know on Windows it's not shown standard, so you might believe it's csv while it isn't.
The next thing you should do, is open the file in Notepad or Wordpad (or another editor) and check that the format is equivalent to my file test.csv
:
Test1,Test2,Test3
1,1,1
2,2,2
3,3,3
4,4,
5,5,
,6,
This file will give you the following dataframe :
> read.table(testfile,header=T,sep=",")
Test1 Test2 Test3
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 NA
5 5 5 NA
6 NA 6 NA
The csv format saved by excel seperates all cells with a comma. Empty cells just don't have a value. read.table()
can easily deal with this, and recognizes empty cells just fine.
To turn the option ON/OFF, follow the steps below from menu bar:
Tools ? Options ? Environment ? Documents ? Check for consistent line endings on load
The comment states
// Determines what character(s) are used to terminate each line in new files.
// Valid values are 'system' (whatever the OS uses), 'windows' (CRLF) and
// 'unix' (LF only).
You are setting
"default_line_ending": "LF",
You should set
"default_line_ending": "unix",
The SQL script was originally created on a Windows OS. The '^M' characters are a result of Windows and Unix having different ideas about what to use for an end-of-line character. You can use perl at the command line to fix this.
perl -pie 's/\r//g' filename.txt
Update 2:
Xcode 9 appears to have a "feature" where it will ignore the file's current line endings, and instead just use your default line-ending setting when inserting lines into a file, resulting in files with mixed line endings.
I'm pretty sure this bug didn't exist in Xcode 7; not sure about Xcode 8. The good news is that it appears to be fixed in Xcode 10.
For the time it existed, this bug caused a small amount of hilarity in the codebase I refer to in the question (which to this day uses autocrlf=false
), and led to many "EOL" commit messages and eventually to my writing a git pre-commit
hook to check for/prevent introducing mixed line endings.
Update:
Note: As noted by VonC, starting from Git 2.8, merge markers will not introduce Unix-style line-endings to a Windows-style file.
Original:
One little hiccup that I've noticed with this setup is that when there are merge conflicts, the lines git adds to mark up the differences do not have Windows line-endings, even when the rest of the file does, and you can end up with a file with mixed line endings, e.g.:
// Some code<CR><LF>
<<<<<<< Updated upstream<LF>
// Change A<CR><LF>
=======<LF>
// Change B<CR><LF>
>>>>>>> Stashed changes<LF>
// More code<CR><LF>
This doesn't cause us any problems (I imagine any tool that can handle both types of line-endings will also deal sensible with mixed line-endings--certainly all the ones we use do), but it's something to be aware of.
The other thing* we've found, is that when using git diff
to view changes to a file that has Windows line-endings, lines that have been added display their carriage returns, thus:
// Not changed
+ // New line added in^M
+^M
// Not changed
// Not changed
* It doesn't really merit the term: "issue".
This answer seems relevant since the OP makes reference to a need for a multi-OS solution. This Github help article details available approaches for handling lines endings cross-OS. There are global and per-repo approaches to managing cross-os line endings.
Global approach
Configure Git line endings handling on Linux or OS X:
git config --global core.autocrlf input
Configure Git line endings handling on Windows:
git config --global core.autocrlf true
Per-repo approach:
In the root of your repo, create a .gitattributes
file and define line ending settings for your project files, one line at a time in the following format: path_regex line-ending-settings
where line-ending-settings
is one of the following:
The text
value can be configured further to instruct Git on how to handle line endings for matching files:
text
- Changes line endings to OS native line endings.text eol=crlf
- Converts line endings to CRLF
on checkout.text eol=lf
- Converts line endings to LF
on checkout.text=auto
- Sensible default that leaves line handle up to Git's discretion.Here is the content of a sample .gitattributes file:
# Set the default behavior for all files.
* text=auto
# Normalized and converts to
# native line endings on checkout.
*.c text
*.h text
# Convert to CRLF line endings on checkout.
*.sln text eol=crlf
# Convert to LF line endings on checkout.
*.sh text eol=lf
# Binary files.
*.png binary
*.jpg binary
More on how to refresh your repo after changing line endings settings here. Tldr:
backup your files with Git, delete every file in your repository (except the .git directory), and then restore the files all at once. Save your current files in Git, so that none of your work is lost.
git add . -u
git commit -m "Saving files before refreshing line endings"
Remove the index and force Git to rescan the working directory.
rm .git/index
Rewrite the Git index to pick up all the new line endings.
git reset
Show the rewritten, normalized files.
In some cases, this is all that needs to be done. Others may need to complete the following additional steps:
git status
Add all your changed files back, and prepare them for a commit. This is your chance to inspect which files, if any, were unchanged.
git add -u
It is perfectly safe to see a lot of messages here that read[s] "warning: CRLF will be replaced by LF in file."
Rewrite the .gitattributes file.
git add .gitattributes
Commit the changes to your repository.
git commit -m "Normalize all the line endings"
Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.
If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll
(assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.
If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).
char variable = 'x'; // the variable is a char whose value is lowercase x
printf("<%c>", variable); // print it with angle brackets around the character
You have to dispatch after the async request ends.
This would work:
export function bindComments(postId) {
return function(dispatch) {
return API.fetchComments(postId).then(comments => {
// dispatch
dispatch({
type: BIND_COMMENTS,
comments,
postId
});
});
};
}
public static Method[] getAccessibleMethods(Class clazz) {
List<Method> result = new ArrayList<Method>();
while (clazz != null) {
for (Method method : clazz.getDeclaredMethods()) {
int modifiers = method.getModifiers();
if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
result.add(method);
}
}
clazz = clazz.getSuperclass();
}
return result.toArray(new Method[result.size()]);
}
For swift4.0 and above used below code:
let udid = UIDevice.current.identifierForVendor?.uuidString
let name = UIDevice.current.name
let version = UIDevice.current.systemVersion
let modelName = UIDevice.current.model
let osName = UIDevice.current.systemName
let localized = UIDevice.current.localizedModel
print(udid ?? "")
print(name)
print(version)
print(modelName)
print(osName)
print(localized)
This works, even done is printed.
SpringApplication.run(MyApplication.class, args).close();
System.out.println("done");
So adding .close()
after run()
Explanation:
public ConfigurableApplicationContext run(String... args)
Run the Spring application, creating and refreshing a new ApplicationContext. Parameters:
args
- the application arguments (usually passed from a Java main method)Returns: a running ApplicationContext
and:
void close()
Close this application context, releasing all resources and locks that the implementation might hold. This includes destroying all cached singleton beans. Note: Does not invoke close on a parent context; parent contexts have their own, independent lifecycle.This method can be called multiple times without side effects: Subsequent close calls on an already closed context will be ignored.
So basically, it will not close the parent context, that's why the VM doesn't quit.
UPDATE:
Thank you for the quick response. open http://localhost/
opened that domain in my default browser on my Mac.
I ended up writing this alias, did the trick:
# Opens git file's localhost; ${PWD##*/} is the current directory's name
alias lcl='open "http://localhost/${PWD##*/}/"'
Thank you again!
Another simple trick:
SELECT CONVERT(char(2), cast('2015-01-01' as datetime), 101) -- month with 2 digits
SELECT CONVERT(char(6), cast('2015-01-01' as datetime), 112) -- year (yyyy) and month (mm)
Outputs:
01
201501
You can use this free service: https://www.smtpjs.com
<script src="https://smtpjs.com/v2/smtp.js"></script>
Email.send(
"[email protected]",
"[email protected]",
"This is a subject",
"this is the body",
"smtp.yourisp.com",
"username",
"password"
);
private void DgvRoomInformation_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (DgvRoomInformation.CurrentCell.ColumnIndex == 4) //example-'Column index=4'
{
DgvRoomInformation.BeginEdit(true);
}
}
Try the following. It may be help you.
For more information, visit Input type=password, don't let browser remember the password
function setAutoCompleteOFF(tm) {_x000D_
if(typeof tm == "undefined") {_x000D_
tm = 10;_x000D_
}_x000D_
try {_x000D_
var inputs = $(".auto-complete-off, input[autocomplete=off]");_x000D_
setTimeout(function() {_x000D_
inputs.each(function() {_x000D_
var old_value = $(this).attr("value");_x000D_
var thisobj = $(this);_x000D_
setTimeout(function() {_x000D_
thisobj.removeClass("auto-complete-off").addClass("auto-complete-off-processed");_x000D_
thisobj.val(old_value);_x000D_
}, tm);_x000D_
});_x000D_
}, tm);_x000D_
}_x000D_
catch(e){_x000D_
}_x000D_
}_x000D_
_x000D_
$(function(){_x000D_
setAutoCompleteOFF();_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="passfld" type="password" autocomplete="off" />_x000D_
<input type="submit">
_x000D_
You can change the code when you decompiled it, but it has to be recompiled to a class
file, the decompiler outputs java
code, this has to be recompiled with the same classpath as the original jar
/class
file
If you want to call a different size for the button inline, you would probably do it like this:
<div class="button" style="width:60px;height:100px;">This is a button</div>
Or, a better way to have different sizes (say there will be 3 standard sizes for the button) would be to have classes just for size.
For example, you would call your button like this:
<div class="button small">This is a button</div>
And in your CSS
.button.small { width: 60px; height: 100px; }
and just create classes for each size you wish to have. That way you still have the perks of using a stylesheet in case say, you want to change the size of all the small buttons at once.
Disclaimer: I work for a company, Particle Code, that makes a cross-platform framework. There are a ton of companies in this space. New ones seem to spring up every week. Good news for you: you have a lot of choices.
These frameworks take different approaches, and many of them are fundamentally designed to solve different problems. Some are focused on games, some are focused on apps. I would ask the following questions:
What do you want to write? Enterprise application, personal productivity application, puzzle game, first-person shooter?
What kind of development environment do you prefer? IDE or plain ol' text editor?
Do you have strong feelings about programming languages? Of the frameworks I'm familiar with, you can choose from ActionScript, C++, C#, Java, Lua, and Ruby.
My company is more in the game space, so I haven't played as much with the JavaScript+CSS frameworks like Titanium, PhoneGap, and Sencha. But I can tell you a bit about some of the games-oriented frameworks. Games and rich internet applications are an area where cross-platform frameworks can shine, because these applications tend to place more importance of being visually unique and less on blending in with native UIs. Here are a few frameworks to look for:
Unity www.unity3d.com is a 3D games engine. It's really unlike any other development environment I've worked in. You build scenes with 3D models, and define behavior by attaching scripts to objects. You can script in JavaScript, C#, or Boo. If you want to write a 3D physics-based game that will run on iOS, Android, Windows, OS X, or consoles, this is probably the tool for you. You can also write 2D games using 3D assets--a fine example of this is indie game Max and the Magic Marker, a 2D physics-based side-scroller written in Unity. If you don't know it, I recommend checking it out (especially if there are any kids in your household). Max is available for PC, Wii, iOS and Windows Phone 7 (although the latter version is a port, since Unity doesn't support WinPhone). Unity comes with some sample games complete with 3D assets and textures, which really helps getting up to speed with what can be a pretty complicated environment.
Corona www.anscamobile.com/corona is a 2D games engine that uses the Lua scripting language and supports iOS and Android. The selling point of Corona is the ability to write physics-based games very quickly in few lines of code, and the large number of Corona-based games in the iOS app store is a testament to its success. The environment is very lean, which will appeal to some people. It comes with a simulator and debugger. You add your text editor of choice, and you have a development environment. The base SDK doesn't include any UI components, like buttons or list boxes, but a CoronaUI add-on is available to subscribers.
The Particle SDK www.particlecode.com is a slightly more general cross-platform solution with a background in games. You can write in either Java or ActionScript, using a MVC application model. It includes an Eclipse-based IDE with a WYSIWYG UI editor. We currently support building for Android, iOS, webOS, and Windows Phone 7 devices. You can also output Flash or HTML5 for the web. The framework was originally developed for online multiplayer social games, such as poker and backgammon, and it suits 2D games and apps with complex logic. The framework supports 2D graphics and includes a 2D physics engine.
NB:
Today we announced that Particle Code has been acquired by Appcelerator, makers of the Titanium cross-platform framework.
...
As of January 1, 2012, [Particle Code] will no longer officially support the [Particle SDK] platform.
In terms of learning curve, I'd say that Unity had the steepest learning curve (for me), Corona was the simplest, and Particle and Airplay are somewhere in between.
Another interesting point is how the frameworks handle different form factors. Corona supports dynamic scaling, which will be familiar to Flash developers. This is very easy to use but means that you end up wasting screen space when going from a 4:3 screen like the iPhone to a 16:9 like the new qHD Android devices. The Particle SDK's UI editor lets you design flexible layouts that scale, but also lets you adjust the layouts for individual screen sizes. This takes a little more time but lets you make the app look custom made for each screen.
Of course, what works for you depends on your individual taste and work style as well as your goals -- so I recommend downloading a couple of these tools and giving them a shot. All of these tools are free to try.
Also, if I could just put in a public service announcement -- most of these tools are in really active development. If you find a framework you like, by all means send feedback and let them know what you like, what you don't like, and features you'd like to see. You have a real opportunity to influence what goes into the next versions of these tools.
Hope this helps.
In .net core 3.1 (and other more recent versions), you can use:
private readonly UserManager<IdentityUser> _userManager;
public ExampleController(UserManager<IdentityUser> userManager)
{
_userManager = userManager;
}
Then:
string userId = _userManager.GetUserId(User);
Or async:
var user = await _userManager.GetUserAsync(User);
var userId = user.Id;
At this point, I'm trying to figure out why you'd use one over the other. I know the general benefits of async, but see both of these used frequently. Please post some comments if anyone knows.
You can use Ctrl + Shift + / for Windows.
It's called the ternary operator
. For some more info, here's another question I answered regarding this:
HTML5 defined a window.saveAs(blob, filename)
method. It isn't supported by any browser right now. But there is a compatibility library called FileSaver.js that adds this function to most modern browsers (including Internet Explorer 10+). Internet Explorer 10 supports a navigator.msSaveBlob(blob, filename)
method (MSDN), which is used in FileSaver.js for Internet Explorer support.
I wrote a blog posting with more details about this problem.
Drop the hash - that's for identifying the id attribute.
If you think the executable is locked by a process, try Process Explorer from SysInternals. In the File/handle, enter Fibonacci.exe and you should see who holds the file.
If it is not enough, you can use Process Monitor (from SysInternals, again) to follow the activity of all processes on your system on Fibonacci.exe. With a little bit of analysis (call stacks), you'll may find out why the access to the file is denied and what make it disappear.
I get this every time I want to create an application in VC++.
Right-click the project, select Properties then under 'Configuration properties | C/C++ | Code Generation', select "Multi-threaded Debug (/MTd)" for Debug configuration.
Note that this does not change the setting for your Release configuration - you'll need to go to the same location and select "Multi-threaded (/MT)" for Release.
it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);
DECLARE @STARTDATE datetime;
DECLARE @EntDt datetime;
set @STARTDATE = '01/01/2009';
set @EntDt = '12/31/2009';
declare @dcnt int;
;with DateList as
(
select @STARTDATE DateValue
union all
select DateValue + 1 from DateList
where DateValue + 1 < convert(VARCHAR(15),@EntDt,101)
)
select count(*) as DayCnt from (
select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )
)a
option (maxrecursion 365);
From my experience and Maven best practices there are two kinds of "parent poms"
"company" parent pom - this pom contains your company specific information and configuration that inherit every pom and doesn't need to be copied. These informations are:
Preparing this parent pom need to be done with caution, because all your company poms will inherit from it, so this pom have to be mature and stable (releasing a version of parent pom should not affect to release all your company projects!)
The intention is to be scalable to a large scale build so should be scalable to a large number of projects and artifacts.
Mutliprojects have structure of trees - so you aren't arrown down to one level of parent pom. Try to find a suitable project struture for your needs - a classic exmample is how to disrtibute mutimodule projects
distibution/
documentation/
myproject/
myproject-core/
myproject-api/
myproject-app/
pom.xml
pom.xml
A few bonus questions:
- Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).
This configuration has to be wisely splitted into a "company" parent pom and project parent pom(s). Things related to all you project go to "company" parent and this related to current project go to project one's.
- How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?
Company parent pom have to be released first. For multiprojects standard rules applies. CI server need to know all to build the project correctly.
only shortcut for something like this that I know of is
var val;
(val==null || val===false) ? false: true;
Use repr()[1:-1]. In this case, the double quotes don't need to be escaped. The [-1:1] slice is to remove the single quote from the beginning and the end.
>>> x = raw_input()
I'm "stuck" :\
>>> print x
I'm "stuck" :\
>>> print repr(x)[1:-1]
I\'m "stuck" :\\
Or maybe you just want to escape a phrase to paste into your program? If so, do this:
>>> raw_input()
I'm "stuck" :\
'I\'m "stuck" :\\'
I had similar situation and here is my approach which is somewhat different:
HADOOP_USER_NAME=hdfs hdfs dfs -put /root/MyHadoop/file1.txt /
What you actually do is you read local file in accordance to your local permissions but when placing file on HDFS you are authenticated like user hdfs
. You can do this with other ID (beware of real auth schemes configuration but this is usually not a case).
Advantages:
sudo
.tv_nsec
is the sleep time in nanoseconds. 500000us = 500000000ns, so you want:
nanosleep((const struct timespec[]){{0, 500000000L}}, NULL);
select * from table
where tester NOT LIKE '%username%';
You can use an alias to automate the solutions provided by others:
[alias]
rms = "!f(){ git rm --cached \"$1\";rm -r \"$1\";git config -f .gitmodules --remove-section \"submodule.$1\";git config -f .git/config --remove-section \"submodule.$1\";git add .gitmodules; }; f"
Put that in your git config, and then you can do: git rms path/to/submodule
There are references to the official docs (DialogFragment Reference) in other answers, but no mention of the example given there:
void showDialog() {
mStackLevel++;
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
newFragment.show(ft, "dialog");
}
This removes any currently shown dialog, creates a new DialogFragment with an argument, and shows it as a new state on the back stack. When the transaction is popped, the current DialogFragment and its Dialog will be destroyed, and the previous one (if any) re-shown. Note that in this case DialogFragment will take care of popping the transaction of the Dialog is dismissed separately from it.
For my needs I changed it to:
FragmentManager manager = getSupportFragmentManager();
Fragment prev = manager.findFragmentByTag(TAG);
if (prev != null) {
manager.beginTransaction().remove(prev).commit();
}
MyDialogFragment fragment = new MyDialogFragment();
fragment.show(manager, TAG);
For time:
label1.Text = DateTime.Now.ToString("HH:mm:ss"); //result 22:11:45
or
label1.Text = DateTime.Now.ToString("hh:mm:ss tt"); //result 11:11:45 PM
For date:
label1.Text = DateTime.Now.ToShortDateString(); //30.5.2012
The following script removes quotation marks only from around the column value if table is called [Messages] and the column is called [Description].
-- If the content is in the form of "anything" (LIKE '"%"')
-- Then take the whole text without the first and last characters
-- (from the 2nd character and the LEN([Description]) - 2th character)
UPDATE [Messages]
SET [Description] = SUBSTRING([Description], 2, LEN([Description]) - 2)
WHERE [Description] LIKE '"%"'
Actually my panel had this collapse state arrow icon and I tried other answers in this post , but icon position changed, so here is the solution with collapse state arrow icon.
Add this Custom CSS
.panel-heading
{
cursor: pointer;
padding: 0;
}
a.accordion-toggle
{
display: block;
padding: 10px 15px;
}
Credit's goes to this post answerer.
Hope helps.
You can replace the certificate by just running the certbot again with ./certbot-auto certonly
You will be prompted with this message if you try to generate a certificate for a domain that you have already covered by an existing certificate:
-------------------------------------------------------------------------------
You have an existing certificate that contains a portion of the domains you
requested (ref: /etc/letsencrypt/renewal/<domain>.conf)
It contains these names: <domain>
You requested these names for the new certificate: <domain>,
<the domain you want to add to the cert>.
Do you want to expand and replace this existing certificate with the new
certificate?
-------------------------------------------------------------------------------
Just chose Expand
and replace it.
Add more than one class based on the condition:
<div ng-click="AbrirPopUp(s)"
ng-class="{'class1 class2 class3':!isNew,
'class1 class4': isNew}">{{ isNew }}</div>
Apply: class1 + class2 + class3 when isNew=false,
Apply: class1+ class4 when isNew=true
Unix timestamp is in seconds, so simply add the corresponding number of seconds to the timestamp:
$timeInFuture = time() + (60 * 60 * 24);
I hacked this out for release Bootstrap 4.1.1 per my needs before I saw @florian_korner's post. Looks very similar.
If you use sass you can paste this snippet at the end of your bootstrap includes. It seems to fix the issue for chrome, IE, and edge. Does not seem to break anything in firefox.
@mixin make-td-col($size, $columns: $grid-columns) {
width: percentage($size / $columns);
}
@each $breakpoint in map-keys($grid-breakpoints) {
$infix: breakpoint-infix($breakpoint, $grid-breakpoints);
@for $i from 1 through $grid-columns {
td.col#{$infix}-#{$i}, th.col#{$infix}-#{$i} {
@include make-td-col($i, $grid-columns);
}
}
}
or if you just want the compiled css utility:
td.col-1, th.col-1 {
width: 8.33333%; }
td.col-2, th.col-2 {
width: 16.66667%; }
td.col-3, th.col-3 {
width: 25%; }
td.col-4, th.col-4 {
width: 33.33333%; }
td.col-5, th.col-5 {
width: 41.66667%; }
td.col-6, th.col-6 {
width: 50%; }
td.col-7, th.col-7 {
width: 58.33333%; }
td.col-8, th.col-8 {
width: 66.66667%; }
td.col-9, th.col-9 {
width: 75%; }
td.col-10, th.col-10 {
width: 83.33333%; }
td.col-11, th.col-11 {
width: 91.66667%; }
td.col-12, th.col-12 {
width: 100%; }
td.col-sm-1, th.col-sm-1 {
width: 8.33333%; }
td.col-sm-2, th.col-sm-2 {
width: 16.66667%; }
td.col-sm-3, th.col-sm-3 {
width: 25%; }
td.col-sm-4, th.col-sm-4 {
width: 33.33333%; }
td.col-sm-5, th.col-sm-5 {
width: 41.66667%; }
td.col-sm-6, th.col-sm-6 {
width: 50%; }
td.col-sm-7, th.col-sm-7 {
width: 58.33333%; }
td.col-sm-8, th.col-sm-8 {
width: 66.66667%; }
td.col-sm-9, th.col-sm-9 {
width: 75%; }
td.col-sm-10, th.col-sm-10 {
width: 83.33333%; }
td.col-sm-11, th.col-sm-11 {
width: 91.66667%; }
td.col-sm-12, th.col-sm-12 {
width: 100%; }
td.col-md-1, th.col-md-1 {
width: 8.33333%; }
td.col-md-2, th.col-md-2 {
width: 16.66667%; }
td.col-md-3, th.col-md-3 {
width: 25%; }
td.col-md-4, th.col-md-4 {
width: 33.33333%; }
td.col-md-5, th.col-md-5 {
width: 41.66667%; }
td.col-md-6, th.col-md-6 {
width: 50%; }
td.col-md-7, th.col-md-7 {
width: 58.33333%; }
td.col-md-8, th.col-md-8 {
width: 66.66667%; }
td.col-md-9, th.col-md-9 {
width: 75%; }
td.col-md-10, th.col-md-10 {
width: 83.33333%; }
td.col-md-11, th.col-md-11 {
width: 91.66667%; }
td.col-md-12, th.col-md-12 {
width: 100%; }
td.col-lg-1, th.col-lg-1 {
width: 8.33333%; }
td.col-lg-2, th.col-lg-2 {
width: 16.66667%; }
td.col-lg-3, th.col-lg-3 {
width: 25%; }
td.col-lg-4, th.col-lg-4 {
width: 33.33333%; }
td.col-lg-5, th.col-lg-5 {
width: 41.66667%; }
td.col-lg-6, th.col-lg-6 {
width: 50%; }
td.col-lg-7, th.col-lg-7 {
width: 58.33333%; }
td.col-lg-8, th.col-lg-8 {
width: 66.66667%; }
td.col-lg-9, th.col-lg-9 {
width: 75%; }
td.col-lg-10, th.col-lg-10 {
width: 83.33333%; }
td.col-lg-11, th.col-lg-11 {
width: 91.66667%; }
td.col-lg-12, th.col-lg-12 {
width: 100%; }
td.col-xl-1, th.col-xl-1 {
width: 8.33333%; }
td.col-xl-2, th.col-xl-2 {
width: 16.66667%; }
td.col-xl-3, th.col-xl-3 {
width: 25%; }
td.col-xl-4, th.col-xl-4 {
width: 33.33333%; }
td.col-xl-5, th.col-xl-5 {
width: 41.66667%; }
td.col-xl-6, th.col-xl-6 {
width: 50%; }
td.col-xl-7, th.col-xl-7 {
width: 58.33333%; }
td.col-xl-8, th.col-xl-8 {
width: 66.66667%; }
td.col-xl-9, th.col-xl-9 {
width: 75%; }
td.col-xl-10, th.col-xl-10 {
width: 83.33333%; }
td.col-xl-11, th.col-xl-11 {
width: 91.66667%; }
td.col-xl-12, th.col-xl-12 {
width: 100%; }
There is a way to get count of runes without any packages by converting string to []rune as len([]rune(YOUR_STRING))
:
package main
import "fmt"
func main() {
russian := "??????? ? ??????"
english := "Sputnik & pogrom"
fmt.Println("count of bytes:",
len(russian),
len(english))
fmt.Println("count of runes:",
len([]rune(russian)),
len([]rune(english)))
}
count of bytes 30 16
count of runes 16 16
One issue is that reindex
will fail if there are duplicate values. Say we're working with timestamped data, which we want to index by date:
df = pd.DataFrame({
'timestamps': pd.to_datetime(
['2016-11-15 1:00','2016-11-16 2:00','2016-11-16 3:00','2016-11-18 4:00']),
'values':['a','b','c','d']})
df.index = pd.DatetimeIndex(df['timestamps']).floor('D')
df
yields
timestamps values
2016-11-15 "2016-11-15 01:00:00" a
2016-11-16 "2016-11-16 02:00:00" b
2016-11-16 "2016-11-16 03:00:00" c
2016-11-18 "2016-11-18 04:00:00" d
Due to the duplicate 2016-11-16
date, an attempt to reindex:
all_days = pd.date_range(df.index.min(), df.index.max(), freq='D')
df.reindex(all_days)
fails with:
...
ValueError: cannot reindex from a duplicate axis
(by this it means the index has duplicates, not that it is itself a dup)
Instead, we can use .loc
to look up entries for all dates in range:
df.loc[all_days]
yields
timestamps values
2016-11-15 "2016-11-15 01:00:00" a
2016-11-16 "2016-11-16 02:00:00" b
2016-11-16 "2016-11-16 03:00:00" c
2016-11-17 NaN NaN
2016-11-18 "2016-11-18 04:00:00" d
fillna
can be used on the column series to fill blanks if needed.
What Arrays.toString()
does is create a string representation of each individual byte in your byteArray.
Please check the API documentation Arrays API
To convert your response string back to the original byte array, you have to use split(",")
or something and convert it into a collection and then convert each individual item in there to a byte to recreate your byte array.
Follow the below steps,
The problem setting the layer's borderWidth
and borderColor
is that the when you touch the button the border doesn't animate the highlight effect.
Of course, you can observe the button's events and change the border color accordingly but that feels unnecessary.
Another option is to create a stretchable UIImage and setting it as the button's background image. You can create an Image set in your Images.xcassets like this:
Then, you set it as the button's background image:
If your image is a template image you can set tint color of the button and the border will change:
Now the border will highlight with the rest of the button when touched.
You should use like this:
body { background: url("img/debut_dark.png") repeat 0 0; } body { background: url("../img/debut_dark.png") repeat 0 0; } body { background-image: url("../img/debut_dark.png") repeat 0 0; }
or try Inspecting CSS Rules using Firefox Firebug tool.
I created a jar file from a Maven project (by write mvn package or mvn install )
after that i open the cmd , move to the jar direction and then
to run this code the
java -cp FILENAME.jar package.Java-Main-File-Name-Class
Edited : after puting in Pom file declar the main to run the code :
java -jar FILENAME.JAR
You can use the auto_now
and auto_now_add
options for updated_at
and created_at
respectively.
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
This is a self contained project so that you can see everything in context.
Create a layout like the following with a UIView
and a UIButton
. The UIView
will be the container in which we will play our video.
If you need a sample video to practice with, you can get one from sample-videos.com. I'm using an mp4 format video in this example. Drag and drop the video file into your project. I also had to add it explicitly into the bundle resources (go to Build Phases > Copy Bundle Resources, see this answer for more).
Here is the complete code for the project.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVPlayer?
@IBOutlet weak var videoViewContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
initializeVideoPlayerWithVideo()
}
func initializeVideoPlayerWithVideo() {
// get the path string for the video from assets
let videoString:String? = Bundle.main.path(forResource: "SampleVideo_360x240_1mb", ofType: "mp4")
guard let unwrappedVideoPath = videoString else {return}
// convert the path string to a url
let videoUrl = URL(fileURLWithPath: unwrappedVideoPath)
// initialize the video player with the url
self.player = AVPlayer(url: videoUrl)
// create a video layer for the player
let layer: AVPlayerLayer = AVPlayerLayer(player: player)
// make the layer the same size as the container view
layer.frame = videoViewContainer.bounds
// make the video fill the layer as much as possible while keeping its aspect size
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
// add the layer to the container view
videoViewContainer.layer.addSublayer(layer)
}
@IBAction func playVideoButtonTapped(_ sender: UIButton) {
// play the video if the player is initialized
player?.play()
}
}
Notes
AVPlayerItem
.AVFoundation
and AVPlayer
, then you have to build all of your own controls. If you want full screen video playback, you can use AVPlayerViewController
. You will need to import AVKit
for that. It comes with a full set of controls for pause, fast forward, rewind, stop, etc. Here and here are some video tutorials.MPMoviePlayerController
that you may have seen in other answers is deprecated.The project should look like this now.
You have to bind your event handlers to correct context (this
):
onChange={this.setAuthorState.bind(this)}
The below code will help you to auto open the .exe file from excel...
Sub Auto_Open()
Dim x As Variant
Dim Path As String
' Set the Path variable equal to the path of your program's installation
Path = "C:\Program Files\GameTop.com\Alien Shooter\game.exe"
x = Shell(Path, vbNormalFocus)
End Sub
With Chrome and Safari you can add the CSS style -webkit-print-color-adjust: exact;
to the element to force print the background color and/or image
listofIDs.Select(int.Parse).ToList()
This is similar to an 'ls' but it does not take into account the prefix folder convention and will list the objects in the bucket. It's left up to the reader to filter out prefixes which are part of the Key name.
In Python 2:
from boto.s3.connection import S3Connection
conn = S3Connection() # assumes boto.cfg setup
bucket = conn.get_bucket('bucket_name')
for obj in bucket.get_all_keys():
print(obj.key)
In Python 3:
from boto3 import client
conn = client('s3') # again assumes boto.cfg setup, assume AWS S3
for key in conn.list_objects(Bucket='bucket_name')['Contents']:
print(key['Key'])
Sorry to beat a dead horse, but it is kind-of weird that no-one pointed this out - "Yes you can, but this is the opposite of how you use capturing groups in real life".
If you use Regex the way it is meant to be used, the solution is as simple as this:
"6 example input 4".replaceAll("(?:\\d)(.*)(?:\\d)", "number$11");
Or as rightfully pointed out by shmosel below,
"6 example input 4".replaceAll("\d(.*)\d", "number$11");
...since in your regex there is no good reason to group the decimals at all.
You don't usually use capturing groups on the parts of the string you want to discard, you use them on the part of the string you want to keep.
If you really want groups that you want to replace, what you probably want instead is a templating engine (e.g. moustache, ejs, StringTemplate, ...).
As an aside for the curious, even non-capturing groups in regexes are just there for the case that the regex engine needs them to recognize and skip variable text. For example, in
(?:abc)*(capture me)(?:bcd)*
you need them if your input can look either like "abcabccapture mebcdbcd" or "abccapture mebcd" or even just "capture me".
Or to put it the other way around: if the text is always the same, and you don't capture it, there is no reason to use groups at all.
You Just clicking the key.
first press ESC + enter and then press :x + enter
You could use a DataSet to read XML strings.
var xmlString = File.ReadAllText(FILE_PATH);
var stringReader = new StringReader(xmlString);
var dsSet = new DataSet();
dsSet.ReadXml(stringReader);
Posting this for the sake of information.
public static void listRemove() {
List<String> list = Arrays.asList("", "Hi", "", "How", "are", "you");
List<String> result = new ArrayList<String>();
for (String str : list) {
if (str != null && !str.isEmpty()) {
result.add(str);
}
}
System.out.println(result);
}
The cd
in your script technically worked as it changed the directory of the shell that ran the script, but that was a separate process forked from your interactive shell.
A Posix-compatible way to solve this problem is to define a shell procedure rather than a shell-invoked command script.
jhome () {
cd /home/tree/projects/java
}
You can just type this in or put it in one of the various shell startup files.
Please see $RANDOM
:
$RANDOM
is an internal Bash function (not a constant) that returns a pseudorandom integer in the range 0 - 32767. It should not be used to generate an encryption key.
Another possibile solution is,maybe your file is ASCII type file,just change the type of your files.
To complete the picture, since -Werror
might considered too "invasive",
for gcc (and llvm) a more precise solution is to transform just this warning in an error, using the option:
-Werror=implicit-function-declaration
See Make one gcc warning an error?
Regarding general use of -Werror
: Of course, having warningless code is recommendable, but in some stage of development it might slow down the prototyping.
how random count in :
count, one := big.NewInt(0), big.NewInt(1)
count.SetString("100000000000000000000000", 10)
on the main.dart file import service like follow
import 'package:flutter/services.dart';
and inside build method just add this line before return
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.orange
));
Like this:
@override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: CustomColors.appbarcolor
));
return MaterialApp(
home: MySplash(),
theme: ThemeData(
brightness: Brightness.light,
primaryColor: CustomColors.appbarcolor,
),
);
}
If you're targeting iOS 11.0+ / macOS 10.13+, you simply use ISO8601DateFormatter
with the withInternetDateTime
and withFractionalSeconds
options, like so:
let date = Date()
let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let string = iso8601DateFormatter.string(from: date)
// string looks like "2020-03-04T21:39:02.112Z"
Please make sure in manifest that package name is same with your main activity
As a rule of thumb, I usually apply the following image pre-processing techniques using OpenCV library:
Rescaling the image (it's recommended if you’re working with images that have a DPI of less than 300 dpi):
img = cv2.resize(img, None, fx=1.2, fy=1.2, interpolation=cv2.INTER_CUBIC)
Converting image to grayscale:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Applying dilation and erosion to remove the noise (you may play with the kernel size depending on your data set):
kernel = np.ones((1, 1), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)
Applying blur, which can be done by using one of the following lines (each of which has its pros and cons, however, median blur and bilateral filter usually perform better than gaussian blur.):
cv2.threshold(cv2.GaussianBlur(img, (5, 5), 0), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
cv2.threshold(cv2.bilateralFilter(img, 5, 75, 75), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
cv2.threshold(cv2.medianBlur(img, 3), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
cv2.adaptiveThreshold(cv2.GaussianBlur(img, (5, 5), 0), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
cv2.adaptiveThreshold(cv2.bilateralFilter(img, 9, 75, 75), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
cv2.adaptiveThreshold(cv2.medianBlur(img, 3), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
I've recently written a pretty simple guide to Tesseract but it should enable you to write your first OCR script and clear up some hurdles that I experienced when things were less clear than I would have liked in the documentation.
In case you'd like to check them out, here I'm sharing the links with you:
After reading Sime Vidas's answer, I searched more and found a very straight-forward and easy-to-understand explanation in the angular docs.
HTML attribute vs. DOM property
-------------------------------
Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).
A few HTML attributes have 1:1 mapping to properties.
id
is one example.Some HTML attributes don't have corresponding properties.
colspan
is one example.Some DOM properties don't have corresponding attributes.
textContent
is one example.Many HTML attributes appear to map to properties ... but not in the way you might think!
That last category is confusing until you grasp this general rule:
Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.
For example, when the browser renders
<input type="text" value="Bob">
, it creates a corresponding DOM node with avalue
property initialized to "Bob".When the user enters "Sally" into the input box, the DOM element
value
property becomes "Sally". But the HTMLvalue
attribute remains unchanged as you discover if you ask the input element about that attribute:input.getAttribute('value')
returns "Bob".The HTML attribute
value
specifies the initial value; the DOMvalue
property is the current value.
The
disabled
attribute is another peculiar example. A button'sdisabled
property isfalse
by default so the button is enabled. When you add thedisabled
attribute, its presence alone initializes the button'sdisabled
property totrue
so the button is disabled.Adding and removing the
disabled
attribute disables and enables the button. The value of the attribute is irrelevant, which is why you cannot enable a button by writing<button disabled="false">Still Disabled</button>.
Setting the button's
disabled
property disables or enables the button. The value of the property matters.The HTML attribute and the DOM property are not the same thing, even when they have the same name.
For completeness, I'll mention that Oracle 12c does support this feature. Also it's supposedly faster than the triggers approach. For example:
CREATE TABLE foo
(
id NUMBER GENERATED BY DEFAULT AS IDENTITY (
START WITH 1 NOCACHE ORDER ) NOT NULL ,
name VARCHAR2 (50)
)
LOGGING ;
ALTER TABLE foo ADD CONSTRAINT foo_PK PRIMARY KEY ( id ) ;
A bit more low-tech than leo's solution:
for i in */.git; do ( echo $i; cd $i/..; git pull; ); done
This will update all Git repositories in your working directory. No need to explicitly list their names ("cms", "admin", "chart"). The "cd" command only affects a subshell (spawned using the parenthesis).
Exception in thread "main" java.lang.NoClassDefFoundError
One of the places java tries to find your .class
file is your current directory. So if your .class
file is in C:\java
, you should change your current directory to that.
To change your directory, type the following command at the prompt and press Enter:
cd c:\java
This .
tells java that your classpath is your local directory.
Executing your program using this command should correct the problem:
java -classpath . HelloWorld
Use capitalize
. From the String documentation:
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
"hello".capitalize #=> "Hello"
"HELLO".capitalize #=> "Hello"
"123ABC".capitalize #=> "123abc"
In the simplest case, just do
X <- read.csv(url("http://some.where.net/data/foo.csv"))
plus which ever options read.csv()
may need.
Edit in Sep 2020 or 9 years later:
For a few years now R also supports directly passing the URL to read.csv
:
X <- read.csv("http://some.where.net/data/foo.csv")
End of 2020 edit. Original post continutes.
Long answer: Yes this can be done and many packages have use that feature for years. E.g. the tseries packages uses exactly this feature to download stock prices from Yahoo! for almost a decade:
R> library(tseries)
Loading required package: quadprog
Loading required package: zoo
‘tseries’ version: 0.10-24
‘tseries’ is a package for time series analysis and computational finance.
See ‘library(help="tseries")’ for details.
R> get.hist.quote("IBM")
trying URL 'http://chart.yahoo.com/table.csv? ## manual linebreak here
s=IBM&a=0&b=02&c=1991&d=5&e=08&f=2011&g=d&q=q&y=0&z=IBM&x=.csv'
Content type 'text/csv' length unknown
opened URL
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
........
downloaded 258 Kb
Open High Low Close
1991-01-02 112.87 113.75 112.12 112.12
1991-01-03 112.37 113.87 112.25 112.50
1991-01-04 112.75 113.00 111.87 112.12
1991-01-07 111.37 111.87 110.00 110.25
1991-01-08 110.37 110.37 108.75 109.00
1991-01-09 109.75 110.75 106.75 106.87
[...]
This is all exceedingly well documented in the manual pages for help(connection)
and help(url)
. Also see the manul on 'Data Import/Export' that came with R.
There is an option “unlimited scrollback buffer” which you can find under Preferences > Profiles > Terminal
or you can just pump up number of lines that you want to have in history in the same place.
The best solution is to use Dozer. You just need something like this in the mapper file:
<mapping map-id="myTestMapping">
<class-a>org.dozer.vo.map.SomeComplexType</class-a>
<class-b>java.util.Map</class-b>
</mapping>
And that's it, Dozer takes care of the rest!!!
#sides{_x000D_
margin:0;_x000D_
}_x000D_
#left{_x000D_
float:left;_x000D_
width:75%;_x000D_
overflow:hidden;_x000D_
}_x000D_
#right{_x000D_
float:left;_x000D_
width:25%;_x000D_
overflow:hidden;_x000D_
}
_x000D_
<h1 id="left">Left Side</h1>_x000D_
<h1 id="right">Right Side</h1>_x000D_
<!-- It Works!-->
_x000D_
Try it like this:
Sub testIt()
Dim r As Long, endRow as Long, pasteRowIndex As Long
endRow = 10 ' of course it's best to retrieve the last used row number via a function
pasteRowIndex = 1
For r = 1 To endRow 'Loop through sheet1 and search for your criteria
If Cells(r, Columns("B").Column).Value = "YourCriteria" Then 'Found
'Copy the current row
Rows(r).Select
Selection.Copy
'Switch to the sheet where you want to paste it & paste
Sheets("Sheet2").Select
Rows(pasteRowIndex).Select
ActiveSheet.Paste
'Next time you find a match, it will be pasted in a new row
pasteRowIndex = pasteRowIndex + 1
'Switch back to your table & continue to search for your criteria
Sheets("Sheet1").Select
End If
Next r
End Sub
Since the img is an inline element, Just use text-center
on it's container. Using mx-auto
will center the container (column) too.
<div class="row">
<div class="col-4 mx-auto text-center">
<img src="..">
</div>
</div>
By default, images are display:inline
. If you only want the center the image (and not the other column content), make the image display:block
using the d-block
class, and then mx-auto
will work.
<div class="row">
<div class="col-4">
<img class="mx-auto d-block" src="..">
</div>
</div>
IMHO, this looks better:
Chess *array = malloc(size * sizeof(Chess)); // array of pointers of size `size`
for ( int i =0; i < SOME_VALUE; ++i )
{
array[i] = (Chess) malloc(sizeof(Chess));
}
Here is the code
.showme{ _x000D_
display: none;_x000D_
}_x000D_
.showhim:hover .showme{_x000D_
display : block;_x000D_
}_x000D_
.showhim:hover .ok{_x000D_
display : none;_x000D_
}
_x000D_
<div class="showhim">_x000D_
HOVER ME_x000D_
<div class="showme">hai</div>_x000D_
<div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
Python functions always return a unique value. The comma operator is the constructor of tuples so self.first_name, self.last_name
evaluates to a tuple and that tuple is the actual value the function is returning.
The default is height: auto
in browser, but height: X%
Defines the height in percentage of the containing block.
Here is the right anwser:
ADD_EXECUTABLE(your_executable ${source_files})
TARGET_LINK_LIBRARIES( your_executable
pthread
)
equivalent to
-lpthread
Try the following code:
start=$(date +'%s') && sleep 5 && echo "It took $(($(date +'%s') - $start)) seconds"
You could make use of expect (man expect comes with examples).
A bin is range that represents the width of a single bar of the histogram along the X-axis. You could also call this the interval. (Wikipedia defines them more formally as "disjoint categories".)
The Numpy histogram
function doesn't draw the histogram, but it computes the occurrences of input data that fall within each bin, which in turns determines the area (not necessarily the height if the bins aren't of equal width) of each bar.
In this example:
np.histogram([1, 2, 1], bins=[0, 1, 2, 3])
There are 3 bins, for values ranging from 0 to 1 (excl 1.), 1 to 2 (excl. 2) and 2 to 3 (incl. 3), respectively. The way Numpy defines these bins if by giving a list of delimiters ([0, 1, 2, 3]
) in this example, although it also returns the bins in the results, since it can choose them automatically from the input, if none are specified. If bins=5
, for example, it will use 5 bins of equal width spread between the minimum input value and the maximum input value.
The input values are 1, 2 and 1. Therefore, bin "1 to 2" contains two occurrences (the two 1
values), and bin "2 to 3" contains one occurrence (the 2
). These results are in the first item in the returned tuple: array([0, 2, 1])
.
Since the bins here are of equal width, you can use the number of occurrences for the height of each bar. When drawn, you would have:
You can plot this directly with Matplotlib (its hist
function also returns the bins and the values):
>>> import matplotlib.pyplot as plt
>>> plt.hist([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]), <a list of 3 Patch objects>)
>>> plt.show()
The with
function will let you use shorthand column references and sum
will count TRUE
results from the expression(s).
sum(with(aaa, sex==1 & group1==2))
## [1] 3
sum(with(aaa, sex==1 & group2=="A"))
## [1] 2
As @mnel pointed out, you can also do:
nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3
nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2
The benefit of that is that you can do:
nrow(aaa)
## [1] 6
And, the behaviour matches Stata's count
almost exactly (syntax notwithstanding).
Use whoami /priv
command to list all the user privileges.
You use the hash mark like this
# This is a comment in Powershell
Wikipedia has a good page for keeping track of how to do comments in several popular languages
http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(syntax)#Comments
Project->maven->Update Project->tick all checkboxes expect offline and error is solved soon.
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";_x000D_
var person = {[key]:"John"};_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};_x000D_
var key = "name";_x000D_
_x000D_
person[key] /* this is same as person.name */ = "John";_x000D_
_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
This is default database :
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'mydatabase',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Add another database at the bottom of database.php file
$db['second'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'mysecond',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
In autoload.php config file
$autoload['libraries'] = array('database', 'email', 'session');
The default database is worked fine by autoload the database library but second database load and connect by using constructor in model and controller...
<?php
class Seconddb_model extends CI_Model {
function __construct(){
parent::__construct();
//load our second db and put in $db2
$this->db2 = $this->load->database('second', TRUE);
}
public function getsecondUsers(){
$query = $this->db2->get('members');
return $query->result();
}
}
?>
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh
is PDO db connecter, and based on id
from table users
we've get the username
using fetch();
I hope this help someone, Enjoy!
use curl php library: http://php.net/manual/en/book.curl.php
direct example: CURL_EXEC:
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>
Some of these above answers didn't work for me but this did. Just in case someone else has the same issue.
ng-show="column != 'vendorid' && column !='billingMonth'"
$('a[href$="ABC"]')...
Selector documentation can be found at http://docs.jquery.com/Selectors
For attributes:
= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")
One solution is to put them inside <center>
, like this:
<center>
<a href="http//www.google.com">Search</a>
<a href="Contact Us">Contact Us</a>
</center>
I've also created a jsfiddle for you: https://jsfiddle.net/9acgLf8e/
Use textContent
instead of value
to set the button text.
Typically the value attribute is used to associate a value with the button when it's submitted as form data.
Note that while it's possible to set the button text with innerHTML
, using textContext
should be preferred because it's more performant and it can prevent cross-site scripting attacks as its value is not parsed as HTML.
JS:
var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.textContent = 'test value';
var wrapper = document.getElementById("divWrapper");
wrapper.appendChild(b);
Produces this in the DOM:
<div id="divWrapper">
<button content="test content" class="btn">test value</button>
</div>
Sometimes things might be simpler. I came here with the exact issue and tried all the suggestions. But later found that the problem was just the local file path was different and I was on a different folder. :-)
eg -
~/myproject/mygitrepo/app/$ git diff app/TestFile.txt
should have been
~/myproject/mygitrepo/app/$ git diff TestFile.txt
In my opinion, android.text.format.DateFormat.getDateFormat(context)
makes me confused because this method returns java.text.DateFormat
rather than android.text.format.DateFormat
- -".
So, I use the fragment code as below to get the current date/time in my format.
android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());
or
android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());
In addition, you can use others formats. Follow DateFormat.
For "simple" strings (typically what fits into a line) the simplest solution is using fmt.Sprintf()
and friends (fmt.Sprint()
, fmt.Sprintln()
). These are analogous to the functions without the starter S
letter, but these Sxxx()
variants return the result as a string
instead of printing them to the standard output.
For example:
s := fmt.Sprintf("Hi, my name is %s and I'm %d years old.", "Bob", 23)
The variable s
will be initialized with the value:
Hi, my name is Bob and I'm 23 years old.
Tip: If you just want to concatenate values of different types, you may not automatically need to use Sprintf()
(which requires a format string) as Sprint()
does exactly this. See this example:
i := 23
s := fmt.Sprint("[age:", i, "]") // s will be "[age:23]"
For concatenating only string
s, you may also use strings.Join()
where you can specify a custom separator string
(to be placed between the strings to join).
Try these on the Go Playground.
If the string you're trying to create is more complex (e.g. a multi-line email message), fmt.Sprintf()
becomes less readable and less efficient (especially if you have to do this many times).
For this the standard library provides the packages text/template
and html/template
. These packages implement data-driven templates for generating textual output. html/template
is for generating HTML output safe against code injection. It provides the same interface as package text/template
and should be used instead of text/template
whenever the output is HTML.
Using the template
packages basically requires you to provide a static template in the form of a string
value (which may be originating from a file in which case you only provide the file name) which may contain static text, and actions which are processed and executed when the engine processes the template and generates the output.
You may provide parameters which are included/substituted in the static template and which may control the output generation process. Typical form of such parameters are struct
s and map
values which may be nested.
Example:
For example let's say you want to generate email messages that look like this:
Hi [name]!
Your account is ready, your user name is: [user-name]
You have the following roles assigned:
[role#1], [role#2], ... [role#n]
To generate email message bodies like this, you could use the following static template:
const emailTmpl = `Hi {{.Name}}!
Your account is ready, your user name is: {{.UserName}}
You have the following roles assigned:
{{range $i, $r := .Roles}}{{if $i}}, {{end}}{{.}}{{end}}
`
And provide data like this for executing it:
data := map[string]interface{}{
"Name": "Bob",
"UserName": "bob92",
"Roles": []string{"dbteam", "uiteam", "tester"},
}
Normally output of templates are written to an io.Writer
, so if you want the result as a string
, create and write to a bytes.Buffer
(which implements io.Writer
). Executing the template and getting the result as string
:
t := template.Must(template.New("email").Parse(emailTmpl))
buf := &bytes.Buffer{}
if err := t.Execute(buf, data); err != nil {
panic(err)
}
s := buf.String()
This will result in the expected output:
Hi Bob!
Your account is ready, your user name is: bob92
You have the following roles assigned:
dbteam, uiteam, tester
Try it on the Go Playground.
Also note that since Go 1.10, a newer, faster, more specialized alternative is available to bytes.Buffer
which is: strings.Builder
. Usage is very similar:
builder := &strings.Builder{}
if err := t.Execute(builder, data); err != nil {
panic(err)
}
s := builder.String()
Try this one on the Go Playground.
Note: you may also display the result of a template execution if you provide os.Stdout
as the target (which also implements io.Writer
):
t := template.Must(template.New("email").Parse(emailTmpl))
if err := t.Execute(os.Stdout, data); err != nil {
panic(err)
}
This will write the result directly to os.Stdout
. Try this on the Go Playground.
The ON UPDATE
and ON DELETE
specify which action will execute when a row in the parent table is updated and deleted. The following are permitted actions : NO ACTION
, CASCADE
, SET NULL
, and SET DEFAULT
.
If you delete one or more rows in the parent table, you can set one of the following actions:
ON DELETE NO ACTION
: SQL Server raises an error and rolls back the delete action on the row in the parent table.ON DELETE CASCADE
: SQL Server deletes the rows in the child table that is corresponding to the row deleted from the parent table.ON DELETE SET NULL
: SQL Server sets the rows in the child table to NULL if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must be nullable.ON DELETE SET DEFAULT
: SQL Server sets the rows in the child table to their default values if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must have default definitions. Note that a nullable column has a default value of NULL if no default value specified.
By default, SQL Server appliesON DELETE NO ACTION if you don’t explicitly specify any action.If you update one or more rows in the parent table, you can set one of the following actions:
ON UPDATE NO ACTION
: SQL Server raises an error and rolls back the update action on the row in the parent table.ON UPDATE CASCADE
: SQL Server updates the corresponding rows in the child table when the rows in the parent table are updated.ON UPDATE SET NULL
: SQL Server sets the rows in the child table to NULL when the corresponding row in the parent table is updated. Note that the foreign key columns must be nullable for this action to execute.ON UPDATE SET DEFAULT
: SQL Server sets the default values for the rows in the child table that have the corresponding rows in the parent table updated.FOREIGN KEY (foreign_key_columns)
REFERENCES parent_table(parent_key_columns)
ON UPDATE <action>
ON DELETE <action>;
I'm sure you are using a old version. You must use the last version available at master branch:
With python3, iterate on dic.keys() will raise the dictionary size error. You can use this alternative way:
Tested with python3, it works fine and the Error "dictionary changed size during iteration" is not raised:
my_dic = { 1:10, 2:20, 3:30 }
# Is important here to cast because ".keys()" method returns a dict_keys object.
key_list = list( my_dic.keys() )
# Iterate on the list:
for k in key_list:
print(key_list)
print(my_dic)
del( my_dic[k] )
print( my_dic )
# {}
One more way to do it (if you use form), note that input type is button
<input type="button" onclick="showMessage()" value="submit" />
Complete code is:
<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var message = document.getElementById("message").value;
display_message.innerHTML= message;
}
</script>
</head>
<body>
<form>
Enter message: <input type="text" id = "message">
<input type="button" onclick="showMessage()" value="submit" />
</form>
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>
But you can do it even without form:
<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var message = document.getElementById("message").value;
display_message.innerHTML= message;
}
</script>
</head>
<body>
Enter message: <input type="text" id = "message">
<input type="submit" onclick="showMessage()" value="submit" />
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>
Here you can use either submit or button:
<input type="submit" onclick="showMessage()" value="submit" />
No need to set
return false;
from JavaScript function for neither of those two examples.
This program can convert up to 102 digits long number. Suggestions and comments are highly appreciated.
package com.kegeesoft;
/**
* @author Chandana Gamage +94 710 980 120
* @author [email protected]
* @author KeGee Software Solutions
*/
import java.math.BigDecimal;
import java.math.BigInteger;
public class Converter {
private final BigInteger zero = new BigInteger("0");
private final BigInteger scale[] = new BigInteger[33];
private final String scaleName[] = {" Duotrigintillion"," Untrigintillion"," Trigintillion",
" Nonvigintillion"," Octovigintillion"," Septvigintillion",
" Sexvigintillion"," Quinvigintillion"," Quattuorvigintillion",
" Trevigintillion"," Duovigintillion"," Unvigintillion",
" Vigintillion"," Novemdecillion"," Octodecillion",
" Septemdecillion"," Sexdecillion"," Quindecillion",
" Quattuordecillion "," Tredecillion"," Duodecillion",
" Undecillion"," Decillion"," Nonillion"," Octillion",
" Septillion"," Sextillion"," Quintillion"," Quadrillion",
" Trillion"," Billion"," Million"," Thousand"};
private final String ones[] = {""," One"," Two"," Three"," Four"," Five"," Six"," Seven"," Eight"," Nine",
" Ten"," Eleven"," Twelve"," Thirteen"," Fourteen"," Fifteen"," Sixteen",
" Seventeen"," Eighteen"," Nineteen"};
private final String tens[] = {"",""," Twenty"," Thirty"," Forty"," Fifty"," Sixty"," Seventy"," Eighty"," Ninety"};
private int index = 0;
private String shortValueInWords = "";
private String output = "";
private String decimalInWords = "";
private String valueInWords;
public String setValue(BigInteger value) throws Exception{
return this.bigValueInWords(value);
}
public String setValue(BigDecimal value) throws Exception{
int indexOfDecimalPoint = (value.toString()).indexOf(".");
// Split and pass interger value of given decimal value to constructor
String tempIntValue = (value.toString()).substring(0, indexOfDecimalPoint);
BigInteger intValue = new BigInteger(tempIntValue);
// Split and pass decimal value of given decimal value to constructor
String tempDeciValue = (value.toString()).substring(indexOfDecimalPoint+1, value.toString().length());
BigInteger deciValue = new BigInteger(tempDeciValue);
this.bigValueInWords(intValue);
this.decimalValueInWords(deciValue);
return null;
}
public String setValue(BigDecimal value, String currencyName, String centsName) throws Exception{
int indexOfDecimalPoint = (value.toString()).indexOf(".");
// Split and pass interger value of given decimal value to constructor
String tempIntValue = (value.toString()).substring(0, indexOfDecimalPoint);
BigInteger intValue = new BigInteger(tempIntValue);
// Split and pass decimal value of given decimal value to constructor
String tempDeciValue = (value.toString()).substring(indexOfDecimalPoint+1, value.toString().length());
@SuppressWarnings("UnusedAssignment")
BigInteger deciValue = null;
// Concatenate "0" if decimal value has only single digit
if(tempDeciValue.length() == 1){
deciValue = new BigInteger(tempDeciValue.concat("0"));
}else{
deciValue = new BigInteger(tempDeciValue);
}
this.output = currencyName+" ";
this.bigValueInWords(intValue);
this.centsValueInWords(deciValue, centsName);
return null;
}
private String bigValueInWords(BigInteger value) throws Exception{
// Build scale array
int exponent = 99;
for (int i = 0; i < scale.length; i++) {
scale[i] = new BigInteger("10").pow(exponent);
exponent = exponent - 3;
}
/* Idntify whether given value is a minus value or not
if == yes then pass value without minus sign
and pass Minus word to output
*/
if(value.compareTo(zero) == -1){
value = new BigInteger(value.toString().substring(1,value.toString().length()));
output += "Minus ";
}
// Get value in words of big numbers (duotrigintillions to thousands)
for (int i=0; i < scale.length; i++) {
if((value.divide(scale[i])).compareTo(zero)==1){
this.index = (int)(value.divide(scale[i])).intValue();
output += shortValueInWords(this.index) + scaleName[i];
value = value.mod(scale[i]);
}
}
// Get value in words of short numbers (hundreds, tens and ones)
output += shortValueInWords((int)(value.intValue()));
// Get rid of any space at the beginning of output and return value in words
return this.valueInWords = output.replaceFirst("\\s", "");
}
private String shortValueInWords(int shortValue) throws Exception{
// Get hundreds
if(String.valueOf(shortValue).length()==3){
shortValueInWords = ones[shortValue / 100]+" Hundred"+shortValueInWords(shortValue % 100);
}
// Get tens
if(String.valueOf(shortValue).length()== 2 && shortValue >= 20){
if((shortValue / 10)>=2 && (shortValue % 10)>=0){
shortValueInWords = tens[shortValue / 10] + ones[shortValue % 10];
}
}
// Get tens between 10 and 20
if(String.valueOf(shortValue).length()== 2 && shortValue >= 10 && shortValue < 20){
shortValueInWords = ones[shortValue];
}
// Get ones
if(String.valueOf(shortValue).length()==1){
shortValueInWords = ones[shortValue];
}
return this.shortValueInWords;
}
private String decimalValueInWords(BigInteger decimalValue) throws Exception{
decimalInWords = " Point";
// Get decimals in point form (0.563 = zero point five six three)
for(int i=0; i < (decimalValue.toString().length()); i++){
decimalInWords += ones[Integer.parseInt(String.valueOf(decimalValue.toString().charAt(i)))];
}
return this.decimalInWords;
}
private String centsValueInWords(BigInteger decimalValue, String centsName) throws Exception{
decimalInWords = " and"+" "+centsName;
// Get cents in words (5.52 = five and cents fifty two)
if(decimalValue.intValue() == 0){
decimalInWords += shortValueInWords(decimalValue.intValue())+" Zero only";
}else{
decimalInWords += shortValueInWords(decimalValue.intValue())+" only";
}
return this.decimalInWords;
}
public String getValueInWords(){
return this.valueInWords + decimalInWords;
}
public static void main(String args[]){
Converter c1 = new Converter();
Converter c2 = new Converter();
Converter c3 = new Converter();
Converter c4 = new Converter();
try{
// Get integer value in words
c1.setValue(new BigInteger("15634886"));
System.out.println(c1.getValueInWords());
// Get minus integer value in words
c2.setValue(new BigInteger("-15634886"));
System.out.println(c2.getValueInWords());
// Get decimal value in words
c3.setValue(new BigDecimal("358621.56895"));
System.out.println(c3.getValueInWords());
// Get currency value in words
c4.setValue(new BigDecimal("358621.56"),"Dollar","Cents");
System.out.println(c4.getValueInWords());
}catch(Exception e){
e.printStackTrace();
}
}
}
The above answers may help you but you may also want to know how to use array of function pointers.
void fun1()
{
}
void fun2()
{
}
void fun3()
{
}
void (*func_ptr[3])() = {fun1, fun2, fun3};
main()
{
int option;
printf("\nEnter function number you want");
printf("\nYou should not enter other than 0 , 1, 2"); /* because we have only 3 functions */
scanf("%d",&option);
if((option>=0)&&(option<=2))
{
(*func_ptr[option])();
}
return 0;
}
You can only assign the addresses of functions with the same return type and same argument types and no of arguments to a single function pointer array.
You can also pass arguments like below if all the above functions are having the same number of arguments of same type.
(*func_ptr[option])(argu1);
Note: here in the array the numbering of the function pointers will be starting from 0 same as in general arrays. So in above example fun1
can be called if option=0, fun2
can be called if option=1 and fun3
can be called if option=2.
The error:
Tomcat: java.net.BindException: Address already in use: JVM_Bind :80
suggests that the port 80 is already in use.
You may either:
See also: Deployment error:Starting of Tomcat failed, the server port 8080 is already in use
I haven't seen a short, easy to understand answer here--so I'll give it a try.
With a shallow copy, any object pointed to by the source is also pointed to by the destination (so that no referenced objects are copied).
With a deep copy, any object pointed to by the source is copied and the copy is pointed to by the destination (so there will now be 2 of each referenced object). This recurses down the object tree.
For Developer certificate, you need to create a developer .mobileprovision profile and install add it to your XCode. In case you want to distribute the app using an adhoc distribution profile you will require AdHoc Distribution certificate and private key installed in your keychain.
If you have not created the cert, here are steps to create it. Incase it has already been created by someone in your team, ask him to share the cert and private key. If that someone is no longer in your team then you can revoke the cert from developer account and create new.
Please find below example to load image using JavaFX.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class LoadImage extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Load Image");
StackPane sp = new StackPane();
Image img = new Image("javafx.jpg");
ImageView imgView = new ImageView(img);
sp.getChildren().add(imgView);
//Adding HBox to the scene
Scene scene = new Scene(sp);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Create one source folder with name Image in your project and add your image to that folder otherwise you can directly load image from external URL like following.
Image img = new Image("http://mikecann.co.uk/wp-content/uploads/2009/12/javafx_logo_color_1.jpg");
U can try below code snippet
public Uri getUri(ContentResolver cr, String path){
Uri mediaUri = MediaStore.Files.getContentUri(VOLUME_NAME);
Cursor ca = cr.query(mediaUri, new String[] { MediaStore.MediaColumns._ID }, MediaStore.MediaColumns.DATA + "=?", new String[] {path}, null);
if (ca != null && ca.moveToFirst()) {
int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
ca.close();
return MediaStore.Files.getContentUri(VOLUME_NAME,id);
}
if(ca != null) {
ca.close();
}
return null;
}
Using the SVG from @ArnoTenkink as an data url combined with the accepted answer, this gives us the perfect solution for retina displays.
select.form-control:not([multiple]) {
border-radius: 0;
appearance: none;
background-position: right 50%;
background-repeat: no-repeat;
background-image: url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%20%3C%21DOCTYPE%20svg%20PUBLIC%20%22-//W3C//DTD%20SVG%201.1//EN%22%20%22http%3A//www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22%3E%20%3Csvg%20version%3D%221.1%22%20id%3D%22Layer_1%22%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20x%3D%220px%22%20y%3D%220px%22%20width%3D%2214px%22%20height%3D%2212px%22%20viewBox%3D%220%200%2014%2012%22%20enable-background%3D%22new%200%200%2014%2012%22%20xml%3Aspace%3D%22preserve%22%3E%20%3Cpolygon%20points%3D%223.862%2C7.931%200%2C4.069%207.725%2C4.069%20%22/%3E%3C/svg%3E);
padding: .5em;
padding-right: 1.5em
}
string path=@"E:\AppServ\Example.txt";
if(!File.Exists(path))
{
File.Create(path).Dispose();
using( TextWriter tw = new StreamWriter(path))
{
tw.WriteLine("The very first line!");
}
}
else if (File.Exists(path))
{
using(TextWriter tw = new StreamWriter(path))
{
tw.WriteLine("The next line!");
}
}
Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
You can use:
var dictionary = myList.ToDictionary(x => x);
Change appBase
in server.xml
If you want to keep both previous webapps and a new one, you can use another Host instance with another port defined in tomcat.
you can just do $scope.todo = Todo.get({ id: 123 })
. .get()
and .query()
on a Resource return an object immediately and fill it with the result of the promise later (to update your template). It's not a typical promise which is why you need to either use a callback or the $promise property if you have some special code you want executed after the call. But there is no need to assign it to your scope in a callback if you are only using it in the template.
A good plugin that I have used before is DataTables.
At the time of writing, here's the best pure CSS implementation for color manipulation I found:
Use CSS variables to define your colors in HSL instead of HEX/RGB format, then use calc()
to manipulate them.
Here's a basic example:
:root {_x000D_
--link-color-h: 211;_x000D_
--link-color-s: 100%;_x000D_
--link-color-l: 50%;_x000D_
--link-color-hsl: var(--link-color-h), var(--link-color-s), var(--link-color-l);_x000D_
_x000D_
--link-color: hsl(var(--link-color-hsl));_x000D_
--link-color-10: hsla(var(--link-color-hsl), .1);_x000D_
--link-color-20: hsla(var(--link-color-hsl), .2);_x000D_
--link-color-30: hsla(var(--link-color-hsl), .3);_x000D_
--link-color-40: hsla(var(--link-color-hsl), .4);_x000D_
--link-color-50: hsla(var(--link-color-hsl), .5);_x000D_
--link-color-60: hsla(var(--link-color-hsl), .6);_x000D_
--link-color-70: hsla(var(--link-color-hsl), .7);_x000D_
--link-color-80: hsla(var(--link-color-hsl), .8);_x000D_
--link-color-90: hsla(var(--link-color-hsl), .9);_x000D_
_x000D_
--link-color-warm: hsl(calc(var(--link-color-h) + 80), var(--link-color-s), var(--link-color-l));_x000D_
--link-color-cold: hsl(calc(var(--link-color-h) - 80), var(--link-color-s), var(--link-color-l));_x000D_
_x000D_
--link-color-low: hsl(var(--link-color-h), calc(var(--link-color-s) / 2), var(--link-color-l));_x000D_
--link-color-lowest: hsl(var(--link-color-h), calc(var(--link-color-s) / 4), var(--link-color-l));_x000D_
_x000D_
--link-color-light: hsl(var(--link-color-h), var(--link-color-s), calc(var(--link-color-l) / .9));_x000D_
--link-color-dark: hsl(var(--link-color-h), var(--link-color-s), calc(var(--link-color-l) * .9));_x000D_
}_x000D_
_x000D_
.flex {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.flex > div {_x000D_
flex: 1;_x000D_
height: calc(100vw / 10);_x000D_
}
_x000D_
<h3>Color Manipulation (alpha)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
<div style="background-color: var(--link-color-10)"></div>_x000D_
<div style="background-color: var(--link-color-20)"></div>_x000D_
<div style="background-color: var(--link-color-30)"></div>_x000D_
<div style="background-color: var(--link-color-40)"></div>_x000D_
<div style="background-color: var(--link-color-50)"></div>_x000D_
<div style="background-color: var(--link-color-60)"></div>_x000D_
<div style="background-color: var(--link-color-70)"></div>_x000D_
<div style="background-color: var(--link-color-80)"></div>_x000D_
<div style="background-color: var(--link-color-90)"></div>_x000D_
<div style="background-color: var(--link-color)"></div>_x000D_
</div>_x000D_
_x000D_
<h3>Color Manipulation (Hue)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
<div style="background-color: var(--link-color-warm)"></div>_x000D_
<div style="background-color: var(--link-color)"></div>_x000D_
<div style="background-color: var(--link-color-cold)"></div>_x000D_
</div>_x000D_
_x000D_
<h3>Color Manipulation (Saturation)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
<div style="background-color: var(--link-color)"></div>_x000D_
<div style="background-color: var(--link-color-low)"></div>_x000D_
<div style="background-color: var(--link-color-lowest)"></div>_x000D_
</div>_x000D_
_x000D_
<h3>Color Manipulation (Lightness)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
<div style="background-color: var(--link-color-light)"></div>_x000D_
<div style="background-color: var(--link-color)"></div>_x000D_
<div style="background-color: var(--link-color-dark)"></div>_x000D_
</div>
_x000D_
I also created a CSS framework (still in early stage) to provide basic CSS variables support called root-variables.
Don't double click Project.xcodeproj to start your xcode project. Instead, close your project and open the xcworkspace.
File -> Close Workspace
File -> Open -> Search your project folder for Project.xcworkspace
All my errors are gone.
The only surefire option to find the current session.save_path
value is always to check with phpinfo()
in exactly the environment where you want to find out the session storage directory.
Reason: there can be all sorts of things that change session.save_path
, either by overriding the php.ini
value or by setting it at runtime with ini_set('session.save_path','/path/to/folder');
. For example, web server management panels like ISPConfig, Plesk etc. often adapt this to give each website its own directory with session files.
An even simpler way to share the data between controllers is using nested data structures. Instead of, for example
$scope.customer = {};
we can use
$scope.data = { customer: {} };
The data
property will be inherited from parent scope so we can overwrite its fields, keeping the access from other controllers.
In addition to the provided answer, there are more details to navigate
. From the function's comments:
/**
* Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute.
*
* Returns a promise that:
* - resolves to 'true' when navigation succeeds,
* - resolves to 'false' when navigation fails,
* - is rejected when an error happens.
*
* ### Usage
*
* ```
* router.navigate(['team', 33, 'user', 11], {relativeTo: route});
*
* // Navigate without updating the URL
* router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
* ```
*
* In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
* URL.
*/
The Router Guide has more details on programmatic navigation.
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:
dig @ns1.nameserver1.com domain.com txt
If you're looking to use the standard construct of element = element1 || element2 where JavaScript will return the first one that is truthy, you could do exactly that:
element = $('#someParentElement .somethingToBeFound') || $('#someParentElement .somethingElseToBeFound');
which would return the first element that is actually found. But a better way would probably be to use the jQuery selector comma construct (which returns an array of found elements) in this fashion:
element = $('#someParentElement').find('.somethingToBeFound, .somethingElseToBeFound')[0];
which will return the first found element.
I use that from time to time to find either an active element in a list or some default element if there is no active element. For example:
element = $('ul#someList').find('li.active, li:first')[0]
which will return any li with a class of active or, should there be none, will just return the last li.
Either will work. There are potential performance penalties, though, as the || will stop processing as soon as it finds something truthy whereas the array approach will try to find all elements even if it has found one already. Then again, using the || construct could potentially have performance issues if it has to go through several selectors before finding the one it will return, because it has to call the main jQuery object for each one (I really don't know if this is a performance hit or not, it just seems logical that it could be). In general, though, I use the array approach when the selector is a rather long string.
pandas.DataFrame.plot()
, matplotlib.axes.Axes
is returned when creating a plot from a dataframe. As such, the dataframe plot can be assigned to a variable, ax
, which enables the usage of the associated formatting methods.pandas
, is matplotlib
.import pandas as pd
# test dataframe
data = {'a': range(20), 'date': pd.bdate_range('2021-01-09', freq='D', periods=20)}
df = pd.DataFrame(data)
# plot the dataframe and assign the returned axes
ax = df.plot(x='date', color='green', ylabel='values', xlabel='date', figsize=(8, 6))
# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red')
ax.spines['right'].set_color('magenta')
ax.spines['left'].set_color('orange')
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both') # 'both' refers to minor and major axes
restart your computer and run $sudo deluser username... worked for me
Here is one way which I like because it makes the input fill out the whole container. The trick is the "font-size: 100px", and it need to go with the "overflow: hidden" and the relative position.
<div id="upload-file-container" >
<input type="file" />
</div>
#upload-file-container {
width: 200px;
height: 50px;
position: relative;
border: dashed 1px black;
overflow: hidden;
}
#upload-file-container input[type="file"]
{
margin: 0;
opacity: 0;
font-size: 100px;
}
Similar to Antonio Val's p-iteration
, an alternative npm module is async-af
:
const AsyncAF = require('async-af');
const fs = require('fs-promise');
function printFiles() {
// since AsyncAF accepts promises or non-promises, there's no need to await here
const files = getFilePaths();
AsyncAF(files).forEach(async file => {
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
});
}
printFiles();
Alternatively, async-af
has a static method (log/logAF) that logs the results of promises:
const AsyncAF = require('async-af');
const fs = require('fs-promise');
function printFiles() {
const files = getFilePaths();
AsyncAF(files).forEach(file => {
AsyncAF.log(fs.readFile(file, 'utf8'));
});
}
printFiles();
However, the main advantage of the library is that you can chain asynchronous methods to do something like:
const aaf = require('async-af');
const fs = require('fs-promise');
const printFiles = () => aaf(getFilePaths())
.map(file => fs.readFile(file, 'utf8'))
.forEach(file => aaf.log(file));
printFiles();
vcbuild.exe
on your environment variable PATH
vcbuild.exe
get it here https://github.com/kin9puppy/vcbuildFixForNodeThis links might be helpful to convert.
https://code.google.com/p/flying-saucer/
https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html
If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm
Example is given to convert HTML to PDF
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
You can set tag to fragment in this way:
Fragment fragmentA = new FragmentA();
getFragmentManager().beginTransaction()
.replace(R.id.MainFrameLayout,fragmentA,"YOUR_TARGET_FRAGMENT_TAG")
.addToBackStack("YOUR_SOURCE_FRAGMENT_TAG").commit();
foreach(var item in list.ToList())
{
if(item.Delete) list.Remove(item);
}
Simply create an entirely new list from the first one. I say "Easy" rather than "Right" as creating an entirely new list probably comes at a performance premium over the previous method (I haven't bothered with any benchmarking.) I generally prefer this pattern, it can also be useful in overcoming Linq-To-Entities limitations.
for(i = list.Count()-1;i>=0;i--)
{
item=list[i];
if (item.Delete) list.Remove(item);
}
This way cycles through the list backwards with a plain old For loop. Doing this forwards could be problematic if the size of the collection changes, but backwards should always be safe.
To zoom relative to the mouse position, all you need is:
var position = e.GetPosition(image1);
image1.RenderTransformOrigin = new Point(position.X / image1.ActualWidth, position.Y / image1.ActualHeight);
One way of doing it is to use the ClientScriptManager
:
Page.ClientScript.RegisterStartupScript(
GetType(),
"MyKey",
"Myfunction();",
true);
Use 1) form with tokens 2) Check form to form delay with IP address 3) Block IP (optional)
One liner:
string[] items = new string[] { "a", "b" };
// this adds "c" to the string array:
items = new List<string>(items) { "c" }.ToArray();
The field nbytes will give you the size in bytes of all the elements of the array in a numpy.array
:
size_in_bytes = my_numpy_array.nbytes
Notice that this does not measures "non-element attributes of the array object" so the actual size in bytes can be a few bytes larger than this.
I found this:
http://www.robvanderwoude.com/commandlineswitches.php#Acrobat
Open a PDF file with navigation pane active, zoom out to 50%, and search for and highlight the word "batch":
AcroRd32.exe /A "zoom=50&navpanes=1=OpenActions&search=batch" PdfFile
Using Zend_Date it's pretty easy:
$date->setDay($date->get(Zend_Date::MONTH_DAYS));
The function has to be declared before it's getting called. This could be done in various ways:
Write down the prototype in a header
Use this if the function shall be callable from several source files. Just write your prototype
int Fibonacci(int number);
down in a .h
file (e.g. myfunctions.h
) and then #include "myfunctions.h"
in the C code.
Move the function before it's getting called the first time
This means, write down the function
int Fibonacci(int number){..}
before your main()
function
Explicitly declare the function before it's getting called the first time
This is the combination of the above flavors: type the prototype of the function in the C file before your main()
function
As an additional note: if the function int Fibonacci(int number)
shall only be used in the file where it's implemented, it shall be declared static
, so that it's only visible in that translation unit.
open file, save as .csv and then apply
df = pd.read_csv('apps.csv', sep='\t')
for any other format also, just change the sep tag
Simple like this:
import math
def my_cdf(x):
return 0.5*(1+math.erf(x/math.sqrt(2)))
I found the formula in this page https://www.danielsoper.com/statcalc/formulas.aspx?id=55
Why use a complicated solution if a simple one works too?
.child {
white-space: normal;
}
This way worked for me when adding random data to MySql table using a python script.
First install the following packages using the below commands
pip install mysql-connector-python<br>
pip install random
import mysql.connector
import random
from datetime import date
start_dt = date.today().replace(day=1, month=1).toordinal()
end_dt = date.today().toordinal()
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="your_db_name"
)
mycursor = mydb.cursor()
sql_insertion = "INSERT INTO customer (name,email,address,dateJoined) VALUES (%s, %s,%s, %s)"
#insert 10 records(rows)
for x in range(1,11):
#generate a random date
random_day = date.fromordinal(random.randint(start_dt, end_dt))
value = ("customer" + str(x),"customer_email" + str(x),"customer_address" + str(x),random_day)
mycursor.execute(sql_insertion , value)
mydb.commit()
print("customer records inserted!")
Following is a sample output of the insertion
cid | name | email | address | dateJoined |
1 | customer1 | customer_email1 | customer_address1 | 2020-11-15 |
2 | customer2 | customer_email2 | customer_address2 | 2020-10-11 |
3 | customer3 | customer_email3 | customer_address3 | 2020-11-17 |
4 | customer4 | customer_email4 | customer_address4 | 2020-09-20 |
5 | customer5 | customer_email5 | customer_address5 | 2020-02-18 |
6 | customer6 | customer_email6 | customer_address6 | 2020-01-11 |
7 | customer7 | customer_email7 | customer_address7 | 2020-05-30 |
8 | customer8 | customer_email8 | customer_address8 | 2020-04-22 |
9 | customer9 | customer_email9 | customer_address9 | 2020-01-05 |
10 | customer10 | customer_email10| customer_address10| 2020-11-12 |
I was having same problem.
Use @javax.persistence.Entity
instead of org.hibernate.annotations.Entity
This will remove complete tag :
$("body").removeAttr("style");
You can implement a system that handles the type checks automatically, using a wrapper in your function.
With this approach, you can build a complete
declarative type check system
that will manage for you the type checks . If you are interested in taking a more in depth look at this concept, check the Functyped library
The following implementation illustrates the main idea, in a simplistic, but operative way :
/*_x000D_
* checkType() : Test the type of the value. If succeds return true, _x000D_
* if fails, throw an Error_x000D_
*/_x000D_
function checkType(value,type, i){_x000D_
// perform the appropiate test to the passed _x000D_
// value according to the provided type_x000D_
switch(type){_x000D_
case Boolean : _x000D_
if(typeof value === 'boolean') return true;_x000D_
break;_x000D_
case String : _x000D_
if(typeof value === 'string') return true;_x000D_
break;_x000D_
case Number : _x000D_
if(typeof value === 'number') return true;_x000D_
break;_x000D_
default :_x000D_
throw new Error(`TypeError : Unknown type provided in argument ${i+1}`);_x000D_
}_x000D_
// test didn't succeed , throw error_x000D_
throw new Error(`TypeError : Expecting a ${type.name} in argument ${i+1}`);_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
* typedFunction() : Constructor that returns a wrapper_x000D_
* to handle each function call, performing automatic _x000D_
* arguments type checking_x000D_
*/_x000D_
function typedFunction( parameterTypes, func ){_x000D_
// types definitions and function parameters _x000D_
// count must match_x000D_
if(parameterTypes.length !== func.length) throw new Error(`Function has ${func.length} arguments, but type definition has ${parameterTypes.length}`);_x000D_
// return the wrapper..._x000D_
return function(...args){_x000D_
// provided arguments count must match types_x000D_
// definitions count_x000D_
if(parameterTypes.length !== args.length) throw new Error(`Function expects ${func.length} arguments, instead ${args.length} found.`);_x000D_
// iterate each argument value, and perform a_x000D_
// type check against it, using the type definitions_x000D_
// provided in the construction stage_x000D_
for(let i=0; i<args.length;i++) checkType( args[i], parameterTypes[i] , i)_x000D_
// if no error has been thrown, type check succeed_x000D_
// execute function!_x000D_
return func(...args);_x000D_
}_x000D_
}_x000D_
_x000D_
// Play time! _x000D_
// Declare a function that expects 2 Numbers_x000D_
let myFunc = typedFunction( [ Number, Number ], (a,b)=>{_x000D_
return a+b;_x000D_
});_x000D_
_x000D_
// call the function, with an invalid second argument_x000D_
myFunc(123, '456')_x000D_
// ERROR! Uncaught Error: TypeError : Expecting a Number in argument 2
_x000D_
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
The question has been answered, but for your future coding reference you might like to consider this.
In your HTML, add the name as an attribute to the button and remove the onclick reference.
<button id="button" data-name="Mathew" type="button">click</button>
In your JavaScript, grab the button using its ID, assign the function to the button's click
event, and use the function to display the button's data-name attribute.
var button = document.getElementById('button');
button.onclick = myfunction;
function myfunction() {
var name = this.getAttribute('data-name');
alert(name);
}
Here are simple steps that minimize tedium and don't require error-prone semi-automated scripts or pricey tools.
Keep in mind that you can generate DROP/CREATE statements for multiple objects from the Object Explorer Details window (when generated this way, DROP and CREATE scripts are grouped, which makes it easy to insert logic between Drop and Create actions):
If you have smaller projects where it might make sense to change the infrastructure architecture, consider eliminating user-defined table types. Entity Framework and similar tools allow you to move most, if not all, of your data logic to your code base where it's easier to maintain.
An example:
log4j.rootLogger=ERROR, logfile
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false
log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
The Use of Razor code @Html.Hidden or @Html.HiddenFor is similar to the following Html code
<input type="hidden"/>
And also refer the following link
For elements with dynamic width it's possible to use transform: translateX(-100%);
to counter the horizontal percentage value. This leads to two possible solutions:
Transition from:
transform: translateX(0);
to
transform: translateX(calc(100vw - 100%));
#viewportPendulum {_x000D_
position: fixed;_x000D_
left: 0;_x000D_
top: 0;_x000D_
animation: 2s ease-in-out infinite alternate swingViewport;_x000D_
/* just for styling purposes */_x000D_
background: #c70039;_x000D_
padding: 1rem;_x000D_
color: #fff;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingViewport {_x000D_
from {_x000D_
transform: translateX(0);_x000D_
}_x000D_
to {_x000D_
transform: translateX(calc(100vw - 100%));_x000D_
}_x000D_
}
_x000D_
<div id="viewportPendulum">Viewport</div>
_x000D_
Transition from:
transform: translateX(0);
left: 0;
to
left: 100%;
transform: translateX(-100%);
#parentPendulum {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
animation: 2s ease-in-out infinite alternate swingParent;_x000D_
/* just for styling purposes */_x000D_
background: #c70039;_x000D_
padding: 1rem;_x000D_
color: #fff;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingParent {_x000D_
from {_x000D_
transform: translateX(0);_x000D_
left: 0;_x000D_
}_x000D_
to {_x000D_
left: 100%;_x000D_
transform: translateX(-100%);_x000D_
}_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
padding: 2rem 0;_x000D_
margin: 2rem 15%;_x000D_
background: #eee;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div id="parentPendulum">Parent</div>_x000D_
</div>
_x000D_
Note: This approach can easily be extended to work for vertical positioning. Visit example here.
Actually what made this so confusing is that the Beanstalk people stand behind their very non-standard use of Staging (it comes before development in their diagram, and it's not a mistake!
Many SQL databases allow a table to contain a subtable as a component. The usual method is to allow the domain of one of the columns to be a table. This is in addition to using some convention like CSV to encode the substructure in ways unknown to the DBMS.
When Ed Codd was developing the relational model in 1969-1970, he specifically defined a normal form that would disallow this kind of nesting of tables. Normal form was later called First Normal Form. He then went on to show that for every database, there is a database in first normal form that expresses the same information.
Why bother with this? Well, databases in first normal form permit keyed access to all data. If you provide a table name, a key value into that table, and a column name, the database will contain at most one cell containing one item of data.
If you allow a cell to contain a list or a table or any other collection, now you can't provide keyed access to the sub items, without completely reworking the idea of a key.
Keyed access to all data is fundamental to the relational model. Without this concept, the model isn't relational. As to why the relational model is a good idea, and what might be the limitations of that good idea, you have to look at the 50 years worth of accumulated experience with the relational model.
we have to create your own docker volume mapped with the host directory before we mention in the docker-compose.yml as external
1.Create volume named share
docker volume create --driver local \
--opt type=none \
--opt device=/home/mukundhan/share \
--opt o=bind share
2.Use it in your docker-compose
version: "3"
volumes:
share:
external: true
services:
workstation:
container_name: "workstation"
image: "ubuntu"
stdin_open: true
tty: true
volumes:
- share:/share:consistent
- ./source:/source:consistent
working_dir: /source
ipc: host
privileged: true
shm_size: '2gb'
db:
container_name: "db"
image: "ubuntu"
stdin_open: true
tty: true
volumes:
- share:/share:consistent
working_dir: /source
ipc: host
This way we can share the same directory with many services running in different containers
You have more than one form tags with runat="server" on your template, most probably you have one in your master page, remove one on your aspx page, it is not needed if already have form in master page file which is surrounding your content place holders.
Try to remove that tag:
<form id="formID" runat="server">
and of course closing tag:
</form>
git stash apply n
works as of git version 2.11
Original answer, possibly helping to debug issues with the older syntax involving shell escapes:
As pointed out previously, the curly braces may require escaping or quoting depending on your OS, shell, etc.
See "stash@{1} is ambiguous?" for some detailed hints of what may be going wrong, and how to work around it in various shells and platforms.
git stash list
git stash apply stash@{n}
Try trimming the string to make sure there is no extra white space:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
Also use c.moveToFirst()
like @thinksteep mentioned.
This is a complete code for select statements.
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
do {
// Passing values
String column1 = c.getString(0);
String column2 = c.getString(1);
String column3 = c.getString(2);
// Do something Here with values
} while(c.moveToNext());
}
c.close();
db.close();
increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin
heap size can be changed based on Requirements.
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m
In Oracle, you could use rownum
to limit the number of rows returned. I am guessing similar construct exists in other SQLs as well. So, for the example you gave, you could limit the number of rows returned to 500001 and apply a count(*)
then:
SELECT (case when cnt > 500000 then 500000 else cnt end) myCnt
FROM (SELECT count(*) cnt FROM table WHERE rownum<=500001)
A char array is just that - an array of characters:
A string is a class that contains a char array, but automatically manages it for you. Most string implementations have a built-in array of 16 characters (so short strings don't fragment the heap) and use the heap for longer strings.
You can access a string's char array like this:
std::string myString = "Hello World";
const char *myStringChars = myString.c_str();
C++ strings can contain embedded \0 characters, know their length without counting, are faster than heap-allocated char arrays for short texts and protect you from buffer overruns. Plus they're more readable and easier to use.
However, C++ strings are not (very) suitable for usage across DLL boundaries, because this would require any user of such a DLL function to make sure he's using the exact same compiler and C++ runtime implementation, lest he risk his string class behaving differently.
Normally, a string class would also release its heap memory on the calling heap, so it will only be able to free memory again if you're using a shared (.dll or .so) version of the runtime.
In short: use C++ strings in all your internal functions and methods. If you ever write a .dll or .so, use C strings in your public (dll/so-exposed) functions.
From the docs
To whitelist an entire hash of parameters, the permit! method can be used
params.require(:log_entry).permit!
Nested attributes are in the form of a hash. In my app, I have a Question.rb model accept nested attributes for an Answer.rb model (where the user creates answer choices for a question he creates). In the questions_controller, I do this
def question_params
params.require(:question).permit!
end
Everything in the question hash is permitted, including the nested answer attributes. This also works if the nested attributes are in the form of an array.
Having said that, I wonder if there's a security concern with this approach because it basically permits anything that's inside the hash without specifying exactly what it is, which seems contrary to the purpose of strong parameters.
Building on @Peter's solution, here's a version that declares a simple LINQ-style Permutations()
extension method that works on any IEnumerable<T>
.
Usage (on string characters example):
foreach (var permutation in "abc".Permutations())
{
Console.WriteLine(string.Join(", ", permutation));
}
Outputs:
a, b, c
a, c, b
b, a, c
b, c, a
c, b, a
c, a, b
Or on any other collection type:
foreach (var permutation in (new[] { "Apples", "Oranges", "Pears"}).Permutations())
{
Console.WriteLine(string.Join(", ", permutation));
}
Outputs:
Apples, Oranges, Pears
Apples, Pears, Oranges
Oranges, Apples, Pears
Oranges, Pears, Apples
Pears, Oranges, Apples
Pears, Apples, Oranges
using System;
using System.Collections.Generic;
using System.Linq;
public static class PermutationExtension
{
public static IEnumerable<T[]> Permutations<T>(this IEnumerable<T> source)
{
var sourceArray = source.ToArray();
var results = new List<T[]>();
Permute(sourceArray, 0, sourceArray.Length - 1, results);
return results;
}
private static void Swap<T>(ref T a, ref T b)
{
T tmp = a;
a = b;
b = tmp;
}
private static void Permute<T>(T[] elements, int recursionDepth, int maxDepth, ICollection<T[]> results)
{
if (recursionDepth == maxDepth)
{
results.Add(elements.ToArray());
return;
}
for (var i = recursionDepth; i <= maxDepth; i++)
{
Swap(ref elements[recursionDepth], ref elements[i]);
Permute(elements, recursionDepth + 1, maxDepth, results);
Swap(ref elements[recursionDepth], ref elements[i]);
}
}
}
LinkedIn revised their site recently, so there are a ton of old links just redirecting to the developer support homepage. Here is an updated link to the relevant page on LinkedIn's support site (as of Feb 16, 2015): https://developer.linkedin.com/docs/share-on-linkedin
There's no prepackaged "do-while", but the general Python way to implement peculiar looping constructs is through generators and other iterators, e.g.:
import itertools
def dowhile(predicate):
it = itertools.repeat(None)
for _ in it:
yield
if not predicate(): break
so, for example:
i=7; j=3
for _ in dowhile(lambda: i<j):
print i, j
i+=1; j-=1
executes one leg, as desired, even though the predicate's already false at the start.
It's normally better to encapsulate more of the looping logic into your generator (or other iterator) -- for example, if you often have cases where one variable increases, one decreases, and you need a do/while loop comparing them, you could code:
def incandec(i, j, delta=1):
while True:
yield i, j
if j <= i: break
i+=delta; j-=delta
which you can use like:
for i, j in incandec(i=7, j=3):
print i, j
It's up to you how much loop-related logic you want to put inside your generator (or other iterator) and how much you want to have outside of it (just like for any other use of a function, class, or other mechanism you can use to refactor code out of your main stream of execution), but, generally speaking, I like to see the generator used in a for
loop that has little (ideally none) "loop control logic" (code related to updating state variables for the next loop leg and/or making tests about whether you should be looping again or not).
Uninstall Java (via Control Panel / Programs and Features)
Install Java JRE 7 --> OFFLINE <--
Configure JAVA_HOME and Path = %JAVA_HOME%/bin;%PATH%
OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.
First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?
I had previously touched this subject in this article:
Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.
You have some variables that are different types in Java language like that:
message of type string
timestamp of type time
count of type integer
version of type integer
If you use a HashMap like:
HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put("message","message");
yourHash.put("timestamp",timestamp);
yourHash.put("count ",count);
yourHash.put("version ",version);
If you want to use the yourHash:
for(String key : yourHash.keySet()){
String message = (String) yourHash.get(key);
Datetime timestamp= (Datetime) yourHash.get(key);
int timestamp= (int) yourHash.get(key);
}
You can -Xours
or -Xtheirs
with git merge
as well. So:
git reset --hard HEAD
)git merge -Xours
or git merge -Xtheirs
)DISCLAIMER: of course you can choose only one option, either -Xours
or -Xtheirs
, do use different strategy you should of course go file by file.
I do not know if there is a way for checkout
, but I do not honestly think it is terribly useful: selecting the strategy with the checkout command is useful if you want different solutions for different files, otherwise just go for the merge strategy approach.
here is the one working fine:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://www.yahoo.com"))
printer = QPrinter()
printer.setPageSize(QPrinter.A4)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("fileOK.pdf")
def convertIt():
web.print_(printer)
print("Pdf generated")
QApplication.exit()
QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)
sys.exit(app.exec_())
You can add log4jdbc to your project. This adds logging of sql commands as they execute + a lot of other information.
You might want to do something like this (if you're using java 5 and more)
Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt())
{
tall[i++] = scanner.nextInt();
}
Via Julian Grenier from Reading Integers From A File In An Array
You can use the following commands:
To save your uncommitted changes
git stash
To list your saved stashes
git stash list
To apply/get back the uncommited changes where x is 0,1,2...
git stash apply stash@{x}
Note:
To apply a stash and remove it from the stash list
git stash pop stash@{x}
To apply a stash and keep it in the stash list
git stash apply stash@{x}
<resource>
<string name="your_string_here">This is an <u>underline</u>.</string>
</resources>
If it does not work then
<resource>
<string name="your_string_here">This is an <u>underline</u>.</string>
Because "<" could be a keyword at some time.
And for Displaying
TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(getString(R.string.your_string_here)));
You can use flatMap
to flatten the internal lists (after converting them to Streams) into a single Stream, and then collect the result into a list:
List<List<Object>> list = ...
List<Object> flat =
list.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
Here is a simple function to generate timestamp in the format: mm/dd/yy hh:mi:ss
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
Note that PIL will not apply the EXIF rotation information (at least up to v7.1.1; used in many jpgs). A quick fix to accomodate this:
def get_image_dims(file_path):
from PIL import Image as pilim
im = pilim.open(file_path)
# returns (w,h) after rotation-correction
return im.size if im._getexif().get(274,0) < 5 else im.size[::-1]
Now you can use new html5 input validation attribute pattern=".+\.(xlsx|xls|csv)"
.
I like using a package.json file in the root of your app folder.
Here is one I use
nvm use v0.6.4
npm install
Yes, your serving of the policy file can definitely cause the crash.
To repeat, just add a delay to your code:
net.createServer( function(socket)
{
for (i=0; i<1000000000; i++) ;
socket.write("<?xml version=\"1.0\"?>\n");
…
… and use telnet
to connect to the port. If you disconnect telnet before the delay has expired, you'll get a crash (uncaught exception) when socket.write throws an error.
To avoid the crash here, just add an error handler before reading/writing the socket:
net.createServer(function(socket)
{
for(i=0; i<1000000000; i++);
socket.on('error', function(error) { console.error("error", error); });
socket.write("<?xml version=\"1.0\"?>\n");
}
When you try the above disconnect, you'll just get a log message instead of a crash.
And when you're done, remember to remove the delay.
You can use this:
function isDigit(n) {
return Boolean([true, true, true, true, true, true, true, true, true, true][n]);
}
Here, I compared it to the accepted method: http://jsperf.com/isdigittest/5 . I didn't expect much, so I was pretty suprised, when I found out that accepted method was much slower.
Interesting thing is, that while accepted method is faster correct input (eg. '5') and slower for incorrect (eg. 'a'), my method is exact opposite (fast for incorrect and slower for correct).
Still, in worst case, my method is 2 times faster than accepted solution for correct input and over 5 times faster for incorrect input.
You can use the grep alternative sift here (disclaimer: I am the author).
It support multiline matching and limiting the search to specific file types out of the box:
sift -m --files '*.py' 'YOUR_PATTERN'
(search all *.py files for the specified multiline regex pattern)
It is available for all major operating systems. Take a look at the samples page to see how it can be used to to extract multiline values from an XML file.
I had created typings for lodash-es
also, so now you can actually do the following
npm install lodash-es -S
npm install @types/lodash-es -D
import kebabCase from "lodash-es/kebabCase";
const wings = kebabCase("chickenWings");
if you use rollup, i suggest using this instead of the lodash
as it will be treeshaken properly.
To do this you should alter the vertical-align property of the input.
<dd><label class="<?=$email_confirm_class;?>" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; border:none;" name="email_confirm" id="email_confirm" size="18" value="<?=$_POST['email_confirm'];?>" tabindex="4" /> *</dd>
Here is a more complete version. It has been tested in IE 8 and it works. see the difference by removing the vertical-align: middle from the input:
<html><head></head><body><dl><dt>test</dt><dd><label class="test" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; font-size: 22px" name="email_confirm" id="email_confirm" size="28" value="test" tabindex="4" /> *</dd></dl></body></html>
With Nedit you can do several operations with selected column:
CTRL+LEFT-MOUSE -> Mark Rectangular Text-Area
MIDDLE-MOUSE pressed in area -> moving text area with pushing aside other text
CTRL+MIDDLE-MOUSE pressed in marked area -> moving text area with overriding aside text and deleting text from original position
CTRL+SHIFT+MIDDLE-MOUSE pressed in marked area -> copying text area with overriding aside text and keeping text from original position
This solution is HTML and CSS based using z-index and hover, which works if JS is disabled or the video isn't yours (since you can add a thumbnail in YouTube).
<style>
.videoWrapper {
position: relative;
padding-bottom: 56.25%;
}
.videoWrapper .video-modal-poster img {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 10;
}
.videoWrapper .video-modal-poster:hover img {
z-index:0;
}
.videoWrapper iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
}
</style>
<div class="videoWrapper">
<a href="#" class="video-modal-poster">
<img alt="" src="" width="353" height="199" />
<iframe width="353" height="199" src="https://www.youtube.com/embed/" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
</a>
</div>
Bootstrap people use .hidden
class on <td>
.
The answer above didn't work for me.
I added the following code before my ajax request:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
type: 'POST',
url: '/url/',
});
First store that element in object, let's say element
and then write following code to click on that hidden element:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);
list is mutable
Change
last_list=last_list.append(p.last_name)
to
last_list.append(p.last_name)
will work
By default ls
sorts the names, which can take a while if there are a lot of them. Also there will be no output until all of the names are read and sorted. Use the ls -f
option to turn off sorting.
ls -f | wc -l
Note that this will also enable -a
, so .
, ..
, and other files starting with .
will be counted.
You could try this:
string input = "lala.bla";
output = input.Split('.').Last();
1) Normally, you would want to return a Task
. The main exception should be when you need to have a void
return type (for events). If there's no reason to disallow having the caller await
your task, why disallow it?
2) async
methods that return void
are special in another aspect: they represent top-level async operations, and have additional rules that come into play when your task returns an exception. The easiest way is to show the difference is with an example:
static async void f()
{
await h();
}
static async Task g()
{
await h();
}
static async Task h()
{
throw new NotImplementedException();
}
private void button1_Click(object sender, EventArgs e)
{
f();
}
private void button2_Click(object sender, EventArgs e)
{
g();
}
private void button3_Click(object sender, EventArgs e)
{
GC.Collect();
}
f
's exception is always "observed". An exception that leaves a top-level asynchronous method is simply treated like any other unhandled exception. g
's exception is never observed. When the garbage collector comes to clean up the task, it sees that the task resulted in an exception, and nobody handled the exception. When that happens, the TaskScheduler.UnobservedTaskException
handler runs. You should never let this happen. To use your example,
public static async void AsyncMethod2(int num)
{
await Task.Factory.StartNew(() => Thread.Sleep(num));
}
Yes, use async
and await
here, they make sure your method still works correctly if an exception is thrown.
for more information see: http://msdn.microsoft.com/en-us/magazine/jj991977.aspx
This works for me on [{"id":"data"},{"id":"data"}]
function getObjects(obj, key, val)
{
var newObj = false;
$.each(obj, function()
{
var testObject = this;
$.each(testObject, function(k,v)
{
//alert(k);
if(val == v && k == key)
{
newObj = testObject;
}
});
});
return newObj;
}
If you want to mutate props - use object.
<component :model="global.price"></component>
component:
props: ['model'],
methods: {
changeValue: function() {
this.model.value = "new value";
}
}