I've just had the same issue but using sourcetree on windows Same steps for normal GIT on Windows as well. Following the following steps I was able to solve this issue.
This should solve your issue with the self-signed certificates and using GIT.
I tried using the "http.sslcapath" configuration but this did not work. Also if i did not include the whole chain in the certificates file then this would also fail. If anyone has pointers on these please let me know as the above has to be repeated for a new install.
If this is the system GIT then you can use the options in TOOLS -> options GIt tab to use the system GIT and this then solves the issue in sourcetree as well.
I use the approach with PATH variable. Path to Notepad++ is added to system's PATH variable and then core.editor is set like following:
git config --global core.editor notepad++
Also, you may add some additional parameters for Notepad++:
git config --global core.editor "notepad++.exe -multiInst"
(as I detailed in "Git core.editor
for Windows")
And here you can find some options you may use when stating Notepad++ Command Line Options.
Line ending format used in OS
CR
(Carriage Return \r
) and LF
(LineFeed \n
) pairLF
(LineFeed \n
)We can configure git to auto-correct line ending formats for each OS in two ways.
.gitattributes
filegit config --global core.autocrlf input
This will fix any CRLF
to LF
when you commit.
git config --global core.autocrlf true
This will make sure when you checkout in windows, all LF
will convert to CRLF
It is a good idea to keep a .gitattributes
file as we don't want to expect everyone in our team set their config. This file should keep in repo's root path and if exist one, git will respect it.
* text=auto
This will treat all files as text files and convert to OS's line ending on checkout and back to LF
on commit automatically. If wanted to tell explicitly, then use
* text eol=crlf
* text eol=lf
First one is for checkout and second one is for commit.
*.jpg binary
Treat all .jpg
images as binary files, regardless of path. So no conversion needed.
Or you can add path qualifiers:
my_path/**/*.jpg binary
To follow-up on Charles Bailey's answer, here's my git setup that's using p4merge (free cross-platform 3way merge tool); tested on msys Git (Windows) install:
git config --global merge.tool p4merge
git config --global mergetool.p4merge.cmd 'p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\"'
or, from a windows cmd.exe shell, the second line becomes :
git config --global mergetool.p4merge.cmd "p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""
The changes (relative to Charles Bailey):
Download: http://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools
EDIT (Feb 2014)
As pointed out by @Gregory Pakosz, latest msys git now "natively" supports p4merge (tested on 1.8.5.2.msysgit.0).
You can display list of supported tools by running:
git mergetool --tool-help
You should see p4merge in either available or valid list. If not, please update your git.
If p4merge was listed as available, it is in your PATH and you only have to set merge.tool:
git config --global merge.tool p4merge
If it was listed as valid, you have to define mergetool.p4merge.path in addition to merge.tool:
git config --global mergetool.p4merge.path c:/Users/my-login/AppData/Local/Perforce/p4merge.exe
~
should expand to current user's home directory (so in theory the path should be ~/AppData/Local/Perforce/p4merge.exe
), this did not work for me$LOCALAPPDATA/Perforce/p4merge.exe
), git does not seem to be expanding environment variables for paths (if you know how to get this working, please let me know or update this answer)From a blog I found:
"This [git-credential-cache] doesn’t work for Windows systems as git-credential-cache communicates through a Unix socket."
Since msysgit has been superseded by Git for Windows, using Git for Windows is now the easiest option. Some versions of the Git for Windows installer (e.g. 2.7.4) have a checkbox during the install to enable the Git Credential Manager. Here is a screenshot:
The wincred
helper was added in msysgit 1.8.1. Use it as follows:
git config --global credential.helper wincred
First, download git-credential-winstore and install it in your git bin directory.
Next, make sure that the directory containing git.cmd is in your Path environment variable. The default directory for this is C:\Program Files (x86)\Git\cmd on a 64-bit system or C:\Program Files\Git\cmd on a 32-bit system. An easy way to test this is to launch a command prompt and type git
. If you don't get a list of git commands, then it's not set up correctly.
Finally, launch a command prompt and type:
git config --global credential.helper winstore
Or you can edit your .gitconfig file manually:
[credential]
helper = winstore
Once you've done this, you can manage your git credentials through Windows Credential Manager which you can pull up via the Windows Control Panel.
I had the same issue on Windows 10 where I tried to SSH into a Vagrant box. This seems like a bug in the old OpenSSH version. What worked for me:
(Note the ".exe" if you are using Powershell)
You might see something like:
C:\Windows\System32\OpenSSH\ssh.exe
C:\Program Files\OpenSSH\bin\ssh.exe
C:\opscode\chefdk\embedded\git\usr\bin\ssh.exe
Note that in the above example the latest OpenSSH is second in the path so it won't execute.
To change the order:
I faced exactly the same issue. My home drive mapped to a network drive. Also
However below worked from command line and I was able to add HOME
to environment variables.
rundll32 sysdm.cpl,EditEnvironmentVariables
In my case eighter git rebase --abort
and git rebase --continue
was throwing:
error: could not read '.git/rebase-apply/head-name': No such file or directory
I managed to fix this issue by manually removing: .git\rebase-apply
directory.
I had some issues creating a file in Windows Explorer with a .
at the beginning.
A workaround was to go into the commandshell and create a new file using "edit".
None of the above solutions worked for me on Windows 8
But the following command works fine
SHIFT + Q
In an extension to Chris Dolan's answer, I used the following alternative PS1
setting. Simply add the code fragment to your ~/.profile (on Windows 7: C:/Users/USERNAME/.profile).
fast_git_ps1 ()
{
printf -- "$(git branch 2>/dev/null | sed -ne '/^\* / s/^\* \(.*\)/ [\1] / p')"
}
PS1='\[\033]0;$MSYSTEM:\w\007
\033[32m\]\u@\h \[\033[33m\w$(fast_git_ps1)\033[0m\]
$ '
This retains the benefit of a colored shell and display of the current branch name (if in a Git repository), but it is significantly faster on my machine, from ~0.75 s to 0.1 s.
This is based on this blog post.
I'm using GitWebAccess for many projects for half a year now, and it's proven to be the best of what I've tried. It seems, though, that lately sources are not supported, so - don't take latest binaries/sources. Currently they're broken :(
You can build from this version or download compiled binaries which I use from here.
I tried pretty much all the suggestions made here but none worked. For us the issue was temperamental and became worse and worse the larger the repos became (on our Jenkins Windows build slave).
It ended up being the version of ssh being used by git. Git was configured to use some version of Open SSH, specified in the users .gitconfig file via the core.sshCommand variable. Removing that line fixed it. I believe this is because Windows now ships with a more reliable / compatible version of SSH which gets used by default.
Johannes Sixt from the [email protected] mailing list suggested using following command line arguments:
git apply --ignore-space-change --ignore-whitespace mychanges.patch
This solved my problem.
The proper way to get LF endings in Windows is to first set core.autocrlf
to false
:
git config --global core.autocrlf false
You need to do this if you are using msysgit, because it sets it to true
in its system settings.
Now git won’t do any line ending normalization. If you want files you check in to be normalized, do this: Set text=auto
in your .gitattributes
for all files:
* text=auto
And set core.eol
to lf
:
git config --global core.eol lf
Now you can also switch single repos to crlf (in the working directory!) by running
git config core.eol crlf
After you have done the configuration, you might want git to normalize all the files in the repo. To do this, go to to the root of your repo and run these commands:
git rm --cached -rf .
git diff --cached --name-only -z | xargs -n 50 -0 git add -f
If you now want git to also normalize the files in your working directory, run these commands:
git ls-files -z | xargs -0 rm
git checkout .
console2 ( http://sourceforge.net/projects/console/ ) is my go to terminal front end.
it add great features like copy/paste, resizable windows, and tabs. you can also integrate as many "terminals" as you want into the app. i personally use cmd (the basic windows prompt), mingW/msysGit, and i have shortcuts for diving directly into the python and mysql interpreters.
the "shell" argument i use for git (on a win7 machine) is:
C:\Windows\SysWOW64\cmd.exe /c ""C:\Program Files (x86)\Git\bin\sh.exe" --login -i"
The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:
$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pkg/main1.py", line 1, in <module>
import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>>
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>>
In particular:
$ python2 pkg/main2.py
Traceback (most recent call last):
File "pkg/main2.py", line 1, in <module>
from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>>
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Note that python2 pkg/main2.py
has a different behaviour then launching python2
and then importing pkg.main2
(which is equivalent to using the -m
switch).
If you ever want to run a submodule of a package always use the -m
switch which prevents the interpreter for chaining the sys.path
list and correctly handles the semantics of the submodule.
Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.
I got it!
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vId&key=dldfsd981asGhkxHxFf6JqyNrTqIeJ9sjMKFcX4");
$duration = json_decode($dur, true);
foreach ($duration['items'] as $vidTime) {
$vTime= $vidTime['contentDetails']['duration'];
}
There it returns the time for YouTube API version 3 (the key is made up by the way ;). I used $vId
that I had gotten off of the returned list of the videos from the channel I am showing the videos from...
It works. Google REALLY needs to include the duration in the snippet so you can get it all with one call instead of two... it's on their 'wontfix' list.
I was getting this error when I was updating the dictionary with the wrong syntax:
Try with these:
lineItem.values.update({attribute,value})
instead of
lineItem.values.update({attribute:value})
If you're wanting to do this via powershell on windows this worked for me
$env:JPDA_SUSPEND="y"
$env:JPDA_TRANSPORT="dt_socket"
/path/to/tomcat/bin/catalina.bat jpda start
Please use --user at end of this, it is working fine for me.
pip install enum34 --user
I have this issue today with mat-option-group. The thing which solved me the problem is using in other provided event of mat-select : valueChange
I put here a little code for understanding :
<mat-form-field >
<mat-label>Filter By</mat-label>
<mat-select panelClass="" #choosedValue (valueChange)="doSomething1(choosedValue.value)"> <!-- (valueChange)="doSomething1(choosedValue.value)" instead of (change) or other event-->
<mat-option >-- None --</mat-option>
<mat-optgroup *ngFor="let group of filterData" [label]="group.viewValue"
style = "background-color: #0c5460">
<mat-option *ngFor="let option of group.options" [value]="option.value">
{{option.viewValue}}
</mat-option>
</mat-optgroup>
</mat-select>
</mat-form-field>
Mat Version:
"@angular/material": "^6.4.7",
Modify your filter like this:
filter isNumeric {
[Helpers]::IsNumeric($_)
}
function
uses the $input
variable to contain pipeline information whereas the filter
uses the special variable $_
that contains the current pipeline object.
Edit:
For a powershell syntax way you can use just a filter (w/o add-type):
filter isNumeric() {
return $_ -is [byte] -or $_ -is [int16] -or $_ -is [int32] -or $_ -is [int64] `
-or $_ -is [sbyte] -or $_ -is [uint16] -or $_ -is [uint32] -or $_ -is [uint64] `
-or $_ -is [float] -or $_ -is [double] -or $_ -is [decimal]
}
It happens when Xcode doesn't recognize your certificate.
It's just a pain in the ass to solve it, there are a lot of possibilities to help you.
But the first thing you should try is removing in the "Window" tab => Organizer, the provisioning that is in your device. Then re-add them (download them again on the apple website). And try to compile again.
By the way, did you check in the Project Info Window the "code signing identity" ?
Good Luck.
If showing this error for ionic3 project when you upload to iTunes Connect, please check this ANSWER
This is my project error when I try to vilidated.
Finally follow this ANSWER, error solved.
no.
BufferedReader.close()
closes the stream according to javadoc for BufferedReader and InputStreamReader
as well as
FileReader.close()
does.
The most upvoted answers will fail if the file list is too long.
A more portable solution would be using fd
fd -e txt -d 1 -X awk 1 > combined.txt
-d 1
limits the search to the current directory. If you omit this option then it will recursively find all .txt
files from the current directory.
-X
(otherwise known as --exec-batch
) executes a command (awk 1
in this case) for all the search results at once.
I know it is old but according to my own theme editor with default light theme, default
textPrimaryColor = #000000
and
textColorPrimaryDark = #757575
I don't like the above approaches. Using cherry-pick is great for picking a single change, but it is a pain if you want to bring in all the changes except for some bad ones. Here is my approach.
There is no --interactive
argument you can pass to git merge.
Here is the alternative:
You have some changes in branch 'feature' and you want to bring some but not all of them over to 'master' in a not sloppy way (i.e. you don't want to cherry pick and commit each one)
git checkout feature
git checkout -b temp
git rebase -i master
# Above will drop you in an editor and pick the changes you want ala:
pick 7266df7 First change
pick 1b3f7df Another change
pick 5bbf56f Last change
# Rebase b44c147..5bbf56f onto b44c147
#
# Commands:
# pick = use commit
# edit = use commit, but stop for amending
# squash = use commit, but meld into previous commit
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#
git checkout master
git pull . temp
git branch -d temp
So just wrap that in a shell script, change master into $to and change feature into $from and you are good to go:
#!/bin/bash
# git-interactive-merge
from=$1
to=$2
git checkout $from
git checkout -b ${from}_tmp
git rebase -i $to
# Above will drop you in an editor and pick the changes you want
git checkout $to
git pull . ${from}_tmp
git branch -d ${from}_tmp
The solution was to call...
$scope.$apply();
...in my jQuery event callback.
Adding placeholder attributes from code-behind:
txtFilterTerm.Attributes.Add("placeholder", "Filter" + Filter.Name);
Or
txtFilterTerm.Attributes["placeholder"] = "Filter" + Filter.Name;
Adding placeholder attributes from aspx Page
<asp:TextBox type="text" runat="server" id="txtFilterTerm" placeholder="Filter" />
Or
<input type="text" id="txtFilterTerm" placeholder="Filter"/>
Since this is the first Google result for 'pandas new column from others', here's a simple example:
import pandas as pd
# make a simple dataframe
df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
df
# a b
# 0 1 3
# 1 2 4
# create an unattached column with an index
df.apply(lambda row: row.a + row.b, axis=1)
# 0 4
# 1 6
# do same but attach it to the dataframe
df['c'] = df.apply(lambda row: row.a + row.b, axis=1)
df
# a b c
# 0 1 3 4
# 1 2 4 6
If you get the SettingWithCopyWarning
you can do it this way also:
fn = lambda row: row.a + row.b # define a function for the new column
col = df.apply(fn, axis=1) # get column data with an index
df = df.assign(c=col.values) # assign values to column 'c'
Source: https://stackoverflow.com/a/12555510/243392
And if your column name includes spaces you can use syntax like this:
df = df.assign(**{'some column name': col.values})
You can easily get what you want by adding the line in ax:
ax.plot([], [], '-r', label = 'temp')
or
ax.plot(np.nan, '-r', label = 'temp')
This would plot nothing but add a label to legend of ax.
I think this is a much easier way. It's not necessary to track lines automatically when you have only a few lines in the second axes, as fixing by hand like above would be quite easy. Anyway, it depends on what you need.
The whole code is as below:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
time = np.arange(22.)
temp = 20*np.random.rand(22)
Swdown = 10*np.random.randn(22)+40
Rn = 40*np.random.rand(22)
fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()
#---------- look at below -----------
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2.plot(time, temp, '-r') # The true line in ax2
ax.plot(np.nan, '-r', label = 'temp') # Make an agent in ax
ax.legend(loc=0)
#---------------done-----------------
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
The plot is as below:
Update: add a better version:
ax.plot(np.nan, '-r', label = 'temp')
This will do nothing while plot(0, 0)
may change the axis range.
One extra example for scatter
ax.scatter([], [], s=100, label = 'temp') # Make an agent in ax
ax2.scatter(time, temp, s=10) # The true scatter in ax2
ax.legend(loc=1, framealpha=1)
PowerShell Fun
Get-WmiObject win32_logicaldisk -Computername <ServerName> -Credential $(get-credential) | Select DeviceID,VolumeName,FreeSpace,Size | where {$_.DeviceID -eq "C:"}
The problem must be with the parameters you are passing(You must be passing blank parameters). For example : http://www.myurl.com?id=5&name= Check if you are handling this at the server you are calling.
SELECT * FROM table
group by `Group`
ORDER BY COUNT(Group)
Your JSON string is malformed: the type of center
is an array of invalid objects. Replace [
and ]
with {
and }
in the JSON string around longitude
and latitude
so they will be objects:
[
{
"name" : "New York",
"number" : "732921",
"center" : {
"latitude" : 38.895111,
"longitude" : -77.036667
}
},
{
"name" : "San Francisco",
"number" : "298732",
"center" : {
"latitude" : 37.783333,
"longitude" : -122.416667
}
}
]
You need to define a class for the bullets you want to hide. For examples
.no-bullets {
list-style-type: none;
}
Then apply it to the list you want hidden bullets:
<ul class="no-bullets">
All other lists (without a specific class) will show the bulltets as usual.
Media Query classes can be used to achieve something passable with duplicate markup. Here's my approach with bootstrap:
<tr class="total">
<td colspan="1" class="visible-xs"></td>
<td colspan="5" class="hidden-xs"></td>
<td class="focus">Total</td>
<td class="focus" colspan="2"><%= number_to_currency @cart.total %></td>
</tr>
colspan 1 for mobile, colspan 5 for others with CSS doing the work.
This will output the number of lines that contain your search string.
grep -c "echo" FILE
This won't, however, count the number of occurrences in the file (ie, if you have echo multiple times on one line).
edit:
After playing around a bit, you could get the number of occurrences using this dirty little bit of code:
sed 's/echo/echo\n/g' FILE | grep -c "echo"
This basically adds a newline following every instance of echo so they're each on their own line, allowing grep to count those lines. You can refine the regex if you only want the word "echo", as opposed to "echoing", for example.
Use List<T>.Insert
While not relevant to your specific example, if performance is important also consider using LinkedList<T>
because inserting an item to the start of a List<T>
requires all items to be moved over. See When should I use a List vs a LinkedList.
The -s
switch disables per-test capturing (only if a test fails).
Stop using (HTTP 1.0) | Replaced with (HTTP 1.1 since 1999) |
---|---|
Expires: [date] | Cache-Control: max-age=[seconds] |
Pragma: no-cache | Cache-Control: no-cache |
If it's after 1999, and you're still using Expires or Pragma, you're doing it wrong.
I'm looking at you Stackoverflow:
200 OK Pragma: no-cache Content-Type: application/json X-Frame-Options: SAMEORIGIN X-Request-Guid: a3433194-4a03-4206-91ea-6a40f9bfd824 Strict-Transport-Security: max-age=15552000 Content-Length: 54 Accept-Ranges: bytes Date: Tue, 03 Apr 2018 19:03:12 GMT Via: 1.1 varnish Connection: keep-alive X-Served-By: cache-yyz8333-YYZ X-Cache: MISS X-Cache-Hits: 0 X-Timer: S1522782193.766958,VS0,VE30 Vary: Fastly-SSL X-DNS-Prefetch-Control: off Cache-Control: private
tl;dr: Pragma
is a legacy of HTTP/1.0 and hasn't been needed since Internet Explorer 5, or Netscape 4.7. Unless you expect some of your users to be using IE5: it's safe to stop using it.
[date]
(deprecated - HTTP 1.0)[seconds]
And the conditional requests:
Etag: W/“1d2e7–1648e509289”
If-None-Match: W/“1d2e7–1648e509289”
304 Not Modified
last-modified: Thu, 09 May 2019 19:15:47 GMT
If-Modified-Since: Fri, 13 Jul 2018 10:49:23 GMT
304 Not Modified
last-modified: Thu, 09 May 2019 19:15:47 GMT
that's my procedure
CREATE PROC sp_count
@CompanyId sysname,
@codition sysname
AS
SET NOCOUNT ON
CREATE TABLE #ctr
( NumRows int )
DECLARE @intCount int
, @vcSQL varchar(255)
SELECT @vcSQL = ' INSERT #ctr FROM dbo.Comm_Services
WHERE CompanyId = '+@CompanyId+' and '+@condition+')'
EXEC (@vcSQL)
IF @@ERROR = 0
BEGIN
SELECT @intCount = NumRows
FROM #ctr
DROP TABLE #ctr
RETURN @intCount
END
ELSE
BEGIN
DROP TABLE #ctr
RETURN -1
END
GO
I've seen this error in a similar situation to mentioned in Joe's answer:
description: Too high 5xx responses rate: {{ .Value }} > 0.05
We have a colon in description value. So, the problem is in missing quotes around description value. It can be resolved by adding quotes:
description: 'Too high 5xx responses rate: {{ .Value }} > 0.05'
Cascade will work when you delete something on table Courses
. Any record on table BookCourses
that has reference to table Courses
will be deleted automatically.
But when you try to delete on table BookCourses
only the table itself is affected and not on the Courses
follow-up question: why do you have CourseID
on table Category?
Maybe you should restructure your schema into this,
CREATE TABLE Categories
(
Code CHAR(4) NOT NULL PRIMARY KEY,
CategoryName VARCHAR(63) NOT NULL UNIQUE
);
CREATE TABLE Courses
(
CourseID INT NOT NULL PRIMARY KEY,
BookID INT NOT NULL,
CatCode CHAR(4) NOT NULL,
CourseNum CHAR(3) NOT NULL,
CourseSec CHAR(1) NOT NULL,
);
ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;
define
I use for global constants.
const
I use for class constants.
You cannot define
into class scope, and with const
you can. Needless to say, you cannot use const
outside class scope.
Also, with const
, it actually becomes a member of the class, and with define
, it will be pushed to global scope.
I find the answer. 1/First put in the presets, i have this example "Output format MPEG2 DVD HQ"
-vcodec mpeg2video -vstats_file MFRfile.txt -r 29.97 -s 352x480 -aspect 4:3 -b 4000k -mbd rd -trellis -mv0 -cmp 2 -subcmp 2 -acodec mp2 -ab 192k -ar 48000 -ac 2
If you want a report includes the commands -vstats_file MFRfile.txt into the presets like the example. this can make a report which it's ubicadet in the folder source of your file Source. you can put any name if you want , i solved my problem "i write many times in this forum" reading a complete .docx about mpeg properties. finally i can do my progress bar reading this txt file generated.
Regards.
I would do it this way, so you won't end up with duplicate entries if the script is run multiple times.
@echo off
SET NEWLINE=^& echo.
FIND /C /I "ns1.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^62.116.159.4 ns1.intranet.de>>%WINDIR%\System32\drivers\etc\hosts
FIND /C /I "ns2.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^217.160.113.37 ns2.intranet.de>>%WINDIR%\System32\drivers\etc\hosts
FIND /C /I "ns3.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^89.146.248.4 ns3.intranet.de>>%WINDIR%\System32\drivers\etc\hosts
FIND /C /I "ns4.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^74.208.254.4 ns4.intranet.de>>%WINDIR%\System32\drivers\etc\hosts
You can change action bar color on this way:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/green_action_bar</item>
</style>
Thats all you need for changing action bar color.
Plus if you want to change the status bar color just add the line:
<item name="android:colorPrimaryDark">@color/green_dark_action_bar</item>
Here is a screenshot taken from developer android site to make it more clear, and here is a link to read more about customizing the color palete
Add PrivacyBadger to the list of potential causes
From the answers above, the only one that handles the edge cases (bmpasini's from datejs library) has an issue:
var date = new Date("03/31/2015");
var newDate = date.addMonths(1);
console.log(newDate);
// VM223:4 Thu Apr 30 2015 00:00:00 GMT+0200 (CEST)
ok, but:
newDate.toISOString()
//"2015-04-29T22:00:00.000Z"
worse :
var date = new Date("01/01/2015");
var newDate = date.addMonths(3);
console.log(newDate);
//VM208:4 Wed Apr 01 2015 00:00:00 GMT+0200 (CEST)
newDate.toISOString()
//"2015-03-31T22:00:00.000Z"
This is due to the time not being set, thus reverting to 00:00:00, which then can glitch to previous day due to timezone or time-saving changes or whatever...
Here's my proposed solution, which does not have that problem, and is also, I think, more elegant in that it does not rely on hard-coded values.
/**
* @param isoDate {string} in ISO 8601 format e.g. 2015-12-31
* @param numberMonths {number} e.g. 1, 2, 3...
* @returns {string} in ISO 8601 format e.g. 2015-12-31
*/
function addMonths (isoDate, numberMonths) {
var dateObject = new Date(isoDate),
day = dateObject.getDate(); // returns day of the month number
// avoid date calculation errors
dateObject.setHours(20);
// add months and set date to last day of the correct month
dateObject.setMonth(dateObject.getMonth() + numberMonths + 1, 0);
// set day number to min of either the original one or last day of month
dateObject.setDate(Math.min(day, dateObject.getDate()));
return dateObject.toISOString().split('T')[0];
};
Unit tested successfully with:
function assertEqual(a,b) {
return a === b;
}
console.log(
assertEqual(addMonths('2015-01-01', 1), '2015-02-01'),
assertEqual(addMonths('2015-01-01', 2), '2015-03-01'),
assertEqual(addMonths('2015-01-01', 3), '2015-04-01'),
assertEqual(addMonths('2015-01-01', 4), '2015-05-01'),
assertEqual(addMonths('2015-01-15', 1), '2015-02-15'),
assertEqual(addMonths('2015-01-31', 1), '2015-02-28'),
assertEqual(addMonths('2016-01-31', 1), '2016-02-29'),
assertEqual(addMonths('2015-01-01', 11), '2015-12-01'),
assertEqual(addMonths('2015-01-01', 12), '2016-01-01'),
assertEqual(addMonths('2015-01-01', 24), '2017-01-01'),
assertEqual(addMonths('2015-02-28', 12), '2016-02-28'),
assertEqual(addMonths('2015-03-01', 12), '2016-03-01'),
assertEqual(addMonths('2016-02-29', 12), '2017-02-28')
);
This worked for me. Thank you Rody!
y="HELLO"
val=$(echo $y | tr '[:upper:]' '[:lower:]')
string="$val world"
one small modification, if you are using underscore next to the variable You need to encapsulate the variable name in {}.
string="${val}_world"
It was helpful for me: link
function hoverTouchUnstick() {
// Check if the device supports touch events
if('ontouchstart' in document.documentElement) {
// Loop through each stylesheet
for(var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
// Verify if cssRules exists in sheet
if(sheet.cssRules) {
// Loop through each rule in sheet
for(var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
// Verify rule has selector text
if(rule.selectorText) {
// Replace hover psuedo-class with active psuedo-class
rule.selectorText = rule.selectorText.replace(":hover", ":active");
}
}
}
}
}
}
It sounds like the intermediate certificate is missing. As of April 2006, all SSL certificates issued by VeriSign require the installation of an Intermediate CA Certificate.
It could be that you don't have the entire certificate chain loaded on your server. Some businesses do not allow their computers to download additional certificates, causing a failure to complete an SSL handshake.
Here is some information on intermediate chains:
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR657
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AD146
Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.
Associative Array
var a = new Array(1,2,3);
a['key'] = 'experiment';
Array.isArray(a);
returns true
Keep in mind that a.length
will be undefined, because length
is treated as a key, you should use Object.keys(a).length
to get the length of an Associative Array.
Object
var a = {1:1, 2:2, 3:3,'key':'experiment'};
Array.isArray(a)
returns false
JSON returns an Object ... could return an Associative Array ... but it is not like that
Found a really helpful link for that. Using SQLCMD for this is really easier than solving this with a stored procedure
http://www.excel-sql-server.com/sql-server-export-to-excel-using-bcp-sqlcmd-csv.htm
HTML Code:-
enter code here
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
upload.php
enter code here
<?php
$image = $_FILES;
$NewImageName = rand(4,10000)."-". $image['image']['name'];
$destination = realpath('../images/testing').'/';
move_uploaded_file($image['image']['tmp_name'], $destination.$NewImageName);
$image = imagecreatefromjpeg($destination.$NewImageName);
$filename = $destination.$NewImageName;
$thumb_width = 200;
$thumb_height = 150;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
imagejpeg($thumb, $filename, 80);
echo "cropped"; die;
?>
Check the documentation for the best result:
@forelse($status->replies as $reply)
<p>{{ $reply->body }}</p>
@empty
<p>No replies</p>
@endforelse
If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents
export JAVA_OPTS="-server -Xmx512m"
For Windows you will need, in setenv.bat, something like
set JAVA_OPTS=-server -Xmx768m
Original answer here
After you run startup.bat
, you can easily confirm the correct settings have been applied provided you have turned @echo
on somewhere in your catatlina.bat
file (a good place could be immediately after echo Using CLASSPATH: "%CLASSPATH%"
):
Sounds like you are using Microsoft Visual C++. If that is the case, then the most possibility is that you don't compile your two.cpp with one.cpp (one.cpp is the implementation for one.h).
If you are from command line (cmd.exe), then try this first: cl -o two.exe one.cpp two.cpp
If you are from IDE, right click on the project name from Solution Explore. Then choose Add, Existing Item.... Add one.cpp into your project.
grep -v
is your friend:
grep --help | grep invert
-v, --invert-match select non-matching lines
Also check out the related -L
(the complement of -l
).
-L, --files-without-match only print FILE names containing no match
This works great if a straight copy is in order. If the situation calls for creating new objects from templates, I usually wrap the template div in a hidden storage div and use jquery's html() in conjunction with clone() applying the following technique:
<style>
#element-storage {
display: none;
top: 0;
right: 0;
position: fixed;
width: 0;
height: 0;
}
</style>
<script>
$("#new-div").append($("#template").clone().html(function(index, oldHTML){
// .. code to modify template, e.g. below:
var newHTML = "";
newHTML = oldHTML.replace("[firstname]", "Tom");
newHTML = newHTML.replace("[lastname]", "Smith");
// newHTML = newHTML.replace(/[Example Replace String]/g, "Replacement"); // regex for global replace
return newHTML;
}));
</script>
<div id="element-storage">
<div id="template">
<p>Hello [firstname] [lastname]</p>
</div>
</div>
<div id="new-div">
</div>
Note that this will not work:
header('Location: $url');
You need to do this (for variable expansion):
header("Location: $url");
So, finally I realized what the problem is. It is not a Jackson configuration issue as I doubted.
Actually the problem was in ApplesDO Class:
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String apple) {
this.apple = apple;
}
public ApplesDO(CustomType custom) {
//constructor Code
}
}
There was a custom constructor defined for the class making it the default constructor. Introducing a dummy constructor has made the error to go away:
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String apple) {
this.apple = apple;
}
public ApplesDO(CustomType custom) {
//constructor Code
}
//Introducing the dummy constructor
public ApplesDO() {
}
}
There are several ways of doing this. This is an answer that I write hoping that all the basics of Internet Explorer automation will be found when browsing for the keywords "scraping data from website", but remember that nothing's worth as your own research (if you don't want to stick to pre-written codes that you're not able to customize).
Please note that this is one way, that I don't prefer in terms of performance (since it depends on the browser speed) but that is good to understand the rationale behind Internet automation.
1) If I need to browse the web, I need a browser! So I create an Internet Explorer browser:
Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")
2) I ask the browser to browse the target webpage. Through the use of the property ".Visible", I decide if I want to see the browser doing its job or not. When building the code is nice to have Visible = True
, but when the code is working for scraping data is nice not to see it everytime so Visible = False
.
With appIE
.Navigate "http://uk.investing.com/rates-bonds/financial-futures"
.Visible = True
End With
3) The webpage will need some time to load. So, I will wait meanwhile it's busy...
Do While appIE.Busy
DoEvents
Loop
4) Well, now the page is loaded. Let's say that I want to scrape the change of the US30Y T-Bond: What I will do is just clicking F12 on Internet Explorer to see the webpage's code, and hence using the pointer (in red circle) I will click on the element that I want to scrape to see how can I reach my purpose.
5) What I should do is straight-forward. First of all, I will get by the ID property the tr
element which is containing the value:
Set allRowOfData = appIE.document.getElementById("pair_8907")
Here I will get a collection of td
elements (specifically, tr
is a row of data, and the td
are its cells. We are looking for the 8th, so I will write:
Dim myValue As String: myValue = allRowOfData.Cells(7).innerHTML
Why did I write 7 instead of 8? Because the collections of cells starts from 0, so the index of the 8th element is 7 (8-1). Shortly analysing this line of code:
.Cells()
makes me access the td
elements;innerHTML
is the property of the cell containing the value we look for. Once we have our value, which is now stored into the myValue
variable, we can just close the IE browser and releasing the memory by setting it to Nothing:
appIE.Quit
Set appIE = Nothing
Well, now you have your value and you can do whatever you want with it: put it into a cell (Range("A1").Value = myValue
), or into a label of a form (Me.label1.Text = myValue
).
I'd just like to point you out that this is not how StackOverflow works: here you post questions about specific coding problems, but you should make your own search first. The reason why I'm answering a question which is not showing too much research effort is just that I see it asked several times and, back to the time when I learned how to do this, I remember that I would have liked having some better support to get started with. So I hope that this answer, which is just a "study input" and not at all the best/most complete solution, can be a support for next user having your same problem. Because I have learned how to program thanks to this community, and I like to think that you and other beginners might use my input to discover the beautiful world of programming.
Enjoy your practice ;)
Select the commit you would like to roll back to and reverse the changes by clicking Reverse File
, Reverse Hunk
or Reverse Selected Lines
. Do this for all the commits after the commit you would like to roll back to also.
Right click on the commit and click on Reset current branch to this commit
.
I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
You can use CCur
to convert numbers or string to Curency formats. CCur(number)
or CCur(string)
I think this may be what you are looking for,
Replace (ToText(CCur({field})),"$" , "")
that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting
There are 3 ways to allow cross domain origin (excluding jsonp
):
1) Set the header in the page directly using a templating language like PHP. Keep in mind there can be no HTML before your header or it will fail.
<?php header("Access-Control-Allow-Origin: http://example.com"); ?>
2) Modify the server configuration file (apache.conf
) and add this line. Note that "*"
represents allow all. Some systems might also need the credential set. In general allow all access is a security risk and should be avoided:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Credentials true
3) To allow multiple domains on Apache web servers add the following to your config file
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(example.org|example.com)$" AccessControlAllowOrigin=$0$1
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header set Access-Control-Allow-Credentials true
</IfModule>
4) For development use only hack your browser and allow unlimited CORS using the Chrome Allow-Control-Allow-Origin extension
5) Disable CORS in Chrome: Quit Chrome completely. Open a terminal and execute the following. Just be cautious you are disabling web security:
open -a Google\ Chrome --args --disable-web-security --user-data-dir
All scripts should be loaded last
In just about every case, it's best to place all your script references at the end of the page, just before </body>
.
If you are unable to do so due to templating issues and whatnot, decorate your script tags with the defer
attribute so that the browser knows to download your scripts after the HTML has been downloaded:
<script src="my.js" type="text/javascript" defer="defer"></script>
Edge cases
There are some edge cases, however, where you may experience page flickering or other artifacts during page load which can usually be solved by simply placing your jQuery script references in the <head>
tag without the defer
attribute. These cases include jQuery UI and other addons such as jCarousel or Treeview which modify the DOM as part of their functionality.
Further caveats
There are some libraries that must be loaded before the DOM or CSS, such as polyfills. Modernizr is one such library that must be placed in the head tag.
Following up on Niketya's answer, there's a good explanation of Pivot Tables here: http://peltiertech.com/WordPress/grouping-by-date-in-a-pivot-table/
For Excel 2007 you'd create the Pivot Table, make your Date column a Row Label, your Amount column a value. You'd then right click on one of the row labels (ie a date), right click and select Group. You'd then get the option to group by day, month, etc.
Personally that's the way I'd go.
If you prefer formulae, Smandoli's answer would get you most of the way there. To be able to use Sumif by day, you'd add a column with a formula like:
=DATE(YEAR(C1), MONTH(C1), DAY(C1))
where column C contains your datetimes.
You can then use this in your sumif.
You can use the pexpect module
child = pexpect.spawn ('/usr/bin/sftp ' + [email protected] )
child.expect ('.* password:')
child.sendline (your_password)
child.expect ('sftp> ')
child.sendline ('dir')
child.expect ('sftp> ')
file_list = child.before
child.sendline ('bye')
I haven't tested this but it should work
In Python 3, dict.values()
(along with dict.keys()
and dict.items()
) returns a view
, rather than a list. See the documentation here. You therefore need to wrap your call to dict.values()
in a call to list
like so:
v = list(d.values())
{names[i]:v[i] for i in range(len(names))}
In case of Include Program will not terminate and display warning on browser,On the other hand Require program will terminate and display fatal error in case of file not found.
I had a similar problem in reading a graph from a file. The processing included the computation of a 200 000x200 000 float matrix (one line at a time) that did not fit into memory. Trying to free the memory between computations using gc.collect()
fixed the memory-related aspect of the problem but it resulted in performance issues: I don't know why but even though the amount of used memory remained constant, each new call to gc.collect()
took some more time than the previous one. So quite quickly the garbage collecting took most of the computation time.
To fix both the memory and performance issues I switched to the use of a multithreading trick I read once somewhere (I'm sorry, I cannot find the related post anymore). Before I was reading each line of the file in a big for
loop, processing it, and running gc.collect()
every once and a while to free memory space. Now I call a function that reads and processes a chunk of the file in a new thread. Once the thread ends, the memory is automatically freed without the strange performance issue.
Practically it works like this:
from dask import delayed # this module wraps the multithreading
def f(storage, index, chunk_size): # the processing function
# read the chunk of size chunk_size starting at index in the file
# process it using data in storage if needed
# append data needed for further computations to storage
return storage
partial_result = delayed([]) # put into the delayed() the constructor for your data structure
# I personally use "delayed(nx.Graph())" since I am creating a networkx Graph
chunk_size = 100 # ideally you want this as big as possible while still enabling the computations to fit in memory
for index in range(0, len(file), chunk_size):
# we indicates to dask that we will want to apply f to the parameters partial_result, index, chunk_size
partial_result = delayed(f)(partial_result, index, chunk_size)
# no computations are done yet !
# dask will spawn a thread to run f(partial_result, index, chunk_size) once we call partial_result.compute()
# passing the previous "partial_result" variable in the parameters assures a chunk will only be processed after the previous one is done
# it also allows you to use the results of the processing of the previous chunks in the file if needed
# this launches all the computations
result = partial_result.compute()
# one thread is spawned for each "delayed" one at a time to compute its result
# dask then closes the tread, which solves the memory freeing issue
# the strange performance issue with gc.collect() is also avoided
Just use DROP TABLE IF EXISTS
:
DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );
Try searching the MySQL documentation first if you have any other problems.
It's actually Document Object Model. HTML is used to build the DOM which is an in-memory representation of the page (while closely related to HTML, they are not exactly the same thing). Things like CSS and Javascript interact with the DOM.
Try this: .aspx page
<td>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"
CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">
</asp:AutoCompleteExtender>
Now To auto populate from database :
public static List<string> GetCompletionList(string prefixText, int count)
{
return AutoFillProducts(prefixText);
}
private static List<string> AutoFillProducts(string prefixText)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "select ProductName from ProdcutMaster where " + "ProductName like @Search + '%'";
com.Parameters.AddWithValue("@Search", prefixText);
com.Connection = con;
con.Open();
List<string> countryNames = new List<string>();
using (SqlDataReader sdr = com.ExecuteReader())
{
while (sdr.Read())
{
countryNames.Add(sdr["ProductName"].ToString());
}
}
con.Close();
return countryNames;
}
}
}
Now:create a stored Procedure that fetches the Product details depending on the selected product from the Auto Complete Text Box.
Create Procedure GetProductDet
(
@ProductName varchar(50)
)
as
begin
Select BrandName,warranty,Price from ProdcutMaster where ProductName=@ProductName
End
Create a function name to get product details ::
private void GetProductMasterDet(string ProductName)
{
connection();
com = new SqlCommand("GetProductDet", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@ProductName", ProductName);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds=new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
//Binding TextBox From dataTable
txtbrandName.Text =dt.Rows[0]["BrandName"].ToString();
txtwarranty.Text = dt.Rows[0]["warranty"].ToString();
txtPrice.Text = dt.Rows[0]["Price"].ToString();
}
Auto post back should be true
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
Now, Just call this function
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
//calling method and Passing Values
GetProductMasterDet(TextBox1.Text);
}
To answer my own question:
The example policy granted PutObject access, but I also had to grant PutObjectAcl access.
I had to change
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject"
from the example to:
"s3:PutObject",
"s3:PutObjectAcl",
"s3:GetObject",
"s3:GetObjectAcl",
"s3:DeleteObject"
You also need to make sure your bucket is configured for clients to set a public-accessible ACL by unticking these two boxes:
I could do this (demo):
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
<form >
<input type="file" id="f" data-max-size="32154" />
<input type="submit" />
</form>
<script>
$(function(){
$('form').submit(function(){
var isOk = true;
$('input[type=file][data-max-size]').each(function(){
if(typeof this.files[0] !== 'undefined'){
var maxSize = parseInt($(this).attr('max-size'),10),
size = this.files[0].size;
isOk = maxSize > size;
return isOk;
}
});
return isOk;
});
});
</script>
</body>
</html>
If you specify ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to the column.
Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.
Above description is taken from MYSQL official website.
A 2d array is simply an array of arrays. The analog for lists is simply a List
of List
s.
ArrayList<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();
I'll admit, it's not a pretty solution, especially if you go for a 3 or more dimensional structure.
This is what may be happening, if the value of item.photo
is undefined then item.photo != ''
will always show as true. And if you think logically it actually makes sense, item.photo
is not an empty string (so this condition comes true) since it is undefined
.
Now for people who are trying to check if the value of input is empty or not in Angular 6, can go by this approach.
Lets say this is the input field -
<input type="number" id="myTextBox" name="myTextBox"_x000D_
[(ngModel)]="response.myTextBox"_x000D_
#myTextBox="ngModel">
_x000D_
To check if the field is empty or not this should be the script.
<div *ngIf="!myTextBox.value" style="color:red;">_x000D_
Your field is empty_x000D_
</div>
_x000D_
Do note the subtle difference between the above answer and this answer. I have added an additional attribute .value
after my input name myTextBox
.
I don't know if the above answer worked for above version of Angular, but for Angular 6 this is how it should be done.
nodeJS default
https://nodejs.org/api/timers.html
setInterval(function() {
// your function
}, 5000);
The below steps for using Android OpenCV sdk in Android Studio. This is a simplified version of this(1) SO answer.
Step (6) is since Android studio expects native libs in app/src/main/jniLibs
instead of older libs
folder. For those new to Android OpenCV, don't miss below steps
static{ System.loadLibrary("opencv_java"); }
(Note: for OpenCV version 3 at this step you should instead load the library opencv_java3
.)OpenCV written is in C/C++. Java wrappers are
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
You got the order of the arguments to mysqli_select_db()
backwards. And mysqli_error()
requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.
Note also that with mysqli you can specify the DB in mysqli_connect()
:
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
die("Database connection failed: " . mysqli_connect_error();
}
You must use mysqli_connect_error()
, not mysqli_error()
, to get the error from mysqli_connect()
, since the latter requires you to supply a valid connection.
All these answers are partially wrong.
Microsoft has clarified that Community is for ANY USE as long as your revenue is under $1 Million US dollars. That is literally the only difference between Pro and Community. Corporate or free or not, irrelevant.
Even the lack of TFS support is not true. I can verify it is present and works perfectly.
EDIT: Here is an MSDN post regarding the $1M limit: MSDN (hint: it's in the VS 2017 license)
EDIT: Even over the revenue limit, open source is still free.
Lucida Sans Typewriter
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Here $users
is a PDOStatement
object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach
is essentially shorthand for:
while ($row = $users->fetch()) ...
Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
Here all results are being output by the first loop. The call to fetch
will return false
, since you have already exhausted the result set (see above), so you get an error trying to loop over false
.
In the last example you are simply fetching the first result row and are looping over it.
The three operators have related but different meanings, despite the misleading note from the IDE.
The ::
operator is known as the scope resolution operator, and it is used to get from a namespace or class to one of its members.
The .
and ->
operators are for accessing an object instance's members, and only comes into play after creating an object instance. You use .
if you have an actual object (or a reference to the object, declared with &
in the declared type), and you use ->
if you have a pointer to an object (declared with *
in the declared type).
The this
object is always a pointer to the current instance, hence why the ->
operator is the only one that works.
Examples:
// In a header file
namespace Namespace {
class Class {
private:
int x;
public:
Class() : x(4) {}
void incrementX();
};
}
// In an implementation file
namespace Namespace {
void Class::incrementX() { // Using scope resolution to get to the class member when we aren't using an instance
++(this->x); // this is a pointer, so using ->. Equivalent to ++((*this).x)
}
}
// In a separate file lies your main method
int main() {
Namespace::Class myInstance; // instantiates an instance. Note the scope resolution
Namespace::Class *myPointer = new Namespace::Class;
myInstance.incrementX(); // Calling a function on an object instance.
myPointer->incrementX(); // Calling a function on an object pointer.
(*myPointer).incrementX(); // Calling a function on an object pointer by dereferencing first
return 0;
}
Just in case anyone has anymore troubles, this is a pretty sure fix.
check your etc/hosts file make sure you have a root user for every host.
i.e.
127.0.0.1 home.dev
localhost home.dev
Therefore I will have 2 or more users as root for mysql:
root@localhost
[email protected]
this is how I fixed my problem.
I also had a similar problem like yours. The problem is that you are using an old php version. I have upgraded to PHP 5.6 and the problem no longer exist.
The const with the int on either sides will make pointer to constant int:
const int *ptr=&i;
or:
int const *ptr=&i;
const
after *
will make constant pointer to int:
int *const ptr=&i;
In this case all of these are pointer to constant integer, but none of these are constant pointer:
const int *ptr1=&i, *ptr2=&j;
In this case all are pointer to constant integer and ptr2 is constant pointer to constant integer. But ptr1 is not constant pointer:
int const *ptr1=&i, *const ptr2=&j;
Create a Composite object
public class CollectiveObject<X, Y>
{
public X FirstObj;
public Y SecondObj;
}
initialize a composite object with any two objects which you willing to send.
CollectiveObject<myobject1, myobject2> collectiveobj =
new CollectiveObject<myobject1, myobject2>();
collectiveobj.FirstObj = myobj1;
collectiveobj.SecondObj = myobj2;
Do serialization
var req = JSONHelper.JsonSerializer`<CollectiveObject<myobject1, `myobject2>>(collectiveobj);`
`
your API must be like
[Route("Add")]
public List<APIAvailibilityDetails> Add([FromBody]CollectiveObject<myobject1, myobject2> collectiveobj)
{ //to do}
I resolved this issue. In my case my application pool was stopped. After little bit of Googling i found out that application pool was running under some user identity and password was changed for that user. After updating password it starts working fine.
TTFB is something that happens behind the scenes. Your browser knows nothing about what happens behind the scenes.
You need to look into what queries are being run and how the website connects to the server.
This article might help understand TTFB, but otherwise you need to dig deeper into your application.
I had the same problem. You should type your Angular js code outside of any function like this:
$( document ).ready(function() {});
Another, more humane way:
find /<directory> -newermt "-24 hours" -ls
or:
find /<directory> -newermt "1 day ago" -ls
or:
find /<directory> -newermt "yesterday" -ls
Just for people looking to do this in batch files, this code is working:
FOR /R "C:\Users\jonathan\Desktop\test" %%f IN (*.jpg) DO REN "%%f" *.png
In this example all files with .jpg extensions in the C:\Users\jonathan\Desktop\test directory are changed to *.png.
For some cases UIWebView is a good solution. Because:
Using NSAttributedString can lead to crashes, if html is complex or contains tables (so example)
For loading text to web view you can use the following snippet (just example):
func loadHTMLText(_ text: String?, font: UIFont) {
let fontSize = font.pointSize * UIScreen.screens[0].scale
let html = """
<html><body><span style=\"font-family: \(font.fontName); font-size: \(fontSize)\; color: #112233">\(text ?? "")</span></body></html>
"""
self.loadHTMLString(html, baseURL: nil)
}
I have used pdflib for this.
p = new pdflib();
/* Open the input PDF */
indoc = p.open_pdi_document("myTestFile.pdf", "");
pageCount = (int) p.pcos_get_number(indoc, "length:pages");
window.onload
and onunload
are shortcuts to document.body.onload
and document.body.onunload
document.onload
and onload
handler on all html tag seems to be reserved however never triggered
'onload
' in document -> true
object explorer > right-click a table > Script table as > SELECT to > Clipboard
Then you can just paste in the section where you want that as a sub query.
Create you own templates with only a code snippet. Then instead opening the template as a new document just drag it to you current query to insert the snippet.
A snippet can simply be a set of header with comments or just some simple piece of code.
If you wont remember to start a transaction before your delete statemens you can go to options and set implicit transactions by default in all your queries. They require always an explicit commit / rollback.
Go to options and set isolation level to READ_UNCOMMITED by default. This way you dont need to type a NOLOCK in all your ad hoc queries. Just dont forget to place the table hint when writing a new view or stored procedure.
Your login has a default database set by the DBA (To me is usually the undesired one almost every time).
If you want it to be a different one because of the project you are currently working on.
In 'Registered Servers pane' > Right click > Properties > Connection properties tab > connect to database.
(These you might already have done though)
Register the server multiple times, each with a different login. You can then have the same server in the object browser open multiple times (each with a different login).
To execute the same query you already wrote with a different login, instead of copying the query just do a right click over the query pane > Connection > Change connection.
Here's how i finally created the ~/.android/debug.keystore file.
First some background. I got a new travel laptop. Installed Android Studio. Cloned my android project from git hub. The project would not run. Finally figured out that the debug.keystore was not created ... and i could not figure out how to get Android Studio to create it.
Finally, i created a new blank project ... and that created the debug.keystore!
Hope this helps other who have this problem.
How's this:
$(t).first().next()
Apart from how beautiful the answer looks, you must also give a thought to the performance of the code. Therefore, it is also relavant to know what exactly is in the $(t)
variable. Is it an array of <TD>
or is it a <TR>
node with several <TD>s
inside it?
To further illustrate the point, see the jsPerf scores on a <ul>
list with 50 <li>
children:
The $(t).first().next()
method is the fastest here, by far.
But, on the other hand, if you take the <tr>
node and find the <td>
children and and run the same test, the results won't be the same.
Hope it helps. :)
html, body {
height:100%;
}
body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
First off target refers to the BlockID found in either HTML code or chromes developer tools that you are trying to link to. Each code is different and you will need to do some digging to find the ID you are trying to reference. It should look something like div class="page-container drawer-page-content" id"PageContainer"
Note that this is the format for the whole referenced section, not an individual text or image. To do that you would need to find the same piece of code but relating to your target block. For example dv id="your-block-id"
Anyways I was just reading over this thread and an idea came to my mind, if you are a Shopify user and want to do this it is pretty much the same thing as stated.
But instead of
> http://url.to.site/index.html#target
You would put
> http://storedomain.com/target
For example, I am setting up a disclaimer page with links leading to a newsletter signup and shopping blocks on my home page so I insert https://mystore-classifier.com/#shopify-section-1528945200235
for my hyperlink.
Please note that the -classifier is for my internal use and doesn't apply to you. This is just so I can keep track of my stores.
If you want to link to something other than your homepage you would put
> http://mystore-classifier.com/pagename/#BlockID
I hope someone found this useful, if there is something wrong with my explanation please let me know as I am not an HTML programmer my language is C#!
The easier way (same as @Matt M's answer but corrected and added fallback to default map)
// override TypeMapProvider to return custom map for every requested type
Dapper.SqlMapper.TypeMapProvider = type =>
{
// create fallback default type map
var fallback = new DefaultTypeMap(type);
return new CustomPropertyTypeMap(type, (t, column) =>
{
var property = t.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(typeof(ColumnAttribute))
.Cast<ColumnAttribute>()
.Any(attr => attr.Name == column));
// if no property matched - fall back to default type map
if (property == null)
{
property = fallback.GetMember(column)?.Property;
}
return property;
});
};
The simplest way in laravel 5 is:
$listings=Listing::take(10)->get();
return view('view.name',compact('listings'));
This is an extension to Pache's answer using Guava's ListenableFuture
.
In particular, Futures.transform()
returns ListenableFuture
so can be used to chain async calls. Futures.addCallback()
returns void
, so cannot be used for chaining, but is good for handling success/failure on an async completion.
// ListenableFuture1: Open Database
ListenableFuture<Database> database = service.submit(() -> openDatabase());
// ListenableFuture2: Query Database for Cursor rows
ListenableFuture<Cursor> cursor =
Futures.transform(database, database -> database.query(table, ...));
// ListenableFuture3: Convert Cursor rows to List<Foo>
ListenableFuture<List<Foo>> fooList =
Futures.transform(cursor, cursor -> cursorToFooList(cursor));
// Final Callback: Handle the success/errors when final future completes
Futures.addCallback(fooList, new FutureCallback<List<Foo>>() {
public void onSuccess(List<Foo> foos) {
doSomethingWith(foos);
}
public void onFailure(Throwable thrown) {
log.error(thrown);
}
});
NOTE: In addition to chaining async tasks, Futures.transform()
also allows you to schedule each task on a separate executor (Not shown in this example).
'b' should be in capital letter in document.getElementById
modified code jsfiddle
function test()
{
var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
//document.body.appendChild(element);
}
Figured this out with the help of a friend. The -m
PuTTY option will end your session immediately after it executes the shell file. What I've done instead is I've created a batch script called putty.bat
with these contents on my Windows machine:
@echo off
putty -load "host" -l username -pw password
This logs me in remotely to the Linux host. On the host side, I created a shell file called sql
with these contents:
#!/bin/tcsh
add oracle10g
sqlplus username password
My host's Linux build used tcsh
. Other Linux builds might use bash
, so simply replace tcsh with bash and you should be fine.
To summarize, automating these steps are now done in two easy steps:
putty.bat
. This opens PuTTY and logs me into the host.tcsh sql
. This adds the oracle tool to my host, and logs me into the sql database.The main difference what i have observed was that abstract class provides us with some common behaviour implemented already and subclasses only needs to implement specific functionality corresponding to them. where as for an interface will only specify what tasks needs to be done and no implementations will be given by interface. I can say it specifies the contract between itself and implemented classes.
I have checked a variable if it is a boolean or not as below
console.log(isBoolean(this.myVariable));
Similarly we have
isNumber(this.myVariable);
isString(this.myvariable);
and so on.
Using dlpyr::mutate
and forcats::fct_recode
:
library(dplyr)
library(forcats)
iris <- iris %>%
mutate(Species = fct_recode(Species,
"Virginica" = "virginica",
"Versicolor" = "versicolor"
))
iris %>%
count(Species)
# A tibble: 3 x 2
Species n
<fctr> <int>
1 setosa 50
2 Versicolor 50
3 Virginica 50
Console.WriteLine(Path.GetDirectoryName(@"C:\hello\my\dear\world.hm"));
What is JNDI ?
It stands for Java Naming and Directory Interface.
What is its basic use?
JNDI allows distributed applications to look up services in an abstract, resource-independent way.
When it is used?
The most common use case is to set up a database connection pool on a Java EE application server. Any application that's deployed on that server can gain access to the connections they need using the JNDI name java:comp/env/FooBarPool
without having to know the details about the connection.
This has several advantages:
devl->int->test->prod
environments, you can use the same JNDI name in each environment and hide the actual database being used. Applications don't have to change as they migrate between environments.A very old but simple enough technique is to use "Server-Side Includes", to include HTML pages into a top-level page that has the .shtml
extension. For instance this would be your index.shtml
file:
<html>
<head>...</head>
<body>
<!-- repeated header: note that the #include is in a HTML comment -->
<!--#include file="header.html" -->
<!-- unique content here... -->
</body>
</html>
Yes, it is lame, but it works. Remember to enable SSI support in your HTTP server configuration (this is how to do it for Apache).
You can simply specify a series of images like this:
\includegraphics<1>{A}
\includegraphics<2>{B}
\includegraphics<3>{C}
This will produce three slides with the images A to C in exactly the same position.
The simple answer is: **no difference, they are the same thing.
2020-08-20 Update: While GUIDs (as used by Microsoft) and UUIDs (as defined by RFC4122) look similar and serve similar purposes, there are subtle-but-occasionally-important differences. Specifically, some Microsoft GUID docs allow GUIDs to contain any hex digit in any position, while RFC4122 requires certain values for the version
and variant
fields. Also, [per that same link], GUIDs should be all-upper case, whereas UUIDs should be "output as lower case characters and are case insensitive on input". This can lead to incompatibilities between code libraries (such as this).
(Original answer follows)
Treat them as a 16 byte (128 bits) value that is used as a unique value. In Microsoft-speak they are called GUIDs, but call them UUIDs when not using Microsoft-speak.
Even the authors of the UUID specification and Microsoft claim they are synonyms:
From the introduction to IETF RFC 4122 "A Universally Unique IDentifier (UUID) URN Namespace": "a Uniform Resource Name namespace for UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier)."
From the ITU-T Recommendation X.667, ISO/IEC 9834-8:2004 International Standard: "UUIDs are also known as Globally Unique Identifiers (GUIDs), but this term is not used in this Recommendation."
And Microsoft even claims a GUID is specified by the UUID RFC: "In Microsoft Windows programming and in Windows operating systems, a globally unique identifier (GUID), as specified in [RFC4122], is ... The term universally unique identifier (UUID) is sometimes used in Windows protocol specifications as a synonym for GUID."
But the correct answer depends on what the question means when it says "UUID"...
The first part depends on what the asker is thinking when they are saying "UUID".
Microsoft's claim implies that all UUIDs are GUIDs. But are all GUIDs real UUIDs? That is, is the set of all UUIDs just a proper subset of the set of all GUIDs, or is it the exact same set?
Looking at the details of the RFC 4122, there are four different "variants" of UUIDs. This is mostly because such 16 byte identifiers were in use before those specifications were brought together in the creation of a UUID specification. From section 4.1.1 of RFC 4122, the four variants of UUID are:
According to RFC 4122, all UUID variants are "real UUIDs", then all GUIDs are real UUIDs. To the literal question "is there any difference between GUID and UUID" the answer is definitely no for RFC 4122 UUIDs: no difference (but subject to the second part below).
But not all GUIDs are variant 2 UUIDs (e.g. Microsoft COM has GUIDs which are variant 3 UUIDs). If the question was "is there any difference between GUID and variant 2 UUIDs", then the answer would be yes -- they can be different. Someone asking the question probably doesn't know about variants and they might be only thinking of variant 2 UUIDs when they say the word "UUID" (e.g. they vaguely know of the MAC address+time and the random number algorithms forms of UUID, which are both versions of variant 2). In which case, the answer is yes different.
So the answer, in part, depends on what the person asking is thinking when they say the word "UUID". Do they mean variant 2 UUID (because that is the only variant they are aware of) or all UUIDs?
The second part depends on which specification being used as the definition of UUID.
If you think that was confusing, read the ITU-T X.667 ISO/IEC 9834-8:2004 which is supposed to be aligned and fully technically compatible with RFC 4122. It has an extra sentence in Clause 11.2 that says, "All UUIDs conforming to this Recommendation | International Standard shall have variant bits with bit 7 of octet 7 set to 1 and bit 6 of octet 7 set to 0". Which means that only variant 2 UUID conform to that Standard (those two bit values mean variant 2). If that is true, then not all GUIDs are conforming ITU-T/ISO/IEC UUIDs, because conformant ITU-T/ISO/IEC UUIDs can only be variant 2 values.
Therefore, the real answer also depends on which specification of UUID the question is asking about. Assuming we are clearly talking about all UUIDs and not just variant 2 UUIDs: there is no difference between GUID and IETF's UUIDs, but yes difference between GUID and conforming ITU-T/ISO/IEC's UUIDs!
Binary encodings could differ
When encoded in binary (as opposed to the human-readable text format), the GUID may be stored in a structure with four different fields as follows. This format differs from the [UUID standard] 8 only in the byte order of the first 3 fields.
Bits Bytes Name Endianness Endianness
(GUID) RFC 4122
32 4 Data1 Native Big
16 2 Data2 Native Big
16 2 Data3 Native Big
64 8 Data4 Big Big
This header is a part of the MFC Library. VS Express edition doesn't contain MFC. If your project doesn't use MFC you can safely replace afxres.h
with windows.h
in your terrain2.rc
.
After I plotted all the lines, I was able to set the transparency of all of them as follows:
for l in fig_field.gca().lines:
l.set_alpha(.7)
EDIT: please see Joe's answer in the comments.
If its text that has to scale proportionally to the screenwidth, you can also use the font as an svg, you can just export it from something like illustrator. I had to do this in my case, because I wanted to align the top of left and right border with the font's top |TEXT| . Using line-height, the text will jump up and down when scaling the window.
This is the correct way to detect this.
- (void)willMoveToParentViewController:(UIViewController *)parent{
if (parent == nil){
//do stuff
}
}
this method is called when view is pushed as well. So checking parent==nil is for popping view controller from stack
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery('.form-file input').each(function () {
$this = jQuery(this);
$this.on('change', function() {
var fsize = $this[0].files[0].size,
ftype = $this[0].files[0].type,
fname = $this[0].files[0].name,
fextension = fname.substring(fname.lastIndexOf('.')+1);
validExtensions = ["jpg","pdf","jpeg","gif","png","doc","docx","xls","xlsx","ppt","pptx","txt","zip","rar","gzip"];
if ($.inArray(fextension, validExtensions) == -1){
alert("This type of files are not allowed!");
this.value = "";
return false;
}else{
if(fsize > 3145728){/*1048576-1MB(You can change the size as you want)*/
alert("File size too large! Please upload less than 3MB");
this.value = "";
return false;
}
return true;
}
});
});
});
</script>
</head>
<body>
<form>
<div class="form-file">
<label for="file-upload" class="from-label">File Upload</label>
<input class="form-control" name="file-upload" id="file-upload" type="file">
</div>
</form>
</body>
</html>
Here is complete answer for checking file size and file extension. This used default file input field and jQuery library. Working example : https://jsfiddle.net/9pfjq6zr/2/
Given an OnTouchListener
private View.OnTouchListener handleTouch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("TAG", "touched down");
break;
case MotionEvent.ACTION_MOVE:
Log.i("TAG", "moving: (" + x + ", " + y + ")");
break;
case MotionEvent.ACTION_UP:
Log.i("TAG", "touched up");
break;
}
return true;
}
};
set on some view:
myView.setOnTouchListener(handleTouch);
This gives you the touch event coordinates relative to the view that has the touch listener assigned to it. The top left corner of the view is (0, 0)
. If you move your finger above the view, then y
will be negative. If you move your finger left of the view, then x
will be negative.
int x = (int)event.getX();
int y = (int)event.getY();
If you want the coordinates relative to the top left corner of the device screen, then use the raw values.
int x = (int)event.getRawX();
int y = (int)event.getRawY();
I was struggle with this error just because one of my class library
projects was set acceddentaly
to be an console application
so make sure your class library projects is class library in Output type
Take a look at my answer to a similar question.
By aliasing $index
we do not have to write crazy stuff like $parent.$parent.$index
.
Way more elegant solution whan $parent.$index
is using ng-init:
<ul ng-repeat="section in sections" ng-init="sectionIndex = $index">
<li class="section_title {{section.active}}" >
{{section.name}}
</li>
<ul>
<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(sectionIndex)" ng-repeat="tutorial in section.tutorials">
{{tutorial.name}}
</li>
</ul>
</ul>
Open your project build.gradle file and add below line under dependencies module.
dependencies {
compile 'com.google.android.gms:play-services:7.0.0'
}
The below will be add Google Analytics and Maps if you don't want to integrate full library
dependencies {
compile 'com.google.android.gms:play-services-analytics:7.0.0'
compile 'com.google.android.gms:play-services-maps:7.0.0'
}
You can print the PHP variable into your javascript while your page is created.
<script type="text/javascript">
var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
</script>
Of course this is for simple variables and not objects.
I kept having this problem whenever I tried to start an app pool more than once. Rather than rebooting, I simply run the Application Information Service. (Note: This service is set to run manually on my system, which may be the reason for the problem.) From its description, it seems obvious that it is somehow involved:
Facilitates the running of interactive applications with additional administrative privileges. If this service is stopped, users will be unable to launch applications with the additional administrative privileges they may require to perform desired user tasks.
Presumably, IIS manager (as well as most other processes running as an administrator) does not maintain admin privileges throughout the life of the process, but instead request admin rights from the Application Information service on a case-by-case basis.
Source: social.technech.microsoft.com
Check this out! It was built no longer ago in 2014.
Get a list of country/state/city in a hierarchy using geonames webservice
Using executeUpdate()
on the Query
API is faster because it bypasses the persistent context .However , by-passing persistent context would cause the state of instance in the memory and the actual values of that record in the DB are not synchronized.
Consider the following example :
Employee employee= (Employee)entityManager.find(Employee.class , 1);
entityManager
.createQuery("update Employee set name = \'xxxx\' where id=1")
.executeUpdate();
After flushing, the name in the DB is updated to the new value but the employee instance in the memory still keeps the original value .You have to call entityManager.refresh(employee)
to reload the updated name from the DB to the employee instance.It sounds strange if your codes still have to manipulate the employee instance after flushing but you forget to refresh() the employee instance as the employee instance still contains the original values.
Normally , executeUpdate()
is used in the bulk update process as it is faster due to bypassing the persistent context
The right way to update an entity is that you just set the properties you want to updated through the setters and let the JPA to generate the update SQL for you during flushing instead of writing it manually.
Employee employee= (Employee)entityManager.find(Employee.class ,1);
employee.setName("Updated Name");
I used this to get to grips with Comet, I have also set up Comet using the Java Glassfish server and found lots of other examples by subscribing to cometdaily.com
Technically you could do it with a straight TCP socket. I wouldn't recommend it however. I would highly recommend you use Apache HttpClient instead. In its simplest form:
GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();
and here is a more complete example.
You can easily do this as follows
#include <msclr/marshal_cppstd.h>
System::String^ xyz="Hi boys";
std::string converted_xyz=msclr::interop::marshal_as< std::string >( xyz);
You need to type result
to an array of string const result: string[] = [];
.
The accepted answer is very useful and quite comprehensive. However, the OP states
I would like to see a simple example to write a callback function.
So here you go, from C++11 you have std::function
so there is no need for function pointers and similar stuff:
#include <functional>
#include <string>
#include <iostream>
void print_hashes(std::function<int (const std::string&)> hash_calculator) {
std::string strings_to_hash[] = {"you", "saved", "my", "day"};
for(auto s : strings_to_hash)
std::cout << s << ":" << hash_calculator(s) << std::endl;
}
int main() {
print_hashes( [](const std::string& str) { /** lambda expression */
int result = 0;
for (int i = 0; i < str.length(); i++)
result += pow(31, i) * str.at(i);
return result;
});
return 0;
}
This example is by the way somehow real, because you wish to call function print_hashes
with different implementations of hash functions, for this purpose I provided a simple one. It receives a string, returns an int (a hash value of the provided string), and all that you need to remember from the syntax part is std::function<int (const std::string&)>
which describes such function as an input argument of the function that will invoke it.
Maybe this is useful to anyone in the future, I have implemented a custom Authorize Attribute like this:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class ClaimAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly string _claim;
public ClaimAuthorizeAttribute(string Claim)
{
_claim = Claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
if(user.Identity.IsAuthenticated && user.HasClaim(ClaimTypes.Name, _claim))
{
return;
}
context.Result = new ForbidResult();
}
}
What's new in .NET Framework 4 Client Profile RTM explains many of the differences:
When to use NET4 Client Profile and when to use NET4 Full Framework?
NET4 Client Profile:
Always target NET4 Client Profile for all your client desktop applications (including Windows Forms and WPF apps).NET4 Full framework:
Target NET4 Full only if the features or assemblies that your app need are not included in the Client Profile. This includes:
- If you are building Server apps. Such as:
o ASP.Net apps
o Server-side ASMX based web services- If you use legacy client scenarios. Such as:
o Use System.Data.OracleClient.dll which is deprecated in NET4 and not included in the Client Profile.
o Use legacy Windows Workflow Foundation 3.0 or 3.5 (WF3.0 , WF3.5)- If you targeting developer scenarios and need tool such as MSBuild or need access to design assemblies such as System.Design.dll
However, as stated on MSDN, this is not relevant for >=4.5:
Starting with the .NET Framework 4.5, the Client Profile has been discontinued and only the full redistributable package is available. Optimizations provided by the .NET Framework 4.5, such as smaller download size and faster deployment, have eliminated the need for a separate deployment package. The single redistributable streamlines the installation process and simplifies your app's deployment options.
This line
mnuActionLanguage.ComboBox.DisplayMember = "Lang.Language";
is wrong. Change it to
mnuActionLanguage.ComboBox.DisplayMember = "Language";
and it will work (even without DataBind()).
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
The difference between compile time and run time is an example of what pointy-headed theorists call the phase distinction. It is one of the hardest concepts to learn, especially for people without much background in programming languages. To approach this problem, I find it helpful to ask
What can go wrong are run-time errors:
Also there can be errors that are detected by the program itself:
ZedGraph is a good choice.
In Java, we declare a String of arrays (eg. car) as
String []car;
String car[];
We create the array using new operator and by specifying its type:-
String []car=new String[];
String car[]=new String[];
This assigns a reference, to an array of Strings, to car. You can also create the array by initializing it:-
String []car={"Sedan","SUV","Hatchback","Convertible"};
Since you haven't initialized an array and you're trying to access it, a NullPointerException is thrown.
The quick answer is 2^16 TCP ports, 64K.
The issues with system imposed limits is a configuration issue, already touched upon in previous comments.
The internal implications to TCP is not so clear (to me). Each port requires memory for it's instantiation, goes onto a list and needs network buffers for data in transit.
Given 64K TCP sessions the overhead for instances of the ports might be an issue on a 32-bit kernel, but not a 64-bit kernel (correction here gladly accepted). The lookup process with 64K sessions can slow things a bit and every packet hits the timer queues, which can also be problematic. Storage for in transit data can theoretically swell to the window size times ports (maybe 8 GByte).
The issue with connection speed (mentioned above) is probably what you are seeing. TCP generally takes time to do things. However, it is not required. A TCP connect, transact and disconnect can be done very efficiently (check to see how the TCP sessions are created and closed).
There are systems that pass tens of gigabits per second, so the packet level scaling should be OK.
There are machines with plenty of physical memory, so that looks OK.
The performance of the system, if carefully configured should be OK.
The server side of things should scale in a similar fashion.
I would be concerned about things like memory bandwidth.
Consider an experiment where you login to the local host 10,000 times. Then type a character. The entire stack through user space would be engaged on each character. The active footprint would likely exceed the data cache size. Running through lots of memory can stress the VM system. The cost of context switches could approach a second!
This is discussed in a variety of other threads: https://serverfault.com/questions/69524/im-designing-a-system-to-handle-10000-tcp-connections-per-second-what-problems
You most likely want to examine the documentation for T-SQL's CAST and CONVERT functions, located in the documentation here: http://msdn.microsoft.com/en-US/library/ms187928(v=SQL.90).aspx
You will then use one of those functions in your T-SQL query to convert the [idate] column from the database into the datetime format of your liking in the output.
Add this line top of the header
#pragma warning(disable : 4996)
You need run visudo
and in the editor that it opens write:
igor ALL=(ALL) ALL
That line grants all permissions to user igor
.
If you want permit to run only some commands, you need to list them in the line:
igor ALL=(ALL) /bin/kill, /bin/ps
You can assign "button" to role attribute of any html tag/element to make pointer over it. i.e
<html-element role="button" />
The $_post
function need the name value
like:
<input type="submit" value"Submit" name="example">
Call
$var = strip_tags($_POST['example']);
if (isset($var)){
// your code here
}
When using numbers as the key, I suppose you could also try this:
Map<Long, String> map = new HashMap<>();
map.put(4L, "The First");
map.put(6L, "The Second");
map.put(11L, "The Last");
long lastKey = 0;
//you entered Map<Long, String> entry
for (Map.Entry<Long, String> entry : map.entrySet()) {
lastKey = entry.getKey();
}
System.out.println(lastKey); // 11
You can't. Variables defined inside a method are local to that method.
If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Looks like you're using instance methods instead of static ones.
If you don't want to create an object, you should declare all your methods static, so something like
private static void methodName(Argument args...)
If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.
private static int[][] array = new int[3][5];
Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.
Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.
Here's a final (shortened) example of what your code should be like:
public class Test3 {
//Use this array in your methods
private static int[][] scores = new int[3][5];
/* Rather than just "Scores" name it so people know what
* to expect
*/
private static void createScores() {
//Code...
}
//Other methods...
/* Since you're now using static methods, you don't
* have to initialise an object and call its methods.
*/
public static void main(String[] args){
createScores();
MD(); //Don't know what these do
sumD(); //so I'll leave them.
}
}
Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.
At the moment it is not possible to import a CSV (using MySQL Workbench) in all platforms, nor is advised if said file does not reside in the same host as the MySQL server host.
However, you can use mysqlimport.
Example:
mysqlimport --local --compress --user=username --password --host=hostname \
--fields-terminated-by=',' Acme sales.part_*
In this example mysqlimport
is instructed to load all of the files named "sales" with an extension starting with "part_". This is a convenient way to load all of the files created in the "split" example. Use the --compress option to minimize network traffic. The --fields-terminated-by=',' option is used for CSV files and the --local option specifies that the incoming data is located on the client. Without the --local option, MySQL will look for the data on the database host, so always specify the --local option.
There is useful information on the subject in AWS RDS documentation.
sqlcmd -S mamxxxxxmu\sqlserverr -U sa -P x1123 -d QLDB -i D:\qldbscript.sql
Open command prompt in run as administrator
enter above command
"mamxxxxxmu" is computer name "sqlserverr" is server name "sa" is username of server "x1123" is password of server "QLDB" is database name "D:\qldbscript.sql" is sql script file to execute in database
-Dcom.sun.net.ssl.checkRevocation=false
If you have pandas
installed, you can convert the ordered dict to a pandas Series
. This will allow random access to the dictionary elements.
>>> import collections
>>> import pandas as pd
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> s = pd.Series(d)
>>> s['bar']
spam
>>> s.iloc[1]
spam
>>> s.index[1]
bar
Angular 7,8 fix is in app.module.ts
import {APP_BASE_HREF} from '@angular/common';
inside @NgModule add
providers: [{provide: APP_BASE_HREF, useValue: '/'}]
Since you've already stashed your changes, all you need is this one-liner:
git stash branch <branchname> [<stash>]
From the docs (https://www.kernel.org/pub/software/scm/git/docs/git-stash.html):
Creates and checks out a new branch named <branchname> starting from the commit at which the <stash> was originally created, applies the changes recorded in <stash> to the new working tree and index. If that succeeds, and <stash> is a reference of the form stash@{<revision>}, it then drops the <stash>. When no <stash> is given, applies the latest one.
This is useful if the branch on which you ran git stash save has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.
Use GUID constructor standard functionality
Public Function IsValid(pString As String) As Boolean
Try
Dim mGuid As New Guid(pString)
Catch ex As Exception
Return False
End Try
Return True
End Function
The thing you can do is create a .bat that will execute the .jar file created, checking if there is a JRE present.
From Mitch useful link (source)
java -classpath myprogram.jar de.vogella.eclipse.ide.first.MyFirstClass
This can be used into your batch...
I wondered how the functions will perform for different sets, so I did a benchmark:
from random import sample
def ForLoop(s):
for e in s:
break
return e
def IterNext(s):
return next(iter(s))
def ListIndex(s):
return list(s)[0]
def PopAdd(s):
e = s.pop()
s.add(e)
return e
def RandomSample(s):
return sample(s, 1)
def SetUnpacking(s):
e, *_ = s
return e
from simple_benchmark import benchmark
b = benchmark([ForLoop, IterNext, ListIndex, PopAdd, RandomSample, SetUnpacking],
{2**i: set(range(2**i)) for i in range(1, 20)},
argument_name='set size',
function_aliases={first: 'First'})
b.plot()
This plot clearly shows that some approaches (RandomSample
, SetUnpacking
and ListIndex
) depend on the size of the set and should be avoided in the general case (at least if performance might be important). As already shown by the other answers the fastest way is ForLoop
.
However as long as one of the constant time approaches is used the performance difference will be negligible.
iteration_utilities
(Disclaimer: I'm the author) contains a convenience function for this use-case: first
:
>>> from iteration_utilities import first
>>> first({1,2,3,4})
1
I also included it in the benchmark above. It can compete with the other two "fast" solutions but the difference isn't much either way.
You can use below code snippet to read line by line, till end of file:
line = obj.readline()
while(line != ''):
# Do Something
line = obj.readline()
Introduction
This is based on Android's java and it's a good example on changing the database without annoying your application fans/customers. This is based on the idea of the SQLite FAQ page http://sqlite.org/faq.html#q11
The problem
I did not notice that I need to set a row_number or record_id to delete a single purchased item in a receipt, and at same time the item barcode number fooled me into thinking of making it as the key to delete that item. I am saving a receipt details in the table receipt_barcode. Leaving it without a record_id can mean deleting all records of the same item in a receipt if I used the item barcode as the key.
Notice
Please understand that this is a copy-paste of my code I am work on at the time of this writing. Use it only as an example, copy-pasting randomly won't help you. Modify this first to your needs
Also please don't forget to read the comments in the code .
The Code
Use this as a method in your class to check 1st whether the column you want to add is missing . We do this just to not repeat the process of altering the table receipt_barcode. Just mention it as part of your class. In the next step you'll see how we'll use it.
public boolean is_column_exists(SQLiteDatabase mDatabase , String table_name,
String column_name) {
//checks if table_name has column_name
Cursor cursor = mDatabase.rawQuery("pragma table_info("+table_name+")",null);
while (cursor.moveToNext()){
if (cursor.getString(cursor.getColumnIndex("name")).equalsIgnoreCase(column_name)) return true;
}
return false;
}
Then , the following code is used to create the table receipt_barcode if it already does NOT exit for the 1st time users of your app. And please notice the "IF NOT EXISTS" in the code. It has importance.
//mDatabase should be defined as a Class member (global variable)
//for ease of access :
//SQLiteDatabse mDatabase=SQLiteDatabase.openOrCreateDatabase(dbfile_path, null);
creation_query = " CREATE TABLE if not exists receipt_barcode ( ";
creation_query += "\n record_id INTEGER PRIMARY KEY AUTOINCREMENT,";
creation_query += "\n rcpt_id INT( 11 ) NOT NULL,";
creation_query += "\n barcode VARCHAR( 255 ) NOT NULL ,";
creation_query += "\n barcode_price VARCHAR( 255 ) DEFAULT (0),";
creation_query += "\n PRIMARY KEY ( record_id ) );";
mDatabase.execSQL(creation_query);
//This is where the important part comes in regarding the question in this page:
//adding the missing primary key record_id in table receipt_barcode for older versions
if (!is_column_exists(mDatabase, "receipt_barcode","record_id")){
mDatabase.beginTransaction();
try{
Log.e("record_id", "creating");
creation_query="CREATE TEMPORARY TABLE t1_backup(";
creation_query+="record_id INTEGER PRIMARY KEY AUTOINCREMENT,";
creation_query+="rcpt_id INT( 11 ) NOT NULL,";
creation_query+="barcode VARCHAR( 255 ) NOT NULL ,";
creation_query+="barcode_price VARCHAR( 255 ) NOT NULL DEFAULT (0) );";
mDatabase.execSQL(creation_query);
creation_query="INSERT INTO t1_backup(rcpt_id,barcode,barcode_price) SELECT rcpt_id,barcode,barcode_price FROM receipt_barcode;";
mDatabase.execSQL(creation_query);
creation_query="DROP TABLE receipt_barcode;";
mDatabase.execSQL(creation_query);
creation_query="CREATE TABLE receipt_barcode (";
creation_query+="record_id INTEGER PRIMARY KEY AUTOINCREMENT,";
creation_query+="rcpt_id INT( 11 ) NOT NULL,";
creation_query+="barcode VARCHAR( 255 ) NOT NULL ,";
creation_query+="barcode_price VARCHAR( 255 ) NOT NULL DEFAULT (0) );";
mDatabase.execSQL(creation_query);
creation_query="INSERT INTO receipt_barcode(record_id,rcpt_id,barcode,barcode_price) SELECT record_id,rcpt_id,barcode,barcode_price FROM t1_backup;";
mDatabase.execSQL(creation_query);
creation_query="DROP TABLE t1_backup;";
mDatabase.execSQL(creation_query);
mdb.setTransactionSuccessful();
} catch (Exception exception ){
Log.e("table receipt_bracode", "Table receipt_barcode did not get a primary key (record_id");
exception.printStackTrace();
} finally {
mDatabase.endTransaction();
}
Old post I know, but unless I've misunderstood the question, this should do the trick:
s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
alert(array[i][index]);
}
}
Doing it the mathy way...
nums = [1, 2, 3, 4, 5]
min_combo = (min(nums), max(nums))
Unless, of course, you have negatives in there. In that case, this won't work because you actually want the min and max absolute values - the numerator should be close to zero, and the denominator far from it, in either direction. And double negatives would break it.
unzip
doesn't spew files everywhereWhen zipping directories, keeping the parent directory in the archive will help to avoid littering your current directory when you later unzip the archive file
So to avoid retaining all paths, and since you can't use -j and -r together ( you'll get an error ), you can do this instead:
cd path/to/parent/dir/;
zip -r ../my.zip ../$(basename $PWD)
cd -;
The ../$(basename $PWD)
is the magic that retains the parent directory.
So now unzip my.zip
will give a folder containing all your files:
parent-directory
+-- file1
+-- file2
+-- dir1
¦ +-- file3
¦ +-- file4
Instead of littering the current directory with the unzipped files:
file1
file2
dir1
+-- file3
+-- file4
I tried
in different combinations.
But going from Intellij 2020 version to 2019 solved my issue.
I don't have Python 2.7 installed, but in Python 3.3 calling Popen
with stdout
set to sys.stdout
worked just fine. Not before I had escaped the backslashes in the path, though.
>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_
I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.
According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.
According to their documentation, here's what you would send:
http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>
And here's what you would receive back:
<?xml version="1.0"?>
<CityStateLookupResponse>
<ZipCode ID="0">
<Zip5>90210</Zip5>
<City>BEVERLY HILLS</City>
<State>CA</State>
</ZipCode>
</CityStateLookupResponse>
USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.
Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here
This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:
GET http://ziptasticapi.com/48867
And they will return a JSON object along the lines of:
{"country": "US", "state": "MI", "city": "OWOSSO"}
Indeed, it works. You can test this from a command line by doing something like:
curl http://ziptasticapi.com/48867
Just adding a example code to Greg's answer:
dim sqlstmt as new StringBuilder
sqlstmt.add("SELECT * FROM Products")
sqlstmt.add(" WHERE 1=1")
''// From now on you don't have to worry if you must
''// append AND or WHERE because you know the WHERE is there
If ProductCategoryID <> 0 then
sqlstmt.AppendFormat(" AND ProductCategoryID = {0}", trim(ProductCategoryID))
end if
If MinimunPrice > 0 then
sqlstmt.AppendFormat(" AND Price >= {0}", trim(MinimunPrice))
end if
I like the simplicity of tabulary
package:
\usepackage{tabulary}
...
\begin{tabulary}{\linewidth}{LCL}
\hline
Short sentences & \# & Long sentences \\
\hline
This is short. & 173 & This is much loooooooonger, because there are many more words. \\
This is not shorter. & 317 & This is still loooooooonger, because there are many more words. \\
\hline
\end{tabulary}
In the example, you arrange the whole width of the table with respect to \textwidth. E.g 0.4 of it. Then the rest is automatically done by the package.
Most of the example is taken from http://en.wikibooks.org/wiki/LaTeX/Tables .
To get the number of votes for a specific item, you would use:
vote_count = Item.objects.filter(votes__contest=contestA).count()
If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:
contest = Contest.objects.get(pk=contest_id)
votes = contest.votes_set.select_related()
vote_counts = {}
for vote in votes:
if not vote_counts.has_key(vote.item.id):
vote_counts[vote.item.id] = {
'item': vote.item,
'count': 0
}
vote_counts[vote.item.id]['count'] += 1
This will create dictionary that maps items to number of votes. Not the only way to do this, but it's pretty light on database hits, so will run pretty quickly.
There is no difference between both, AS
is just a more explicit way of mentioning the alias which is good because some dependent libraries depends on this small keyword. e.g. JDBC 4.0. Depend on use of it, different behaviour can be observed.
See this. I would always suggest to use the full form of semantic to avoid such issues.
You may use an iterator over each byte in the output of the subprocess. This allows inline update (lines ending with '\r' overwrite previous output line) from the subprocess:
from subprocess import PIPE, Popen
command = ["my_command", "-my_arg"]
# Open pipe to subprocess
subprocess = Popen(command, stdout=PIPE, stderr=PIPE)
# read each byte of subprocess
while subprocess.poll() is None:
for c in iter(lambda: subprocess.stdout.read(1) if subprocess.poll() is None else {}, b''):
c = c.decode('ascii')
sys.stdout.write(c)
sys.stdout.flush()
if subprocess.returncode != 0:
raise Exception("The subprocess did not terminate correctly.")
It means there is a problem with the build path in your project. If it is an android project then it mostly means the target value specified in project.properties file cannot be found. This can also be caused because of other kinds of built problems. But it is shown mostly for built problems only. See here for more details. It is about built error decorater seen in eclipse.
An extract from that page:
Build path problems are sometimes easy to miss among other problems in a project. The Package Explorer and Project Explorer views now show a new decorator on Java projects and working sets that contain build path errors:
The concrete errors can be seen in the Problems view, and if you open the view menu and select Group By > Java Problem Type, they all show up in the Build Path category:
Sample DF:
In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))
In [80]: df
Out[80]:
a b c
0 6 11 11
1 14 7 8
2 13 5 11
3 13 7 11
4 13 5 9
5 5 11 9
6 9 8 6
7 5 11 10
8 8 10 14
9 7 14 13
present only those rows where b > 10
In [81]: df[df.b > 10]
Out[81]:
a b c
0 6 11 11
5 5 11 9
7 5 11 10
9 7 14 13
Minimums (for all columns) for the rows satisfying b > 10
condition
In [82]: df[df.b > 10].min()
Out[82]:
a 5
b 11
c 9
dtype: int32
Minimum (for the b
column) for the rows satisfying b > 10
condition
In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11
UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.
I found that my dfs both had the same type column (str
) but switching from join
to merge
solved the issue.
System.out.print(a + "" + b + "" + c);
SELECT sobjects.name
FROM sysobjects sobjects
WHERE sobjects.xtype = 'U'
Here is an example that should help. If you have a timestamp with a timezone, you can convert that timestamp into any other timezone. If you haven't got a base timezone it won't be converted correctly.
SELECT now(),
now()::timestamp,
now() AT TIME ZONE 'CST',
now()::timestamp AT TIME ZONE 'CST'
Output:
-[ RECORD 1 ]---------------------------
now | 2018-09-15 17:01:36.399357+03
now | 2018-09-15 17:01:36.399357
timezone | 2018-09-15 08:01:36.399357
timezone | 2018-09-16 02:01:36.399357+03
I tried this: When you are creating your Retrofit instance, add this converter factory to the retrofit builder:
gsonBuilder = new GsonBuilder().serializeNulls()
your_retrofit_instance = Retrofit.Builder().addConverterFactory( GsonConverterFactory.create( gsonBuilder.create() ) )
scrolldelay="number"
I was really surprised that Scribe logging framework that I use at work isn't even mentioned here. What is more, it doesn't even appear on the first page in Google after searching "scala logging". But this page appears when googling it! So let me leave that here.
Main advantages of Scribe:
Try this.
// uses the URL class
function setParam(key, value) {
let url = new URL(window.document.location);
let params = new URLSearchParams(url.search.slice(1));
if (params.has(key)) {
params.set(key, value);
}else {
params.append(key, value);
}
}
.str.get
This is the simplest to specify string methods
# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df
A B
0 xyz 123
1 abc 456
2 foobar 789
df.dtypes
A object
B int64
dtype: object
For string (read:object
) type columns, use
df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)
.str
handles NaNs by returning NaN as the output.
For non-numeric columns, an .astype
conversion is required beforehand, as shown in @Ed Chum's answer.
# Note that this won't work well if the data has NaNs.
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.
# For string columns
df['C'] = [x[0] for x in df['A']]
# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
If your data has NaNs, then you will need to handle this appropriately with an if
/else
in the list comprehension,
df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2
A B
0 xyz 123.0
1 NaN 456.0
2 foobar NaN
# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]
# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]
A B C D
0 xyz 123.0 x 1
1 NaN 456.0 NaN 4
2 foobar NaN f NaN
Let's do some timeit tests on some larger data.
df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True)
%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])
%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])
12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
List comprehensions are 4x faster.
How about creating your own Custom Panel class? That way you won't have to worry about overriding Bootstrap.
HTML
<div class="panel panel-custom-horrible-red">
<div class="panel-heading">
<h3 class="panel-title">Panel title</h3>
</div>
<div class="panel-body">
Panel content
</div>
</div>
CSS
.panel-custom-horrible-red {
border-color: #ff0000;
}
.panel-custom-horrible-red > .panel-heading {
background: #ff0000;
color: #ffffff;
border-color: #ff0000;
}
Fiddle: https://jsfiddle.net/x05f4crg/1/
This problem happening when your build tool is not set to do restore
on projects set to use PackageReference
vs packages.config
and mostly affect Net Core and Netstandard new style projects.
When you open Visual Studio and build, it resolves this for you. But if you use automation, CLI tools, you see this issue.
Many solutions are offered here. But all you need to remember, you need to force restore
. In some instances you use dotnet restore
before build. If you build using MsBuild just add /t:Restore
switch to your command.
Bottom line, you need to see why restoring can't be activated. Either bad nuget source or missing restore action, or outdated nuget.exe, or all of the above.
Previous responses didn't work with my problem. It was only in production, with tomcat and apache mod_proxy_ajp. Post body lost non ascii chars by ? The problem finally was with JVM defaultCharset (US-ASCII in a default instalation: Charset dfset = Charset.defaultCharset();) so, the solution was run tomcat server with a modifier to run the JVM with UTF-8 as default charset:
JAVA_OPTS="$JAVA_OPTS -Dfile.encoding=UTF-8"
(add this line to catalina.sh and service tomcat restart)
Maybe you must also change linux system variable (edit ~/.bashrc and ~/.profile for permanent change, see https://perlgeek.de/en/article/set-up-a-clean-utf8-environment)
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8export LANGUAGE=en_US.UTF-8
Try this
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions
ON user_category_subscriptions.category_id = categories.category_id
WHERE user_category_subscriptions.user_id = 1
or user_category_subscriptions.user_id is null
if problem:
mywindow.print();
altenative using:
'<scr'+'ipt>print()</scr'+'ipt>'
Full:
$('.print-ticket').click(function(){
var body = $('body').html();
var ticket_area = '<aside class="widget tickets">' + $('.widget.tickets').html() + '</aside>';
$('body').html(ticket_area);
var print_html = '<html lang="tr">' + $('html').html() + '<scr'+'ipt>print()</scr'+'ipt>' + '</html>';
$('body').html(body);
var mywindow = window.open('', 'my div', 'height=600,width=800');
mywindow.document.write(print_html);
mywindow.document.close(); // necessary for IE >= 10'</html>'
mywindow.focus(); // necessary for IE >= 10
//mywindow.print();
mywindow.close();
return true;
});
You need to use the name of your form, as well as ng-disabled: Here's a demo on Plunker
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="myForm.$invalid">Save</button>
</form>
You must run git fetch
before you can compare your local repository against the files on your remote server.
This command only updates your remote tracking branches and will not affect your worktree until you call git merge
or git pull
.
To see the difference between your local branch and your remote tracking branch once you've fetched you can use git diff or git cherry as explained here.
I resolved this issue on centos5.4 by running the following command to install setuptools
yum install python-setuptools
I hope that helps.
MATLAB's FOR loop is static in nature; you cannot modify the loop variable between iterations, unlike the for(initialization;condition;increment) loop structure in other languages. This means that the following code always prints 1, 2, 3, 4, 5 regardless of the value of B.
A = 1:5;
for i = A
A = B;
disp(i);
end
If you want to be able to respond to changes in the data structure during iterations, a WHILE loop may be more appropriate --- you'll be able to test the loop condition at every iteration, and set the value of the loop variable(s) as you wish:
n = 10;
f = n;
while n > 1
n = n-1;
f = f*n;
end
disp(['n! = ' num2str(f)])
Btw, the for-each loop in Java (and possibly other languages) produces unspecified behavior when the data structure is modified during iteration. If you need to modify the data structure, you should use an appropriate Iterator instance which allows the addition and removal of elements in the collection you are iterating. The good news is that MATLAB supports Java objects, so you can do something like this:
A = java.util.ArrayList();
A.add(1);
A.add(2);
A.add(3);
A.add(4);
A.add(5);
itr = A.listIterator();
while itr.hasNext()
k = itr.next();
disp(k);
% modify data structure while iterating
itr.remove();
itr.add(k);
end
You can use opendir()
and check if ENOENT == errno
on failure:
#include <dirent.h>
#include <errno.h>
DIR* dir = opendir("mydir");
if (dir) {
/* Directory exists. */
closedir(dir);
} else if (ENOENT == errno) {
/* Directory does not exist. */
} else {
/* opendir() failed for some other reason. */
}
Run the following command to enable credential caching.
$ git config credential.helper store
$ git push https://github.com/repo.git
Username for 'https://github.com': <USERNAME>
Password for 'https://[email protected]': <PASSWORD>
Use should also specify caching expire,
git config --global credential.helper 'cache --timeout 7200'
After enabling credential caching, it will be cached for 7200 seconds (2 hours).
Note: Credential helper stores an unencrypted password on a local disk.
I had the same problem but finally I found the way.
Here is the walk through:
1- Install VLC on your computer (SERVER) and go to Media->Streaming (Ctrl+S)
2- Select a file to stream or if you want to stream your webcam or... click on "Capture Device" tab and do the configuration and finally click on "Stream" button.
3- Here you should do the streaming server configuration, just go to "Option" tab and paste the following command:
:sout=#transcode{vcodec=mp4v,vb=400,fps=10,width=176,height=144,acodec=mp4a,ab=32,channels=1,samplerate=22050}:rtp{sdp=rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/}
NOTE: Replace YOURCOMPUTER_SERVER_IP_ADDR with your computer IP address or any server which is running VLC...
NOTE: You can see, the video codec is MP4V which is supported by android.
4- go to eclipse and create a new project for media playbak. create a VideoView object and in the OnCreate() function write some code like this:
mVideoView = (VideoView) findViewById(R.id.surface_view);
mVideoView.setVideoPath("rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/");
mVideoView.setMediaController(new MediaController(this));
5- run the apk on the device (not simulator, i did not check it) and wait for the playback to be started. please consider the buffering process will take about 10 seconds...
Question: Anybody know how to reduce buffering time and play video almost live ?
You can try something like this:
$scope.test = "test1,test2";
{{test.split(',')[0]}}
now you will get "test1" while you try {{test.split(',')[0]}}
and you will get "test2" while you try {{test.split(',')[1]}}
here is my plnkr:
My approach:
var temp = { arr : originalArray };
var obj = $.extend(true, {}, temp);
return obj.arr;
gives me a nice, clean, deep clone of the original array - with none of the objects referenced back to the original :-)
EDIT:
The OP was not looking to use cross-domain requests, but jQuery supports JSONP as of v1.5. See jQuery.ajax(), specificically the crossDomain
parameter.
The regular jQuery Ajax requests will not work cross-site, so if you want to query a remote RESTful web service, you'll probably have to make a proxy on your server and query that with a jQuery get request. See this site for an example.
If it's a SOAP web service, you may want to try the jqSOAPClient plugin.
I found the InvokeRequired
not reliable, so I simply use
if (!this.IsHandleCreated)
{
this.CreateHandle();
}
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
check more details about complexity analysis http://javamicro.com/ref-card/DS-Algo/How-to-Reverse-Singly-Linked-List?
You can use AppendAllText
instead:
File.AppendAllText(filePath, csv);
As the documentation of WriteAllText
says:
If the target file already exists, it is overwritten
Also, note that your current code is not using proper new lines, for example in Notepad you'll see it all as one long line. Change the code to this to have proper new lines:
string csv = string.Format("{0},{1}{2}", first, image, Environment.NewLine);
I tried both,
pip install jupyter
and
pip3 install jupyter
but finally got it done using
sudo -H pip install jupyter
execute a command as another user -H
The -H (HOME) option requests that the security policy set the HOME environment variable to the home directory of the target user (root by default) as specified by the password database. Depending on the policy, this may be the default behavior.
StringUtils.substringAfterLast("abcd: efg: 1006746", ": ") = "1006746";
As long as the format of the string is fixed you can use substringAfterLast.
You can use Python retrying package. Retrying
It is written in Python to simplify the task of adding retry behavior to just about anything.
Based on my experience, solution which is fine(the best) when keys are not important:
$cart = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
With angular 6 and rxjs 6 Observable.throw()
, Observable.off()
has been deprecated instead you need to use throwError
ex :
return this.http.get('yoururl')
.pipe(
map(response => response.json()),
catchError((e: any) =>{
//do your processing here
return throwError(e);
}),
);
$(window).height();
To set anything in the middle you can use CSS.
<style>
#divCentre
{
position: absolute;
left: 50%;
top: 50%;
width: 300px;
height: 400px;
margin-left: -150px;
margin-top: -200px;
}
</style>
<div id="divCentre">I am at the centre</div>
Nirsoft's NirCMD can create shortcuts from a command line, too. (Along with a pile of other functions.) Free and available here:
http://www.nirsoft.net/utils/nircmd.html
Full instructions here: http://www.nirsoft.net/utils/nircmd2.html#using (Scroll down to the "shortcut" section.)
Yes, using nircmd does mean you are using another 3rd-party .exe, but it can do some functions not in (most of) the above solutions (e.g., pick a icon # in a dll with multiple icons, assign a hot-key, and set the shortcut target to be minimized or maximized).
Though it appears that the shortcutjs.bat solution above can do most of that, too, but you'll need to dig more to find how to properly assign those settings. Nircmd is probably simpler.
do this in two steps:
and use preg_replace
:
$stringWithoutNonLetterCharacters = preg_replace("/[\/\&%#\$]/", "_", $yourString);
$stringWithQuotesReplacedWithSpaces = preg_replace("/[\"\']/", " ", $stringWithoutNonLetterCharacters);
Descending:
Collections.sort(mArrayList, new Comparator<CustomData>() {
@Override
public int compare(CustomData lhs, CustomData rhs) {
// -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
return lhs.customInt > rhs.customInt ? -1 : (lhs.customInt < rhs.customInt) ? 1 : 0;
}
});
Here is a cross-browser solution if you don't want to use jQuery:
/**
* Resizes the given iFrame width so it fits its content
* @param e The iframe to resize
*/
function resizeIframeWidth(e){
// Set width of iframe according to its content
if (e.Document && e.Document.body.scrollWidth) //ie5+ syntax
e.width = e.contentWindow.document.body.scrollWidth;
else if (e.contentDocument && e.contentDocument.body.scrollWidth) //ns6+ & opera syntax
e.width = e.contentDocument.body.scrollWidth + 35;
else (e.contentDocument && e.contentDocument.body.offsetWidth) //standards compliant syntax – ie8
e.width = e.contentDocument.body.offsetWidth + 35;
}