I tried (with minor changes as suggested) the code from Andrew Cooke's answer. (I am running python 2.7).
The code:
#!/usr/bin/env python
class Celsius:
def __get__(self, instance, owner): return 9 * (instance.fahrenheit + 32) / 5.0
def __set__(self, instance, value): instance.fahrenheit = 32 + 5 * value / 9.0
class Temperature:
def __init__(self, initial_f): self.fahrenheit = initial_f
celsius = Celsius()
if __name__ == "__main__":
t = Temperature(212)
print(t.celsius)
t.celsius = 0
print(t.fahrenheit)
The result:
C:\Users\gkuhn\Desktop>python test2.py
<__main__.Celsius instance at 0x02E95A80>
212
With Python prior to 3, make sure you subclass from object which will make the descriptor work correctly as the get magic does not work for old style classes.
I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?
You could check in the following way (extra = and making length a truthy evaluation)
if (typeof(sub.from) !== 'undefined' && sub.from.length) {
[update]
I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:
for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
mainid = sub.from[i]['id'];
var sub = afcHelper_Submissions[mainid]; // <== re setting sub
My guess is that the error is not on the if statement but on the for(i...
statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).
If you're using Ubuntu then use the following:
sudo chown -R ubuntu /var/www/html
sudo chmod -R 755 /var/www/html
for x in y[:-1]
If y
is a generator, then the above will not work.
Add:
using System.Linq;
to the top of your file.
And then:
Car[] carList = ...
var carMake =
from item in carList
where item.Model == "bmw"
select item.Make;
or if you prefer the fluent syntax:
var carMake = carList
.Where(item => item.Model == "bmw")
.Select(item => item.Make);
Things to pay attention to:
item.Make
in the select
clause instead if s.Make
as in your code.item
and .Model
in your where
clauseThis is what you are trying to do but it poses some security and encoding problems so don't do it.
$url = "http://localhost/main.php?email=" . $email_address . "&eventid=" . $event_id;
All variables in querystrings need to be urlencoded to ensure proper transmission. You should never pass a user's personal information in a url because urls are very leaky. Urls end up in log files, browsing histories, referal headers, etc. The list goes on and on.
As for proper url encoding, it can be achieved using either urlencode()
or http_build_query()
. Either one of these should work:
$url = "http://localhost/main.php?email=" . urlencode($email_address) . "&eventid=" . urlencode($event_id);
or
$vars = array('email' => $email_address, 'event_id' => $event_id);
$querystring = http_build_query($vars);
$url = "http://localhost/main.php?" . $querystring;
Additionally, if $event_id
is in your session, you don't actually need to pass it around in order to access it from different pages. Just call session_start()
and it should be available.
As others have suggested, you can directly write a 2-dimensional array into a Range on sheet, however if your array is single-dimensional then you have two options:
Here is an example depicting both options:
Sub PrintArrayIn1Cell(myArr As Variant, cell As Range) cell = Join(myArr, ",") End Sub Sub PrintArrayAsRange(myArr As Variant, cell As Range) cell.Resize(UBound(myArr, 1), UBound(myArr, 2)) = myArr End Sub Sub TestPrintArrayIntoSheet() '2dArrayToSheet Dim arr As Variant arr = Split("a b c", " ") 'Printing in ONE-CELL: To print all array-elements as a single string separated by comma (a,b,c): PrintArrayIn1Cell arr, [A1] 'Printing in SEPARATE-CELLS: To print array-elements in separate cells: Dim arr2D As Variant arr2D = Application.WorksheetFunction.Transpose(arr) 'convert a 1D array into 2D array PrintArrayAsRange arr2D, Range("B1:B3") End Sub
Note: Transpose will render column-by-column output, to get row-by-row output transpose it again - hope that makes sense.
HTH
the plus works just fine, i personally prefer using the concat function.
var s = string.Concat(string 1, string 2, string, 3, etc)
If lib/__init__.py
defines the Helper class then in settings.py you can use:
from . import Helper
This works because . is the current directory, and acts as a synonym for the lib package from the point of view of the settings module. Note that it is not necessary to export Helper via __all__
.
(Confirmed with python 2.7.10, running on Windows.)
"but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?"
Wow, that's a lot of hand-wringing.
An "an example of the sort of expression you could use" would not be a representation of a specific object. That can't be useful or meaningful.
What is the difference between "an actual expression, that can ... recreate the object" and "a rehasing of the actual expression which was used [to create the object]"? Both are an expression that creates the object. There's no practical distinction between these. A repr call could produce either a new expression or the original expression. In many cases, they're the same.
Note that this isn't always possible, practical or desirable.
In some cases, you'll notice that repr() presents a string which is clearly not an expression of any kind. The default repr() for any class you define isn't useful as an expression.
In some cases, you might have mutual (or circular) references between objects. The repr() of that tangled hierarchy can't make sense.
In many cases, an object is built incrementally via a parser. For example, from XML or JSON or something. What would the repr be? The original XML or JSON? Clearly not, since they're not Python. It could be some Python expression that generated the XML. However, for a gigantic XML document, it might not be possible to write a single Python expression that was the functional equivalent of parsing XML.
let startDate = "2019-01-16T20:00:00.000";
let endDate = "2019-02-11T20:00:00.000";
let sDate = new Date(startDate);
let eDate = new Date(endDate);
startDate = moment(sDate);
endDate = moment(eDate);
I had the same issue. The Authentication Error can be because of your security settings, the 2-step verification for instance. It wont allow third party apps to override the authentication.
Step 1 [Link of Disabling 2-step verification]:
https://myaccount.google.com/security?utm_source=OGB&utm_medium=act#signin
Step 2: [Link for Allowing less secure apps]
https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none
It should be all good now.
Using Swift, it would be:
if myDic[KEY] != nil {
// key exists
}
If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.
Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.
If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.
There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd
on Mac and ifconfig
works differently.
The following table is useful for knowing the various unix shells.
sh The original Bourne shell Present on every unix system
ksh Original Korn shell Richer shell programming environment than sh
csh Original C-shell C-like syntax; early versions buggy
tcsh Enhanced C-shell User-friendly and less buggy csh implementation
bash GNU Bourne-again shell Enhanced and free sh implementation
zsh Z shell Enhanced, user-friendly ksh-like shell
You may also find these guides helpful:
http://homepage.mac.com/rgriff/files/TerminalBasics.pdf
http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html
On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile
on OSX) file with aliases, some examples below.
I now placed all my aliases in a separate .bash_aliases file and include it with:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
in the .bashrc or .bash_profile file.
Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto
. The first time I did this (without knowing) I redefined ls
to be invalid which was a bit alarming until I removed --auto-color
!
You may also find https://unix.stackexchange.com/q/127799/10043 useful
# ~/.bash_aliases
# ls variants
#alias l='ls -CF'
alias la='ls -A'
alias l='ls -alFtr'
alias lsd='ls -d .*'
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i'
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed'
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status'
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'
CodeIgniter Active Records do not currently support sub-queries, However I use the following approach:
#Create where clause
$this->db->select('id_cer');
$this->db->from('revokace');
$where_clause = $this->db->_compile_select();
$this->db->_reset_select();
#Create main query
$this->db->select('*');
$this->db->from('certs');
$this->db->where("`id` NOT IN ($where_clause)", NULL, FALSE);
_compile_select() and _reset_select() are two undocumented (AFAIK) methods which compile the query and return the sql (without running it) and reset the query.
On the main query the FALSE in the where clause tells codeigniter not to escape the query (or add backticks etc) which would mess up the query. (The NULL is simply because the where clause has an optional second parameter we are not using)
However you should be aware as _compile_select() and _reset_select() are not documented methods it is possible that there functionality (or existence) could change in future releases.
you can also use this to read all the lines in the file one by one then print i
#include <iostream>
#include <fstream>
using namespace std;
bool check_file_is_empty ( ifstream& file){
return file.peek() == EOF ;
}
int main (){
string text[256];
int lineno ;
ifstream file("text.txt");
int num = 0;
while (!check_file_is_empty(file))
{
getline(file , text[num]);
num++;
}
for (int i = 0; i < num ; i++)
{
cout << "\nthis is the text in " << "line " << i+1 << " :: " << text[i] << endl ;
}
system("pause");
return 0;
}
hope this could help you :)
Inside relative path tag do as follows
<relative>{project_name}/pom.xml</relative>
and then RunAs-> Maven build
It worked for me.
Using Proxies:
var a = new Proxy({ i: 0 }, {
get: (target, name) => name === Symbol.toPrimitive ? () => ++target.i : target[name],
});
console.log(a == 1 && a == 2 && a == 3);
Proxies basically pretend to be a target object (the first parameter), but intercept operations on the target object (in this case the "get property" operation) so that there is an opportunity to do something other than the default object behavior. In this case the "get property" action is called on a
when ==
coerces its type in order to compare it to each number. This happens:
{ i: 0 }
, where the i
property is our countera
a ==
comparison, a
's type is coerced to a primitive valuea[Symbol.toPrimitive]()
internallya[Symbol.toPrimitive]
function using the "get handler"Symbol.toPrimitive
, in which case it increments and then returns the counter from the target object: ++target.i
. If a different property is being retrieved, we just fall back to returning the default property value, target[name]
So:
var a = ...; // a.valueOf == target.i == 0
a == 1 && // a == ++target.i == 1
a == 2 && // a == ++target.i == 2
a == 3 // a == ++target.i == 3
As with most of the other answers, this only works with a loose equality check (==
), because strict equality checks (===
) do not do type coercion that the Proxy can intercept.
you can use following UIView category -
@implementation UIView (SnapShot)
- (UIImage *)snapshotImage
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];
// old style [self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end
this one is out of left field but its a nice little map for resizing your current split to 80 characters if you've got the line numbers on:
" make window 80 + some for numbers wide
noremap <Leader>w :let @w=float2nr(log10(line("$")))+82\|:vertical resize <c-r>w<cr>
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
On Mac, use the command git credential-osxkeychain erase
.
OR remove manually from keychain from Applications ? Utilities ? Keychain Access. Then remove the github.com keychain. Then use push; it will ask for the keychain access; then deny.
It will ask for the new username and password, add it then pushes a file for that.
After git push
I found this error. Then I use the upper case-
issue:
remote: Permission to user1/file.git denied to user2(previously exist user ). fatal: unable to access 'https://github.com/xxxxxxxxxxxx/': The requested URL returned error: 403
There is also a combination, you can use a return value with a recordset:
--Stored Procedure--
CREATE PROCEDURE [TestProc]
AS
BEGIN
DECLARE @Temp TABLE
(
[Name] VARCHAR(50)
)
INSERT INTO @Temp VALUES ('Mark')
INSERT INTO @Temp VALUES ('John')
INSERT INTO @Temp VALUES ('Jane')
INSERT INTO @Temp VALUES ('Mary')
-- Get recordset
SELECT * FROM @Temp
DECLARE @ReturnValue INT
SELECT @ReturnValue = COUNT([Name]) FROM @Temp
-- Return count
RETURN @ReturnValue
END
--Calling Code--
DECLARE @SelectedValue int
EXEC @SelectedValue = [TestProc]
SELECT @SelectedValue
--Results--
Slightly modified from: Python Pandas Dataframe: Normalize data between 0.01 and 0.99? but from some of the comments thought it was relevant (sorry if considered a repost though...)
I wanted customized normalization in that regular percentile of datum or z-score was not adequate. Sometimes I knew what the feasible max and min of the population were, and therefore wanted to define it other than my sample, or a different midpoint, or whatever! This can often be useful for rescaling and normalizing data for neural nets where you may want all inputs between 0 and 1, but some of your data may need to be scaled in a more customized way... because percentiles and stdevs assumes your sample covers the population, but sometimes we know this isn't true. It was also very useful for me when visualizing data in heatmaps. So i built a custom function (used extra steps in the code here to make it as readable as possible):
def NormData(s,low='min',center='mid',hi='max',insideout=False,shrinkfactor=0.):
if low=='min':
low=min(s)
elif low=='abs':
low=max(abs(min(s)),abs(max(s)))*-1.#sign(min(s))
if hi=='max':
hi=max(s)
elif hi=='abs':
hi=max(abs(min(s)),abs(max(s)))*1.#sign(max(s))
if center=='mid':
center=(max(s)+min(s))/2
elif center=='avg':
center=mean(s)
elif center=='median':
center=median(s)
s2=[x-center for x in s]
hi=hi-center
low=low-center
center=0.
r=[]
for x in s2:
if x<low:
r.append(0.)
elif x>hi:
r.append(1.)
else:
if x>=center:
r.append((x-center)/(hi-center)*0.5+0.5)
else:
r.append((x-low)/(center-low)*0.5+0.)
if insideout==True:
ir=[(1.-abs(z-0.5)*2.) for z in r]
r=ir
rr =[x-(x-0.5)*shrinkfactor for x in r]
return rr
This will take in a pandas series, or even just a list and normalize it to your specified low, center, and high points. also there is a shrink factor! to allow you to scale down the data away from endpoints 0 and 1 (I had to do this when combining colormaps in matplotlib:Single pcolormesh with more than one colormap using Matplotlib) So you can likely see how the code works, but basically say you have values [-5,1,10] in a sample, but want to normalize based on a range of -7 to 7 (so anything above 7, our "10" is treated as a 7 effectively) with a midpoint of 2, but shrink it to fit a 256 RGB colormap:
#In[1]
NormData([-5,2,10],low=-7,center=1,hi=7,shrinkfactor=2./256)
#Out[1]
[0.1279296875, 0.5826822916666667, 0.99609375]
It can also turn your data inside out... this may seem odd, but I found it useful for heatmapping. Say you want a darker color for values closer to 0 rather than hi/low. You could heatmap based on normalized data where insideout=True:
#In[2]
NormData([-5,2,10],low=-7,center=1,hi=7,insideout=True,shrinkfactor=2./256)
#Out[2]
[0.251953125, 0.8307291666666666, 0.00390625]
So now "2" which is closest to the center, defined as "1" is the highest value.
Anyways, I thought my application was relevant if you're looking to rescale data in other ways that could have useful applications to you.
The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.
See also here: How to supply value to an annotation from a Constant java
It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.
Notice how in Macmade's solution, you can see an extra line of code above the "Code block".
Here are two better solutions:
Indent the code block by an extra 4 spaces (so usually 8, in this nested list example, 12). This will put the code in a <pre>
element. On SO, you can even specify syntax highlight with a
<!-- language: lang-js -->
indented by 4 spaces (+1 here due to the nested list).
item 2
Code.block('JavaScript', maybe)?
item 3
Or, just put the Code block within backticks and indent by 4 spaces (here, 1 extra because of the nested list). You'll get a regular indented text paragraph, with a <code>
element inside it. This one you can't syntax-highlight:
item 2
Code block
item 3
Note: you can click "edit" on this answer to see the underlying Markdown code. No need to save ;)
Security note: Disabling security checks is dangerous and should be avoided
You can disable security checks globally for all requests of the default client:
package main
import (
"fmt"
"net/http"
"crypto/tls"
)
func main() {
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
_, err := http.Get("https://golang.org/")
if err != nil {
fmt.Println(err)
}
}
You can disable security check for a client:
package main
import (
"fmt"
"net/http"
"crypto/tls"
)
func main() {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
_, err := client.Get("https://golang.org/")
if err != nil {
fmt.Println(err)
}
}
Use Google AJAX Feed API unless your RSS data is private. It's fast, of course.
The Python time.strftime
docs say:
When used with the strptime() function, the
%p
directive only affects the output hour field if the%I
directive is used to parse the hour.
Sure enough, changing your %H
to %I
makes it work.
var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);
Caliburn micro flavoured
public class CloseAppResult : CancelResult
{
public override void Execute(CoroutineExecutionContext context)
{
Application.Current.Shutdown();
base.Execute(context);
}
}
public class CancelResult : Result
{
public override void Execute(CoroutineExecutionContext context)
{
OnCompleted(this, new ResultCompletionEventArgs { WasCancelled = true });
}
}
I find that using Apache Commons IO makes my life much easier.
String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");
You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.
So if you go to
-> Setting -> Project:My_project -> Project Structure,
Just the directory in which the source code is available and mark it as "Sources" (You can see it on the same window). The directory with source code should turn blue. Now u can import in modules residing in same directory.
Just to expand on my answer a neater way of doing this multiple times would probably be:
PopulateByteArray(UserCode, 0x20);
which calls:
public static void PopulateByteArray(byte[] byteArray, byte value)
{
for (int i = 0; i < byteArray.Length; i++)
{
byteArray[i] = value;
}
}
This has the advantage of a nice efficient for loop (mention to gwiazdorrr's answer) as well as a nice neat looking call if it is being used a lot. And a lot mroe at a glance readable than the enumeration one I personally think. :)
convert it into python datetime object if it isn't already. then add deltatime
one_years_later = Your_date + datetime.timedelta(days=(years*days_per_year))
for your case days=365.
you can have condition to check if the year is leap or no and adjust days accordingly
you can add as many years as you want
I have done this in the past, and have always used this:
With Me.RecordsetClone
.MoveFirst
Do Until .EOF
If Me.Dirty Then
Me.Dirty = False
End If
.MoveNext
Me.Bookmark = .Bookmark
Loop
End With
Some people would use the form's Recordset, which doesn't require setting the bookmark (i.e., navigating the form's Recordset navigates the form's edit buffer automatically, so the user sees the move immediately), but I prefer the indirection of the RecordsetClone.
if you have numbers in list, you can use map
to apply str
to each element:
print ', '.join(map(str, LIST))
^ map
is C code so it's faster than str(i) for i in LIST
I'm answering because I don't see this particular solution listed by anyone else.
Apparently my antivirus (Ad-Aware) was flagging a DLL one of my projects depends on, and deleting it. Even after excluding the directory where the DLL lives, the same behaviour continued until I restarted my computer.
SEARCH
does not return 0
if there is no match, it returns #VALUE!
. So you have to wrap calls to SEARCH
with IFERROR
.
For example...
=IF(IFERROR(SEARCH("cat", A1), 0), "cat", "none")
or
=IF(IFERROR(SEARCH("cat",A1),0),"cat",IF(IFERROR(SEARCH("22",A1),0),"22","none"))
Here, IFERROR
returns the value from SEARCH
when it works; the given value of 0
otherwise.
you can use a workaround, like this:
<input type='date' (keyup)="0" #myDate [(ngModel)]='demoUser.date'/><br>
on your component :
@Input public date: Date,
The best practice for checking the react native environment information.
react-native info
which will give the information
React Native Environment Info:
System:
OS: Linux 4.15 Ubuntu 18.04.1 LTS (Bionic Beaver)
CPU: (8) x64 Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz
Memory: 2.08 GB / 7.67 GB
Shell: 4.4.19 - /bin/bash
Binaries:
Node: 8.10.0 - /usr/bin/node
Yarn: 1.12.3 - /usr/bin/yarn
npm: 3.5.2 - /usr/bin/npm
npmPackages:
react: 16.4.1 => 16.4.1
react-native: 0.56.0 => 0.56.0
npmGlobalPackages:
react-native-cli: 2.0.1
react-native: 0.57.8
Know the master key yourself. Don't hard code it.
Use py-bcrypt
(bcrypt), powerful hashing technique to generate a password yourself.
Basically you can do this (an idea...)
import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)
save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.
This is basically how login should work these days.
import pandas as pd
from openpyxl import load_workbook
def write_to_excel(df, file):
try:
book = load_workbook(file)
writer = pd.ExcelWriter(file, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df.to_excel(writer, **kwds)
writer.save()
except FileNotFoundError as e:
df.to_excel(file, **kwds)
df_a = pd.DataFrame(range(10), columns=["a"])
df_b = pd.DataFrame(range(10, 20), columns=["b"])
write_to_excel(df_a, "test.xlsx", sheet_name="Sheet a", columns=['a'], index=False)
write_to_excel(df_b, "test.xlsx", sheet_name="Sheet b", columns=['b'])
something like:
p
{
display:inline;
}
in your stylesheet would do it for all p tags.
You can't pass a function as a parameter. Simply remove it from estimatedPopulation() and replace it with 'float growthRate'. use this in your calculation instead of calling the function:
int estimatedPopulation (int currentPopulation, float growthRate)
{
return (currentPopulation + currentPopulation * growthRate / 100);
}
and call it as:
int foo = estimatedPopulation (currentPopulation, growthRate (birthRate, deathRate));
Use the following attribute:
cls.__bases__
From the docs:
The tuple of base classes of a class object.
Example:
>>> str.__bases__
(<type 'basestring'>,)
Another example:
>>> class A(object):
... pass
...
>>> class B(object):
... pass
...
>>> class C(A, B):
... pass
...
>>> C.__bases__
(<class '__main__.A'>, <class '__main__.B'>)
Check if you have
User Instance=true
in connection string. Try removing it which will resolve your problem.
Unlike C++, Java does not support user defined operator overloading. The overloading is done internally in java.
We can take +
(plus) for example:
int a = 2 + 4;
string = "hello" + "world";
Here, plus adds two integer numbers and concatenates two strings. So we can say that Java supports internal operator overloading but not user defined.
Another good GUI designer for Eclipse is Window Builder Pro. Like Jigloo, it's not free for commercial use.
It allows you to design user interfaces for Swing, SWT and even the Google Web Toolkit (GWT).
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
I had the same problem but I use -w 0
option to send only one packet and quit.
You should use this command :
echo -n "hello" | nc -4u -w0 localhost 8000
$('#foo > div').size()
It is disappointing that many databases do not stick to the standard rules and add extra characters, or incorrectly enable ESCAPE with a default value of ‘\’ when it is missing. Like we don't already have enough trouble with ‘\’!
It's impossible to write DBMS-independent code here, because you don't know what characters you're going to have to escape, and the standard says you can't escape things that don't need to be escaped. (See section 8.5/General Rules/3.a.ii.)
Thank you SQL! gnnn
in visualstudio 2008 you could use this code :
var _assembly = System.Reflection.Assembly
.GetExecutingAssembly().GetName().CodeBase;
var _path = System.IO.Path.GetDirectoryName(_assembly) ;
I did a quick test in both node and chrome and found in both cases +=
is faster:
var profile = func => {
var start = new Date();
for (var i = 0; i < 10000000; i++) func('test');
console.log(new Date() - start);
}
profile(x => "testtesttesttesttest");
profile(x => `${x}${x}${x}${x}${x}`);
profile(x => x + x + x + x + x );
profile(x => { var s = x; s += x; s += x; s += x; s += x; return s; });
profile(x => [x, x, x, x, x].join(""));
profile(x => { var a = [x]; a.push(x); a.push(x); a.push(x); a.push(x); return a.join(""); });
results in node: 7.0.10
results from chrome 86.0.4240.198:
The simplest way to log out and redirect back to the login or index:
<?php
if (!isset($_SESSION)) { session_start(); }
$_SESSION = array();
session_destroy();
header("Location: login.php"); // Or wherever you want to redirect
exit();
?>
ivBall.setOnClickListener(View.OnClickListener {
//Animate using XML
// val rotateAnimation = AnimationUtils.loadAnimation(activity, R.anim.rotate_indefinitely)
//OR using Code
val rotateAnimation = RotateAnimation(
0f, 359f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f
)
rotateAnimation.duration = 300
rotateAnimation.repeatCount = 2
//Either way you can add Listener like this
rotateAnimation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) {
}
override fun onAnimationRepeat(animation: Animation?) {
}
override fun onAnimationEnd(animation: Animation?) {
val rand = Random()
val ballHit = rand.nextInt(50) + 1
Toast.makeText(context, "ballHit : " + ballHit, Toast.LENGTH_SHORT).show()
}
})
ivBall.startAnimation(rotateAnimation)
})
Simple code that you can write in main(String[] args) function
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//application will be closed when you close frame
frame.setSize(800,600);
frame.setLocation(200,200);
JFileChooser fc = new JFileChooser();
if(fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION){
BufferedImage img = ImageIO.read(fc.getSelectedFile());//it must be an image file, otherwise you'll get an exception
JLabel label = new JLabel();
label.setIcon(new ImageIcon(img));
frame.getContentPane().add(label);
}
frame.setVisible(true);//showing up the frame
You can use other characters besides "/" in substitution:
sed "s#$1#$2#g" -i FILE
Empty returns true if the var is not set. But isset returns true even if the var is not empty.
Is not necesary to create the function only the @result part. For example:
Select Name,
(SELECT CASE WHEN
DATEPART(DAY, '2016-08-28') > DATEPART(DAY, '2016-09-29')
THEN DATEDIFF(MONTH, '2016-08-28', '2016-09-29') - 1
ELSE DATEDIFF(MONTH, '2016-08-28', '2016-09-29') END) as NumberOfMonths
FROM
tableExample;
None of these solutions worked for me inside a Weebly "add your own html" box. Not sure what they are doing with their code. But I found this solution at https://benmarshall.me/responsive-iframes/ and it works perfectly.
CSS
.iframe-container {
overflow: hidden;
padding-top: 56.25%;
position: relative;
}
.iframe-container iframe {
border: 0;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}
/* 4x3 Aspect Ratio */
.iframe-container-4x3 {
padding-top: 75%;
}
HTML
<div class="iframe-container">
<iframe src="https://player.vimeo.com/video/106466360" allowfullscreen></iframe>
</div>
I had a similar issue, I was sending a POST request (using RESTClient plugin for Firefox) with data in the request body and was receiving the same message.
In my case this happened because I was trying to use HTTPS protocol in a local tomcat instance where HTTPS was not configured.
Go to Windows->Preferences->Validation.
There would be a list of validators with checkbox options for Manual & Build, go and individually disable the javascript validator there.
If you select the Suspend All Validators checkbox on the top it doesn't necessarily take affect.
You can use $.ajax call to get the value and then put it in the div you want to. One thing you must know is you cannot receive JSON Data. You have to use JSONP.
Code would be like this:
function CallURL() {
$.ajax({
url: 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan',
type: "GET",
dataType: "jsonp",
async: false,
success: function(msg) {
JsonpCallback(msg);
},
error: function() {
ErrorFunction();
}
});
}
function JsonpCallback(json) {
document.getElementById('summary').innerHTML = json.result;
}
There's no operator for such usage in C, but a family of functions:
double pow (double base , double exponent);
float powf (float base , float exponent);
long double powl (long double base, long double exponent);
Note that the later two are only part of standard C since C99.
If you get a warning like:
"incompatible implicit declaration of built in function 'pow' "
That's because you forgot #include <math.h>
.
This one works for me:
grep <stuff> -R --exclude-dir=<your_dir>
For IntelliJ IDEA 2019.3.4 (Ultimate Edition), the following worked for me:
select * from table where
(dtColumn between #3/1/2009# and #3/31/2009#) and
(hour(dtColumn) between 6 and 22) and
(weekday(dtColumn, 1) between 2 and 4)
Basically, you want to loop through each direct descendent of the old-parent node, and move it to the new parent. Any children of a direct descendent will get moved with it.
var newParent = document.getElementById('new-parent');
var oldParent = document.getElementById('old-parent');
while (oldParent.childNodes.length > 0) {
newParent.appendChild(oldParent.childNodes[0]);
}
With the java.time classes built into Java 8 and later:
public static void main(String[] args) {
LocalDateTime localNow = LocalDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
System.out.println(localNow);
// Prints current time of given zone without zone information : 2016-04-28T15:41:17.611
ZonedDateTime zoneNow = ZonedDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
System.out.println(zoneNow);
// Prints current time of given zone with zone information : 2016-04-28T15:41:17.627+02:00[Europe/Madrid]
}
Another way to dump data as file from table by DumpDataFromTable sproc
EXEC dbo.DumpDataFromTable
@SchemaName = 'dbo'
,@TableName = 'YourTableName'
,@PathOut = N'c:\tmp\scripts\' -- folder must exist !!!'
Note: SQL must have permission to create files, if is not set-up then exec follow line once
EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
By this script you can call the sproc: DumpDataFromTable.sql and dump more tables in one go, instead of doing manually one by one from Management Studio
By default the format of generated scrip will be like
INSERT INTO <TableName> SELECT <Values>
Or you can change the generated format into
SELECT ... FROM
by setting variable @BuildMethod = 2
full sproc code:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DumpDataFromTable]') AND type in (N'P', N'PC'))
DROP PROCEDURE dbo.[DumpDataFromTable]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Oleg Ciobanu
-- Create date: 20171214
-- Version 1.02
-- Description:
-- dump data in 2 formats
-- @BuildMethod = 1 INSERT INTO format
-- @BuildMethod = 2 SELECT * FROM format
--
-- SQL must have permission to create files, if is not set-up then exec follow line once
-- EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
--
-- =============================================
CREATE PROCEDURE [dbo].[DumpDataFromTable]
(
@SchemaName nvarchar(128) --= 'dbo'
,@TableName nvarchar(128) --= 'testTable'
,@WhereClause nvarchar (1000) = '' -- must start with AND
,@BuildMethod int = 1 -- taking values 1 for INSERT INTO forrmat or 2 for SELECT from value Table
,@PathOut nvarchar(250) = N'c:\tmp\scripts\' -- folder must exist !!!'
,@AsFileNAme nvarchar(250) = NULL -- if is passed then will use this value as FileName
,@DebugMode int = 0
)
AS
BEGIN
SET NOCOUNT ON;
-- run follow next line if you get permission deny for sp_OACreate,sp_OAMethod
-- EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
DECLARE @Sql nvarchar (max)
DECLARE @SqlInsert nvarchar (max) = ''
DECLARE @Columns nvarchar(max)
DECLARE @ColumnsCast nvarchar(max)
-- cleanUp/prepraring data
SET @SchemaName = REPLACE(REPLACE(@SchemaName,'[',''),']','')
SET @TableName = REPLACE(REPLACE(@TableName,'[',''),']','')
SET @AsFileNAme = NULLIF(@AsFileNAme,'')
SET @AsFileNAme = REPLACE(@AsFileNAme,'.','_')
SET @AsFileNAme = COALESCE(@PathOut + @AsFileNAme + '.sql', @PathOut + @SchemaName + ISNULL('_' + @TableName,N'') + '.sql')
--debug
IF @DebugMode = 1
PRINT @AsFileNAme
-- Create temp SP what will be responsable for generating script files
DECLARE @PRC_WritereadFile VARCHAR(max) =
'IF EXISTS (SELECT * FROM sys.objects WHERE type = ''P'' AND name = ''PRC_WritereadFile'')
BEGIN
DROP Procedure PRC_WritereadFile
END;'
EXEC (@PRC_WritereadFile)
-- '
SET @PRC_WritereadFile =
'CREATE Procedure PRC_WritereadFile (
@FileMode INT -- Recreate = 0 or Append Mode 1
,@Path NVARCHAR(1000)
,@AsFileNAme NVARCHAR(500)
,@FileBody NVARCHAR(MAX)
)
AS
DECLARE @OLEResult INT
DECLARE @FS INT
DECLARE @FileID INT
DECLARE @hr INT
DECLARE @FullFileName NVARCHAR(1500) = @Path + @AsFileNAme
-- Create Object
EXECUTE @OLEResult = sp_OACreate ''Scripting.FileSystemObject'', @FS OUTPUT
IF @OLEResult <> 0 BEGIN
PRINT ''Scripting.FileSystemObject''
GOTO Error_Handler
END
IF @FileMode = 0 BEGIN -- Create
EXECUTE @OLEResult = sp_OAMethod @FS,''CreateTextFile'',@FileID OUTPUT, @FullFileName
IF @OLEResult <> 0 BEGIN
PRINT ''CreateTextFile''
GOTO Error_Handler
END
END ELSE BEGIN -- Append
EXECUTE @OLEResult = sp_OAMethod @FS,''OpenTextFile'',@FileID OUTPUT, @FullFileName, 8, 0 -- 8- forappending
IF @OLEResult <> 0 BEGIN
PRINT ''OpenTextFile''
GOTO Error_Handler
END
END
EXECUTE @OLEResult = sp_OAMethod @FileID, ''WriteLine'', NULL, @FileBody
IF @OLEResult <> 0 BEGIN
PRINT ''WriteLine''
GOTO Error_Handler
END
EXECUTE @OLEResult = sp_OAMethod @FileID,''Close''
IF @OLEResult <> 0 BEGIN
PRINT ''Close''
GOTO Error_Handler
END
EXECUTE sp_OADestroy @FS
EXECUTE sp_OADestroy @FileID
GOTO Done
Error_Handler:
DECLARE @source varchar(30), @desc varchar (200)
EXEC @hr = sp_OAGetErrorInfo null, @source OUT, @desc OUT
PRINT ''*** ERROR ***''
SELECT OLEResult = @OLEResult, hr = CONVERT (binary(4), @hr), source = @source, description = @desc
Done:
';
-- '
EXEC (@PRC_WritereadFile)
EXEC PRC_WritereadFile 0 /*Create*/, '', @AsFileNAme, ''
;WITH steColumns AS (
SELECT
1 as rn,
c.ORDINAL_POSITION
,c.COLUMN_NAME as ColumnName
,c.DATA_TYPE as ColumnType
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE 1 = 1
AND c.TABLE_SCHEMA = @SchemaName
AND c.TABLE_NAME = @TableName
)
--SELECT *
SELECT
@ColumnsCast = ( SELECT
CASE WHEN ColumnType IN ('date','time','datetime2','datetimeoffset','smalldatetime','datetime','timestamp')
THEN
'convert(nvarchar(1001), s.[' + ColumnName + ']' + ' , 121) AS [' + ColumnName + '],'
--,convert(nvarchar, [DateTimeScriptApplied], 121) as [DateTimeScriptApplied]
ELSE
'CAST(s.[' + ColumnName + ']' + ' AS NVARCHAR(1001)) AS [' + ColumnName + '],'
END
as 'data()'
FROM
steColumns t2
WHERE 1 =1
AND t1.rn = t2.rn
FOR xml PATH('')
)
,@Columns = ( SELECT
'[' + ColumnName + '],' as 'data()'
FROM
steColumns t2
WHERE 1 =1
AND t1.rn = t2.rn
FOR xml PATH('')
)
FROM steColumns t1
-- remove last char
IF lEN(@Columns) > 0 BEGIN
SET @Columns = SUBSTRING(@Columns, 1, LEN(@Columns)-1);
SET @ColumnsCast = SUBSTRING(@ColumnsCast, 1, LEN(@ColumnsCast)-1);
END
-- debug
IF @DebugMode = 1 BEGIN
print @ColumnsCast
print @Columns
select @ColumnsCast , @Columns
END
-- build unpivoted Data
SET @SQL = '
SELECT
u.rn
, c.ORDINAL_POSITION as ColumnPosition
, c.DATA_TYPE as ColumnType
, u.ColumnName
, u.ColumnValue
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn,
'
+ CHAR(13) + @ColumnsCast
+ CHAR(13) + 'FROM [' + @SchemaName + '].[' + @TableName + '] s'
+ CHAR(13) + 'WHERE 1 = 1'
+ CHAR(13) + COALESCE(@WhereClause,'')
+ CHAR(13) + ') tt
UNPIVOT
(
ColumnValue
FOR ColumnName in (
' + CHAR(13) + @Columns
+ CHAR(13)
+ '
)
) u
LEFT JOIN INFORMATION_SCHEMA.COLUMNS c ON c.COLUMN_NAME = u.ColumnName
AND c.TABLE_SCHEMA = '''+ @SchemaName + '''
AND c.TABLE_NAME = ''' + @TableName +'''
ORDER BY u.rn
, c.ORDINAL_POSITION
'
-- debug
IF @DebugMode = 1 BEGIN
print @Sql
exec (@Sql)
END
-- prepare data for cursor
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
DROP TABLE #tmp
CREATE TABLE #tmp
(
rn bigint
,ColumnPosition int
,ColumnType varchar (128)
,ColumnName varchar (128)
,ColumnValue nvarchar (2000) -- I hope this size will be enough for storring values
)
SET @Sql = 'INSERT INTO #tmp ' + CHAR(13) + @Sql
-- debug
IF @DebugMode = 1 BEGIN
print @Sql
END
EXEC (@Sql)
-- Insert dummy rec, otherwise will not proceed the last rec :)
INSERT INTO #tmp (rn)
SELECT MAX(rn) + 1
FROM #tmp
IF @DebugMode = 1 BEGIN
SELECT * FROM #tmp
END
DECLARE @rn bigint
,@ColumnPosition int
,@ColumnType varchar (128)
,@ColumnName varchar (128)
,@ColumnValue nvarchar (2000)
,@i int = -1 -- counter/flag
,@ColumnsInsert varchar(max) = NULL
,@ValuesInsert nvarchar(max) = NULL
DECLARE cur CURSOR FOR
SELECT rn, ColumnPosition, ColumnType, ColumnName, ColumnValue
FROM #tmp
ORDER BY rn, ColumnPosition -- note order is really important !!!
OPEN cur
FETCH NEXT FROM cur
INTO @rn, @ColumnPosition, @ColumnType, @ColumnName, @ColumnValue
IF @BuildMethod = 1
BEGIN
SET @SqlInsert = 'SET NOCOUNT ON;' + CHAR(13);
EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileName, @SqlInsert
SET @SqlInsert = ''
END
ELSE BEGIN
SET @SqlInsert = 'SET NOCOUNT ON;' + CHAR(13);
SET @SqlInsert = @SqlInsert
+ 'SELECT *'
+ CHAR(13) + 'FROM ('
+ CHAR(13) + 'VALUES'
EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileName, @SqlInsert
SET @SqlInsert = NULL
END
SET @i = @rn
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@i <> @rn) -- is a new row
BEGIN
IF @BuildMethod = 1
-- build as INSERT INTO -- as Default
BEGIN
SET @SqlInsert = 'INSERT INTO [' + @SchemaName + '].[' + @TableName + '] ('
+ CHAR(13) + @ColumnsInsert + ')'
+ CHAR(13) + 'VALUES ('
+ @ValuesInsert
+ CHAR(13) + ');'
END
ELSE
BEGIN
-- build as Table select
IF (@i <> @rn) -- is a new row
BEGIN
SET @SqlInsert = COALESCE(@SqlInsert + ',','') + '(' + @ValuesInsert+ ')'
EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
SET @SqlInsert = '' -- in method 2 we should clear script
END
END
-- debug
IF @DebugMode = 1
print @SqlInsert
EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
-- we have new row
-- initialise variables
SET @i = @rn
SET @ColumnsInsert = NULL
SET @ValuesInsert = NULL
END
-- build insert values
IF (@i = @rn) -- is same row
BEGIN
SET @ColumnsInsert = COALESCE(@ColumnsInsert + ',','') + '[' + @ColumnName + ']'
SET @ValuesInsert = CASE
-- date
--WHEN
-- @ColumnType IN ('date','time','datetime2','datetimeoffset','smalldatetime','datetime','timestamp')
--THEN
-- COALESCE(@ValuesInsert + ',','') + '''''' + ISNULL(RTRIM(@ColumnValue),'NULL') + ''''''
-- numeric
WHEN
@ColumnType IN ('bit','tinyint','smallint','int','bigint'
,'money','real','','float','decimal','numeric','smallmoney')
THEN
COALESCE(@ValuesInsert + ',','') + '' + ISNULL(RTRIM(@ColumnValue),'NULL') + ''
-- other types treat as string
ELSE
COALESCE(@ValuesInsert + ',','') + '''' + ISNULL(RTRIM(
-- escape single quote
REPLACE(@ColumnValue, '''', '''''')
),'NULL') + ''''
END
END
FETCH NEXT FROM cur
INTO @rn, @ColumnPosition, @ColumnType, @ColumnName, @ColumnValue
-- debug
IF @DebugMode = 1
BEGIN
print CAST(@rn AS VARCHAR) + '-' + CAST(@ColumnPosition AS VARCHAR)
END
END
CLOSE cur
DEALLOCATE cur
IF @BuildMethod = 1
BEGIN
PRINT 'ignore'
END
ELSE BEGIN
SET @SqlInsert = CHAR(13) + ') AS vtable '
+ CHAR(13) + ' (' + @Columns
+ CHAR(13) + ')'
EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
SET @SqlInsert = NULL
END
PRINT 'Done: ' + @AsFileNAme
END
Or can be downloaded latest version from https://github.com/Zindur/MSSQL-DumpTable/tree/master/Scripts
Here's what I get.
I'm using Visual Studio Code and its Terminal to execute the 'npm' commands.
Visual Studio Code (not as administrator)
PS g:\labs\myproject> npm install bootstrap@3
Results in scandir and/or permission errors.
Visual Studio Code (as Administrator)
Run this command after I've run something like 'ng serve'
PS g:\labs\myproject> npm install bootstrap@3
Results in scandir and/or permission errors.
Visual Studio Code (as Administrator - closing and opening the IDE)
If I have already executed other commands that would impact node modules I decided to try closing Visual Studio Code first, opening it up as Administrator then running the command:
PS g:\labs\myproject> npm install bootstrap@3
Result I get then is: + [email protected]
added 115 packages and updated 1 package in 24.685s
This is not a permanent solution since I don't want to continue closing down VS Code every time I want to execute an npm command, but it did resolve the issue to a point.
Just an idea:
You may get the filesize by running command "dir":
>dir thing
Then again it returns so many things.
Maybe you can get it from there if you look for it.
But I am not sure.
I was facing the same issue; and the following worked well for me. Hope this helps someone landing here:
<div class="row">
<div class="col-md-6">
<div class="col-md-12">
Set room heater temperature
</div>
</div>
<div class="col-md-6">
<div class="col-md-12">
Set room heater temperature
</div>
</div>
</div>
This will automatically render some space between the 2 divs.
If a programmer is interested in only parsing a table from a webpage, they can utilize the pandas method pandas.read_html
.
Let's say we want to extract the GDP data table from the website: https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries
Then following codes does the job perfectly (No need of beautifulsoup and fancy html):
import pandas as pd
import requests
url = "https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries"
r = requests.get(url)
df_list = pd.read_html(r.text) # this parses all the tables in webpages to a list
df = df_list[0]
df.head()
If you're looking for a Windows GUI, check out DigiCert. I just used this and it was fairly simple.
Under the SSL tab, I first Imported the Certificate. Then once I selected the Certificate I was able to export as a PFX, both with and without a keyfile.
Use:
function getdatabetween($string, $start, $end){
$sp = strpos($string, $start)+strlen($start);
$ep = strpos($string, $end)-strlen($start);
$data = trim(substr($string, $sp, $ep));
return trim($data);
}
$dt = "Find string between two strings in PHP";
echo getdatabetween($dt, 'Find', 'in PHP');
I use SimpleDateFormat without custom pattern to get actual date and time from the system in the device's preselected format:
public static String getFormattedDate() {
//SimpleDateFormat called without pattern
return new SimpleDateFormat().format(Calendar.getInstance().getTime());
}
returns:
Javascript strings have a length
property that will tell you the length of the string.
Then all you have to do is use the substr()
function to get the last character:
var myString = "Test3";
var lastChar = myString.substr(myString.length -1);
edit: yes, or use the array notation as the other posts before me have done.
If you want to keep your bashrc simple, you can remove all the conda init
generated clutter, and keep only a single line:
. "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
See Recommended change to enable conda in your shell.
This will make the conda command available without activating the base environment.
If you want to use your bashrc on other systems where conda is not installed in the same path, you can keep the if
/fi
lines as well to avoid error messages, i.e.:
if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
. "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
fi
Then just Select
:
var list = source.Select(s=>new { ID = s.ID, Name = s.Name }).ToList();
(edit) Actually - the names could be inferred in this case, so you could use:
var list = source.Select(s=>new { s.ID, s.Name }).ToList();
which saves a few electrons...
As I don't like using putty in Windows as a workaround, I created a very simple utility ssh-agent-wrapper. It scans your .ssh folders and adds all your keys to the agent. You simply need to put it into Windows startup folder for it to work.
Assumptions:
I do not agree and do not recommend to return a vector
:
vector <double> vectorial(vector <double> a, vector <double> b)
{
vector <double> c{ a[1] * b[2] - b[1] * a[2], -a[0] * b[2] + b[0] * a[2], a[0] * b[1] - b[0] * a[1] };
return c;
}
This is much faster:
void vectorial(vector <double> a, vector <double> b, vector <double> &c)
{
c[0] = a[1] * b[2] - b[1] * a[2]; c[1] = -a[0] * b[2] + b[0] * a[2]; c[2] = a[0] * b[1] - b[0] * a[1];
}
I tested on Visual Studio 2017 with the following results in release mode:
8.01 MOPs by reference
5.09 MOPs returning vector
In debug mode, things are much worse:
0.053 MOPS by reference
0.034 MOPs by return vector
UPDATE dummy SET myfield=1 WHERE id>1;
Note that when you insert into a List at a position, you are really inserting at a dynamic position within the List's current elements. See here:
package com.tutorialspoint;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
// use add() method to add elements in the list
arrlist.add(15, 15);
arrlist.add(22, 22);
arrlist.add(30, 30);
arrlist.add(40, 40);
// adding element 25 at third position
arrlist.add(2, 25);
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
}
}
$javac com/tutorialspoint/ArrayListDemo.java
$java -Xmx128M -Xms16M com/tutorialspoint/ArrayListDemo
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 0 at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661) at java.util.ArrayList.add(ArrayList.java:473) at com.tutorialspoint.ArrayListDemo.main(ArrayListDemo.java:12)
My approach. Tricky, but works well for me
<p> </p>
Typing the following in the terminal will erase your history (meaning using up arrow will get you nothing), but it will not clear the screen:
history -c
Linq to Sql.
Sql server will cache the query plans, so there's no performance gain for sprocs.
Your linq statements, on the other hand, will be logically part of and tested with your application. Sprocs are always a bit separated and are harder to maintain and test.
If I was working on a new application from scratch right now I would just use Linq, no sprocs.
The MyKey class (@Embeddable) should not have any relationships like @ManyToOne
To force a reload of the php.ini you should restart apache.
Try sudo service apache2 restart
from the command line.
Or sudo /etc/init.d/apache2 restart
Another way, inspired from previous posts to make an extension.
We can put the image on the right or on the left
extension UITextField {
enum Direction {
case Left
case Right
}
// add image to textfield
func withImage(direction: Direction, image: UIImage, colorSeparator: UIColor, colorBorder: UIColor){
let mainView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 45))
mainView.layer.cornerRadius = 5
let view = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 45))
view.backgroundColor = .white
view.clipsToBounds = true
view.layer.cornerRadius = 5
view.layer.borderWidth = CGFloat(0.5)
view.layer.borderColor = colorBorder.cgColor
mainView.addSubview(view)
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFit
imageView.frame = CGRect(x: 12.0, y: 10.0, width: 24.0, height: 24.0)
view.addSubview(imageView)
let seperatorView = UIView()
seperatorView.backgroundColor = colorSeparator
mainView.addSubview(seperatorView)
if(Direction.Left == direction){ // image left
seperatorView.frame = CGRect(x: 45, y: 0, width: 5, height: 45)
self.leftViewMode = .always
self.leftView = mainView
} else { // image right
seperatorView.frame = CGRect(x: 0, y: 0, width: 5, height: 45)
self.rightViewMode = .always
self.rightView = mainView
}
self.layer.borderColor = colorBorder.cgColor
self.layer.borderWidth = CGFloat(0.5)
self.layer.cornerRadius = 5
}
}
Use :
if let myImage = UIImage(named: "my_image"){
textfield.withImage(direction: .Left, image: myImage, colorSeparator: UIColor.orange, colorBorder: UIColor.black)
}
Enjoy :)
Try the following code:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowIsTranslucent">true</item>
</style>
This code works for me and will work on all Android devices.
What operating system are you using? I use Linux Mint. In my case it turned out to be a symbolic link issue. Every time I tried to create the project with the symlink path, it would give me that error. Creating the project elsewhere, and then migrating it to the symlinked directory solved it for me.
Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.
As example you could create your own bundle:
bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
"~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
"~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
"~/Resources/Core/Javascripts/jquery.validate.min.js",
"~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
"~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
"~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))
And render it like this:
@Scripts.Render("~/bundles/mybundle")
One more advantage of @Scripts.Render("~/bundles/mybundle")
over the native <script src="~/bundles/mybundle" />
is that @Scripts.Render()
will respect the web.config
debug setting:
<system.web>
<compilation debug="true|false" />
If debug="true"
then it will instead render individual script tags for each source script, without any minification.
For stylesheets you will have to use a StyleBundle and @Styles.Render().
Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.
In my case, android studio selectively doesnt recognize my device for projects with COMPILE AND TARGET SDKVERSION 29 under the app level build.gradle.
I fixed this either by downloading 'sources for android 29' which comes up after clicking the 'show package details' under the sdk manager tab or by reducing the compile and targetsdkversions to 28
I needed to keep the placeholder alignment so adam's answer was not enough for me.
To solve this I used a small variation that I hope will help some of you too:
- (void) drawPlaceholderInRect:(CGRect)rect {
//search field placeholder color
UIColor* color = [UIColor whiteColor];
[color setFill];
[self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
}
In Visual Studio 2019 you can find cl.exe inside
32-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx86\x86
64-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx64\x64
Before trying to compile either run vcvars32 for 32-Bit compilation or vcvars64 for 64-Bit.
32-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars32.bat"
64-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"
If you can't find the file or the directory, try going to C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC
and see if you can find a folder with a version number. If you can't, then you probably haven't installed C++ through the Visual Studio Installation yet.
There are 2 errors is this code:
1) You should remove this line, as it will reqrite x to an empty list:
x = []
2) In the first "if" statement, you should indent the "letter += 1" statement, like:
if x[i].isalpha():
letters += 1
TLDR; range is an arithmetic series so it can very easily calculate whether the object is there.It could even get the index of it if it were list like really quickly.
A very simple solution is to use html5 validation:
<form>
<input type="email" required pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}">
<input type="submit">
</form>
you should use
select FLOOR(DATEDIFF(CURDATE(),DATE(DOB))/365.25) from table_name;
here CURDATE() uses current date you can give own date in 'yyyy-mm-dd' format
DATE(DOB) extract yyyy-mm-dd year from your column which is in DATETIME format
here DOB is your column name (but you should alter table to modify the data type to be DATETIME in your case which is nvarchar)
Note-
this query is used in mysql
this return age in whole year
Checkboxes (radio buttons and <select>
) are OS-level components, not browser-level. You cannot reliably style them in a manner that will be consistent across browsers and operating systems.
Your best bet it to put an overlay on top and style that instead.
You can pass a variable on the line with the cmake invocation:
FOO=1 cmake
or by exporting a variable in BASH:
export FOO=1
Then you can pick it up in a cmake script using:
$ENV{FOO}
It really depends on what functions you're using to plot the lines, but try see if the on you're using takes an alpha value and set it to something like 0.5. If that doesn't work, try get the line objects and set their alpha values directly.
You should do mkdir build
and cd build
while inside opencv
folder, not the opencv-contrib
folder. The CMakeLists.txt
is there.
I need to produce both a logical model and a conceptual model. All the explanations here are really vague. The link posted above just shows the difference being that a conceptual model is a logical model without fields. Ok fine, I don't mention the name of the database. It appears to be totally redundant.
I really don't know what 'semantic' means. can someone explain what I would do differently using 'english' and possibly post a link to better examples than a picture that shows one picture that has fields and one that does not. The buzzwords are all well and good, but its so vague its not useful to practically implement.
do I do anything other than take my logical model (which is basically my physical model reversed engineered out of the DB, click a button in said tools and the images look a little different and then take off the data types).
From what i can practically see (and without buzzwords)
physical model: actually tables. The little pictures have data types in them and named pk/fk constraints Logical Model: click the little button my tool (using Oracles SQL Developer Data Modeller, I dont have an erwin license and 2010 visio no longer reverse engineers out of the DB), and then the images on the screen change slightly. The data types are gone and the names of the constraints are gone, then the colors of the table representations changes to purple (so now I call them entities).
ok. so what would my Conceptual model look like other then: exact same thing as my logical model minus the fields. I would think there is more to it than this. Reciting that its a 'semantic' representation of data sounds real nice and fancy, but doesn't make sense to someone who has not made one of these before.
Microsoft SQL Server Integration Services (SSIS) is a platform for building high-performance data integration solutions, including extraction, transformation, and load (ETL) packages for data warehousing. SSIS includes graphical tools and wizards for building and debugging packages; tasks for performing workflow functions such as FTP operations, executing SQL statements, and sending e-mail messages; data sources and destinations for extracting and loading data; transformations for cleaning, aggregating, merging, and copying data; a management database, SSISDB, for administering package execution and storage; and application programming interfaces (APIs) for programming the Integration Services object model.
As per Microsoft, the main uses of SSIS Package are:
• Merging Data from Heterogeneous Data Stores Populating Data
• Warehouses and Data Marts Cleaning and Standardizing Data Building
• Business Intelligence into a Data Transformation Process Automating
• Administrative Functions and Data Loading
For developers:
SSIS Package can be integrated with VS development environment for building Business Intelligence solutions. Business Intelligence Development Studio is the Visual Studio environment with enhancements that are specific to business intelligence solutions. It work with 32-bit development environment only.
Download SSDT tools for Visual Studio:
http://www.microsoft.com/en-us/download/details.aspx?id=36843
Creating SSIS ETL Package - Basics :
Sample project of SSIS features in 6 lessons:
It sets result
to the (unsigned) value resulting from putting the 8 bits of value
in the lowest 8 bits of result
.
The reason something like this is necessary is that byte
is a signed type in Java. If you just wrote:
int result = value;
then result
would end up with the value ff ff ff fe
instead of 00 00 00 fe
. A further subtlety is that the &
is defined to operate only on int
values1, so what happens is:
value
is promoted to an int
(ff ff ff fe
).0xff
is an int
literal (00 00 00 ff
).&
is applied to yield the desired value for result
.(The point is that conversion to int
happens before the &
operator is applied.)
1Well, not quite. The &
operator works on long
values as well, if either operand is a long
. But not on byte
. See the Java Language Specification, sections 15.22.1 and 5.6.2.
Make sure your maven war plugin block in pom.xml includes all files (especially xml files) while building the war. But you don't need to include the .java files though.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.5</version>
<configuration>
<webResources>
<resources>
<directory>WebContent</directory>
<includes>
<include>**/*.*</include> <!--this line includes the xml files into the war, which will be found when it is exploded in server during deployment -->
</includes>
<excludes>
<exclude>*.java</exclude>
</excludes>
</resources>
</webResources>
<webXml>WebContent/WEB-INF/web.xml</webXml>
</configuration>
</plugin>
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
If a DateTime solution is acceptable this snippet returns the year of last month and month of last month avoiding the possible trap when you run this in January.
function fn_LastMonthYearNumber()
{
$now = new DateTime();
$lastMonth = $now->sub(new DateInterval('P1M'));
$lm= $lastMonth->format('m');
$ly= $lastMonth->format('Y');
return array($lm,$ly);
}
Do the following, download SQLLite Database Browser from here:
Locate your db. file in your phone.
Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!
You can actually export the data to an excel file or SQL.
Go to your CSS file and resize all your images as follows
img {
width: 100px;
height: 100px;
}
$fso = New-Object -com scripting.filesystemobject
$fso.GetFolder('c:\Program Files (x86)').ShortName()
PROGRA~2
This post describes how to integrate Fontawesome 5 into Angular 6 (Angular 5 and previous versions will also work, but then you have to adjust my writings)
Option 1: Add the css-Files
Pro: Every icon will be included
Contra: Every icon will be included (bigger app size because all fonts are included)
Add the following package:
npm install @fortawesome/fontawesome-free-webfonts
Afterwards add the following lines to your angular.json:
"app": {
....
"styles": [
....
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fontawesome.css",
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fa-regular.css",
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fa-brands.css",
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fa-solid.css"
],
...
}
Option 2: Angular package
Pro: Smaller app size
Contra: You have to include every icon you want to use seperatly
Use the FontAwesome 5 Angular package:
npm install @fortawesome/angular-fontawesome
Just follow their documentation to add the icons. They use the svg-icons, so you only have to add the svgs / icons, you really use.
Worth knowing:
If you are running an ENTRYPOINT script ... the script will work with the shebang
#!/bin/bash -x
But will stop the container from stopping with
#!/bin/bash -xe
I had the same problem on my local home network without proxy. Other answers in this thread didn't work for me. What I ended up doing was using yarn
which can be used interchangeably with npm
:
yarn add
To this day I don't know why my npm still don't work. I know for sure that it's a problem with my Wi-Fi, because when I connect to LTE internet broadcasted from my smartphone npm install
works again. It has probably something to do with router settings (problems started when I upgraded my internet speed and ISP worker replaced my old router with a new one).
Apparently you're missing setuptools. Some virtualenv versions use distribute instead of setuptools by default. Use the --setuptools
option when creating the virtualenv or set the VIRTUALENV_SETUPTOOLS=1
in your environment.
USE MyDatabase
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';
to get table counts
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'dbName';
this also works
USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();
In this post Scrollview vertical and horizontal in android they talk about a possible solution, quoting:
Matt Clark has built a custom view based on the Android source, and it seems to work perfectly: http://blog.gorges.us/2010/06/android-two-dimensional-scrollview
Beware that the class in that page has a bug calculating the view's horizonal width. A fix by Manuel Hilty is in the comments:
Solution: Replace the statement on line 808 by the following:
final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);
According with the official guidelines and sources if you want to be certain that also the last frame of your layout was drawned you can write for example:
import 'package:flutter/scheduler.dart';
void initState() {
super.initState();
if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
SchedulerBinding.instance.addPostFrameCallback((_) => yourFunction(context));
}
}
Use MySQL FIND_IN_SET function:
SELECT *
FROM table_name
WHERE id IN (..,..,..,..)
ORDER BY FIND_IN_SET (coloumn_name, .., .., ..);
I wanted a more exact and useful answer to this question. Here's the real answer (adjust accordingly if you want a byte array specifically; obviously the math will be off by a factor of 8 bits : 1 byte
):
class BitArray {
constructor(bits = 0) {
this.uints = new Uint32Array(~~(bits / 32));
}
getBit(bit) {
return (this.uints[~~(bit / 32)] & (1 << (bit % 32))) != 0 ? 1 : 0;
}
assignBit(bit, value) {
if (value) {
this.uints[~~(bit / 32)] |= (1 << (bit % 32));
} else {
this.uints[~~(bit / 32)] &= ~(1 << (bit % 32));
}
}
get size() {
return this.uints.length * 32;
}
static bitsToUints(bits) {
return ~~(bits / 32);
}
}
Usage:
let bits = new BitArray(500);
for (let uint = 0; uint < bits.uints.length; ++uint) {
bits.uints[uint] = 457345834;
}
for (let bit = 0; bit < 50; ++bit) {
bits.assignBit(bit, 1);
}
str = '';
for (let bit = bits.size - 1; bit >= 0; --bit) {
str += bits.getBit(bit);
}
str;
Output:
"00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000111111111111111111
11111111111111111111111111111111"
Note: This class is really slow to e.g. assign bits (i.e. ~2s per 10 million assignments) if it's created as a global variable, at least in the Firefox 76.0 Console on Linux... If, on the other hand, it's created as a variable (i.e. let bits = new BitArray(1e7);
), then it's blazingly fast (i.e. ~300ms per 10 million assignments)!
For more info, see here:
Note that I used Uint32Array because there's no way to directly have a bit/byte array (that you can interact with directly) and because even though there's a BigUint64Array
, JS only supports 32 bits:
Bitwise operators treat their operands as a sequence of 32 bits
...
The operands of all bitwise operators are converted to...32-bit integers
Centering something absolute
ly positioned is rather convoluted in CSS.
ul#slideshow li {
position: absolute;
left:50%;
margin-left:-20px;
}
Change margin-left
to (negative) half the width of the element you are trying to center.
This works for me
Move your .htaccess file to root folder (locate before application folder in my case)
RewriteEngine on
RewriteBase /yourProjectFolder
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
Mine config.php looks like this (application/config/config.php)
$config['base_url'] = "";
$config['index_page'] = "index.php";
$config['uri_protocol'] = "AUTO";
Let me know if its working for you guys too ! Cheers !
**just copy paste this code and run you can see the textbox disabled **
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style>.container{float:left;width:200px;height:25px;position:relative;}
.container input{float:left;width:200px;height:25px;}
.overlay{display:block;width:208px;position:absolute;top:0px;left:0px;height:32px;}
</style>
</head>
<body>
<div class="container">
<input type="text" value="[email protected]" />
<div class="overlay">
</div>
</div>
</body>
</html>
This is one way:
.your-selector:empty::after {
content: ".";
visibility: hidden;
}
For those who couldn't find this option. Install JDK Parameter Plugin
In your oncreateView() method you need to write this code and in KEYCODE_BACk condition you can write whatever the functionality you want
View v = inflater.inflate(R.layout.xyz, container, false);
//Back pressed Logic for fragment
v.setFocusableInTouchMode(true);
v.requestFocus();
v.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().finish();
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
return true;
}
}
return false;
}
});
I had to use the following CSS to get it working:
.parent {
display: flex;
justify-content: space-around;
align-items: flex-start;
overflow: visible;
}
.sticky {
position: sticky;
position: -webkit-sticky;
top: 0;
}
If above dosen't work then...
Go through all ancestors and make sure none of these elements have overflow: hidden
. You have to change this to overflow: visible
You cannot do new T()
due to type erasure. The default constructor can only be
public Navigation() { this("", "", null); }
You can create other constructors to provide default values for trigger and description. You need an concrete object of T
.
You can use MATCH
for instance.
Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.
In the entry box, put:
=MATCH(A2, 'Sheet2'!A:A, 0)
Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.
MATCH
takes the value A2
from your data table, looks into 'Sheet2'!A:A
and if there's an exact match (that's why there's a 0
at the end), then it'll return the row number.
Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.
EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:
=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))
<div align="center">
or
<div style="margin: 0 auto;">
The Trace messages can occur in the output window as well, even if you're not in debug mode. You just have to make sure the the TRACE compiler constant is defined.
This worked for me:
background: #4C2516 url('imagename.png') repeat-y 0 0;
Just put your sound file in the Res\raw\siren.mp3
folder, then use this code:
For Custom Sound:
Notification notification = builder.build();
notification.sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.siren);
For Default Sound:
notification.defaults |= Notification.DEFAULT_SOUND;
For Custom Vibrate:
long[] vibrate = { 0, 100, 200, 300 };
notification.vibrate = vibrate;
For Default Vibrate:
notification.defaults |= Notification.DEFAULT_VIBRATE;
Though Excel format conditions will only display 1 of 3 conditions related to number size (they code it as "positive; negative; zero; text" but I prefer to see it as : if isnumber and true; elseif isnumber and false; elseif number; elseif is text )
so to me the best answer is David's as well as Grastveit's comment for other regional format.
Here are the ones I use depending on reports I make.
[<1000000]#,##0.00," KB";[<1000000000]#,##0.00,," MB";#,##0.00,,," GB"
[>999999999999]#,##0.00,,,," TB";[>999999999]#,##0.00,,," GB";#.##0.00,," MB"
[<1000000]# ##0,00 " KB";[<1000000000]# ##0,00 " MB";# ##0,00 " GB"
[>999999999999]# ##0,00 " TB";[>999999999]# ##0,00 " GB";# ##0,00 " MB"
Take your pick!
Go to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager.
If you see that SQL Server/ SQL Server Browser State is 'stopped'.Right click on SQL Server/SQL Server Browser and click start. In some cases above state can stop though TCP connection to port 1433 is assigned.
You can use normal file operation to create an error log. Just refer this and input this link: PHP File Handling
It is not so much that C is fast as that C's cost model is transparent. If a C program is slow, it is slow in an obvious way: by executing a lot of statements. Compared with the cost of operations in C, high-level operations on objects (especially reflection) or strings can have costs that are not obvious.
Two languages that generally compile to binaries which are just as fast as C are Standard ML (using the MLton compiler) and Objective Caml. If you check out the benchmarks game you'll find that for some benchmarks, like binary trees, the OCaml version is faster than C. (I didn't find any MLton entries.) But don't take the shootout too seriously; it is, as it says, a game, the the results often reflect how much effort people have put in tuning the code.
MongoDB 3.4 now includes the ability to make a true case-insensitive index, which will dramtically increase the speed of case insensitive lookups on large datasets. It is made by specifying a collation with a strength of 2.
Probably the easiest way to do it is to set a collation on the database. Then all queries inherit that collation and will use it:
db.createCollection("cities", { collation: { locale: 'en_US', strength: 2 } } )
db.names.createIndex( { city: 1 } ) // inherits the default collation
You can also do it like this:
db.myCollection.createIndex({city: 1}, {collation: {locale: "en", strength: 2}});
And use it like this:
db.myCollection.find({city: "new york"}).collation({locale: "en", strength: 2});
This will return cities named "new york", "New York", "New york", etc.
For more info: https://jira.mongodb.org/browse/SERVER-90
<!-- xaml code-->
<Grid>
<ComboBox Name="cmbData" SelectedItem="{Binding SelectedstudentInfo, Mode=OneWayToSource}" HorizontalAlignment="Left" Margin="225,150,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
<Button VerticalAlignment="Center" Margin="0,0,150,0" Height="40" Width="70" Click="Button_Click">OK</Button>
</Grid>
//student Class
public class Student
{
public int Id { set; get; }
public string name { set; get; }
}
//set 2 properties in MainWindow.xaml.cs Class
public ObservableCollection<Student> studentInfo { set; get; }
public Student SelectedstudentInfo { set; get; }
//MainWindow.xaml.cs Constructor
public MainWindow()
{
InitializeComponent();
bindCombo();
this.DataContext = this;
cmbData.ItemsSource = studentInfo;
}
//method to bind cobobox or you can fetch data from database in MainWindow.xaml.cs
public void bindCombo()
{
ObservableCollection<Student> studentList = new ObservableCollection<Student>();
studentList.Add(new Student { Id=0 ,name="==Select=="});
studentList.Add(new Student { Id = 1, name = "zoyeb" });
studentList.Add(new Student { Id = 2, name = "siddiq" });
studentList.Add(new Student { Id = 3, name = "James" });
studentInfo=studentList;
}
//button click to get selected student MainWindow.xaml.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
Student student = SelectedstudentInfo;
if(student.Id ==0)
{
MessageBox.Show("select name from dropdown");
}
else
{
MessageBox.Show("Name :"+student.name + "Id :"+student.Id);
}
}
Make sure you don't have any firewalls blocking SMTP. The first time I tried to send an email, it was blocked both by Windows Firewall and McAfee - took forever to find them both.
I would suggest using inline CSS styling.
<table border="1" style="padding-right: 10px;">
<tr>
<td>Content</td>
</tr>
</table>
or
<table border="1">
<tr style="padding-right: 10px;">
<td>Content</td>
</tr>
</table>
or
<table border="1">
<tr>
<td style="padding-right: 10px;">Content</td>
</tr>
</table>
I don't quite follow what you need, but this is what I would do, assuming I understand you needs.
if element is hide by jquery then use
if($("#elmentid").is(':hidden'))
var objectList = objects.ToList();
objectList[0].SimpleInt=5;
This will update the original object as well. The new list will contain references to the objects contained within it, just like the original list. You can change the elements either and the update will be reflected in the other.
Now if you update a list (adding or deleting an item) that will not be reflected in the other list.
How to use PUT method using WebRequest.
//JsonResultModel class
public class JsonResultModel
{
public string ErrorMessage { get; set; }
public bool IsSuccess { get; set; }
public string Results { get; set; }
}
// HTTP_PUT Function
public static JsonResultModel HTTP_PUT(string Url, string Data)
{
JsonResultModel model = new JsonResultModel();
string Out = String.Empty;
string Error = String.Empty;
System.Net.WebRequest req = System.Net.WebRequest.Create(Url);
try
{
req.Method = "PUT";
req.Timeout = 100000;
req.ContentType = "application/json";
byte[] sentData = Encoding.UTF8.GetBytes(Data);
req.ContentLength = sentData.Length;
using (System.IO.Stream sendStream = req.GetRequestStream())
{
sendStream.Write(sentData, 0, sentData.Length);
sendStream.Close();
}
System.Net.WebResponse res = req.GetResponse();
System.IO.Stream ReceiveStream = res.GetResponseStream();
using (System.IO.StreamReader sr = new
System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
{
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
Out += str;
count = sr.Read(read, 0, 256);
}
}
}
catch (ArgumentException ex)
{
Error = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
}
catch (WebException ex)
{
Error = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
}
catch (Exception ex)
{
Error = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
}
model.Results = Out;
model.ErrorMessage = Error;
if (!string.IsNullOrWhiteSpace(Out))
{
model.IsSuccess = true;
}
return model;
}
I got the same error the first time I wanted to install LightGBM on python (GPU version).
You can simply fix it with this command line :
sudo apt-get install cmake libblkid-dev e2fslibs-dev libboost-all-dev libaudit-dev
the boost libraries will be installed and you'll be fine to continue your installation process.
Clone-: It will create exactly duplicate copy of your remote repository project in your local machine.
Pull-: Suppose two or more than two people are sharing the same repository. (Suppose another person name is Syam) (A Repository is a place where your project exist in Github) So if Syam does some changes in the same project in his local and pushes it to the remote repository So whatever the changes Syam did those changes will not reflect in your local. So to reflect those new changes in your local you have to use git pull. Overall we use git pull to update the project.
So basically we use git clone only once whereas we use git pull many times.
I was getting the Object not found error as shown in the screen shot while clicking the phpmyadmin link. Apache and SQL server had got started from the xampp console.
Solution: I uninstalled and installed again after deleting all the files and folders of xampp from C drive. Also, this time, I installed just the Apache and the SQL server. After this, phpmyadmin link started to work.
I know this is an old question, but I had a similar issue and found that:
lm(x ~ y + relevel(b, ref = "3"))
does exactly what you asked.
Try this,
$('td').click(function(){
var row_index = $(this).parent().index();
var col_index = $(this).index();
});
If you need the index of table contain td then you can change it to
var row_index = $(this).parent('table').index();
As the best anwser have writed using XMLHttpResponse
except window.open
, and I make the abstracts-anwser as a instance.
The main Js file is download.js
Download-JS
// var download_url = window.BASE_URL+ "/waf/p1/download_rules";
var download_url = window.BASE_URL+ "/waf/p1/download_logs_by_dt";
function download33() {
var sender_data = {"start_time":"2018-10-9", "end_time":"2018-10-17"};
var x=new XMLHttpRequest();
x.open("POST", download_url, true);
x.setRequestHeader("Content-type","application/json");
// x.setRequestHeader("Access-Control-Allow-Origin", "*");
x.setRequestHeader("Authorization", "JWT " + localStorage.token );
x.responseType = 'blob';
x.onload=function(e){download(x.response, "test211.zip", "application/zip" ); }
x.send( JSON.stringify(sender_data) ); // post-data
}
Use a lookup table, like:
char *table[16] = {"0000", "0001", .... "1111"};
then print each nibble like this
printf("%s%s", table[a / 0x10], table[a % 0x10]);
Surely you can use just one table, but it will be marginally faster and too big.
Using MVVM Light Toolkit:
Assuming that there is an Exit command in view model:
ICommand _exitCommand;
public ICommand ExitCommand
{
get
{
if (_exitCommand == null)
_exitCommand = new RelayCommand<object>(call => OnExit());
return _exitCommand;
}
}
void OnExit()
{
var msg = new NotificationMessageAction<object>(this, "ExitApplication", (o) =>{});
Messenger.Default.Send(msg);
}
This is received in the view:
Messenger.Default.Register<NotificationMessageAction<object>>(this, (m) => if (m.Notification == "ExitApplication")
{
Application.Current.Shutdown();
});
On the other hand, I handle Closing
event in MainWindow
, using the instance of ViewModel:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (((ViewModel.MainViewModel)DataContext).CancelBeforeClose())
e.Cancel = true;
}
CancelBeforeClose
checks the current state of view model and returns true if closing should be stopped.
Hope it helps someone.
Additional Solution: use Restul api wrapper libraries written in Java
/ python
/ Ruby
- An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.
For documentation and links: Remote Access API
I run at this when I tried to add privileges to performance_schema, which is mysql bug http://bugs.mysql.com/bug.php?id=44898 (workaround to add --single-transaction).
The reason behind posted this answer is I tried many solution but no one work properly, most of the answer not work in case where have to set cookie first time, and got result cookie not sync first time, Please use this solution it work for both iOS >= 11.0 <= iOS 11 till 8.0, also work with cookie sync first time.
For iOS >= 11.0 -- Swift 4.2
Get http cookies and set in wkwebview cookie store like this way, it's very tricky point to load your request in wkwebview, must sent request for loading when cookies gonna be set completely, here is function that i wrote.
Call function with closure in completion you call load webview. FYI this function only handle iOS >= 11.0
self.WwebView.syncCookies {
if let request = self.request {
self.WwebView.load(request)
}
}
Here is implementation for syncCookies function.
func syncCookies(completion:@escaping ()->Void) {
if #available(iOS 11.0, *) {
if let yourCookie = "HERE_YOUR_HTTP_COOKIE_OBJECT" {
self.configuration.websiteDataStore.httpCookieStore.setCookie(yourCookie, completionHandler: {
completion()
})
}
} else {
//Falback just sent
completion()
}
}
For iOS 8 till iOS 11
you need to setup some extra things you need to set two time cookies one through using WKUserScript and dont forget to add cookies in request as well, otherwise your cookie not sync first time and you will see you page not load first time properly. this is the heck that i found to support cookies for iOS 8.0
before you Wkwebview object creation.
func setUpWebView() {
let userController: WKUserContentController = WKUserContentController.init()
if IOSVersion.SYSTEM_VERSION_LESS_THAN(version: "11.0") {
if let cookies = HTTPCookieStorage.shared.cookies {
if let script = getJSCookiesString(for: cookies) {
cookieScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false)
userController.addUserScript(cookieScript!)
}
}
}
let webConfiguration = WKWebViewConfiguration()
webConfiguration.processPool = BaseWebViewController.processPool
webConfiguration.userContentController = userController
let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 0.0, height: self.webContainerView.frame.size.height))
self.WwebView = WKWebView (frame: customFrame, configuration: webConfiguration)
self.WwebView.translatesAutoresizingMaskIntoConstraints = false
self.webContainerView.addSubview(self.WwebView)
self.WwebView.uiDelegate = self
self.WwebView.navigationDelegate = self
self.WwebView.allowsBackForwardNavigationGestures = true // A Boolean value indicating whether horizontal swipe gestures will trigger back-forward list navigations
self.WwebView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
self.view.addConstraint(NSLayoutConstraint(item: WwebView, attribute: .trailing, relatedBy: .equal, toItem: self.webContainerView, attribute: .trailing, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: WwebView, attribute: .leading, relatedBy: .equal, toItem: self.webContainerView, attribute: .leading, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: WwebView, attribute: .top, relatedBy: .equal, toItem: self.webContainerView, attribute: .top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: WwebView, attribute: .bottom, relatedBy: .equal, toItem: self.webContainerView, attribute: .bottom, multiplier: 1, constant: 0))
}
Focus on this function getJSCookiesString
public func getJSCookiesString(for cookies: [HTTPCookie]) -> String? {
var result = ""
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
for cookie in cookies {
if cookie.name == "yout_cookie_name_want_to_sync" {
result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
if let date = cookie.expiresDate {
result += "expires=\(dateFormatter.string(from: date)); "
}
if (cookie.isSecure) {
result += "secure; "
}
result += "'; "
}
}
return result
}
Here is other step wkuserscript not sync cookies immediately, there a lot of heck to load first time page with cookie one is to reload webview again if it terminate process but i don't recommend to use it, its not good for user point of view, heck is whenever you ready to load request set cookies in request header as well like this way, don't forget to add iOS version check. before load request call this function.
request?.addCookies()
i wrote extension for URLRequest
extension URLRequest {
internal mutating func addCookies() {
//"appCode=anAuY28ucmFrdXRlbi5yZXdhcmQuaW9zLXpOQlRTRmNiejNHSzR0S0xuMGFRb0NjbUg4Ql9JVWJH;rpga=kW69IPVSYZTo0JkZBicUnFxC1g5FtoHwdln59Z5RNXgJoMToSBW4xAMqtf0YDfto;rewardadid=D9F8CE68-CF18-4EE6-A076-CC951A4301F6;rewardheader=true"
var cookiesStr: String = ""
if IOSVersion.SYSTEM_VERSION_LESS_THAN(version: "11.0") {
let mutableRequest = ((self as NSURLRequest).mutableCopy() as? NSMutableURLRequest)!
if let yourCookie = "YOUR_HTTP_COOKIE_OBJECT" {
// if have more than one cookies dont forget to add ";" at end
cookiesStr += yourCookie.name + "=" + yourCookie.value + ";"
mutableRequest.setValue(cookiesStr, forHTTPHeaderField: "Cookie")
self = mutableRequest as URLRequest
}
}
}
}
now you ready to go for testing iOS > 8
Besides having to escape colons as in the original answer, I have found if the indentation is off you could potentially get the same problem. In one makefile, I had to replace spaces with a tab and that allowed me to get past the error.
Facebook Graph is awesome. Just do something like below. I've entereted perl.org URL, you can put any URL there.
There are two ways to validate user input: annotations and by inheriting Spring's Validator class. For simple cases, the annotations are nice. If you need complex validations (like cross-field validation, eg. "verify email address" field), or if your model is validated in multiple places in your application with different rules, or if you don't have the ability to modify your model object by placing annotations on it, Spring's inheritance-based Validator is the way to go. I'll show examples of both.
The actual validation part is the same regardless of which type of validation you're using:
RequestMapping(value="fooPage", method = RequestMethod.POST)
public String processSubmit(@Valid @ModelAttribute("foo") Foo foo, BindingResult result, ModelMap m) {
if(result.hasErrors()) {
return "fooPage";
}
...
return "successPage";
}
If you are using annotations, your Foo
class might look like:
public class Foo {
@NotNull
@Size(min = 1, max = 20)
private String name;
@NotNull
@Min(1)
@Max(110)
private Integer age;
// getters, setters
}
Annotations above are javax.validation.constraints
annotations. You can also use Hibernate's
org.hibernate.validator.constraints
, but it doesn't look like you are using Hibernate.
Alternatively, if you implement Spring's Validator, you would create a class as follows:
public class FooValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Foo.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Foo foo = (Foo) target;
if(foo.getName() == null) {
errors.rejectValue("name", "name[emptyMessage]");
}
else if(foo.getName().length() < 1 || foo.getName().length() > 20){
errors.rejectValue("name", "name[invalidLength]");
}
if(foo.getAge() == null) {
errors.rejectValue("age", "age[emptyMessage]");
}
else if(foo.getAge() < 1 || foo.getAge() > 110){
errors.rejectValue("age", "age[invalidAge]");
}
}
}
If using the above validator, you also have to bind the validator to the Spring controller (not necessary if using annotations):
@InitBinder("foo")
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new FooValidator());
}
Also see Spring docs.
Hope that helps.
The MSDN is a good reference for these type of questions regarding syntax and usage. This is from the Transact SQL Reference - CASE page.
http://msdn.microsoft.com/en-us/library/ms181765.aspx
USE AdventureWorks2012;
GO
SELECT ProductNumber, Name, "Price Range" =
CASE
WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
FROM Production.Product
ORDER BY ProductNumber ;
GO
Another good site you may want to check out if you're using SQL Server is SQL Server Central. This has a large variety of resources available for whatever area of SQL Server you would like to learn.
I had the same problem after updating my AjaxControlToolkit.dll to the latest version 4.1.7.725 from 4.1.60623.0.
I've searched and came up to this page, but none of the answers help me.
After looking to the sample website of the Ajax Control Toolkit that is in the CodePlex zip file, I have realized that the <asp:ScriptManager>
replaced by the new <ajaxtoolkit:ToolkitScriptManager>
. I did so and there is no Sys.Extended is undefined any more.
Check if you do not have declared the method getAll() in the model. That causes the controller to think that you are calling a non-static method.
The state you save at onSaveInstanceState()
is later available at onCreate()
method invocation. So use onCreate
(and its Bundle
parameter) to restore state of your activity.
See section Attributes from documentation on directives.
observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.
A working example to implement the accepted answer by adding a "Boolean" column to an existing table in an oracle database (using number
type):
ALTER TABLE my_table_name ADD (
my_new_boolean_column number(1) DEFAULT 0 NOT NULL
CONSTRAINT my_new_boolean_column CHECK (my_new_boolean_column in (1,0))
);
This creates a new column in my_table_name
called my_new_boolean_column
with default values of 0. The column will not accept NULL
values and restricts the accepted values to either 0
or 1
.
The ordering between ng-model
and ng-click
seems to be different and it's something you probably shouldn't rely on. Instead you could do something like this:
<div ng-app="myApp" ng-controller="Ctrl">
<li ng-repeat="todo in todos">
<input type='checkbox' ng-model="todo.done" ng-click='onCompleteTodo(todo)'>
{{todo.text}} {{todo.done}}
</li>
<hr>
task: {{current.text}}
<hr>
<h2>Wrong value</h2>
done: {{current.done}}
</div>
And your script:
angular.module('myApp', [])
.controller('Ctrl', ['$scope', function($scope) {
$scope.todos=[
{'text': "get milk",
'done': true
},
{'text': "get milk2",
'done': false
}
];
$scope.current = $scope.todos[0];
$scope.onCompleteTodo = function(todo) {
console.log("onCompleteTodo -done: " + todo.done + " : " + todo.text);
//$scope.doneAfterClick=todo.done;
//$scope.todoText = todo.text;
$scope.current = todo;
};
}]);
What's different here is whenever you click a box, it sets that box as what's "current" and then display those values in the view. http://jsfiddle.net/QeR7y/
$('#textarea').blur()
Documentation at: http://api.jquery.com/blur/
No, the URL will always be updated when params are passed to transitionTo
.
This happens on state.js:698 in ui-router.
if you destroy the session on 127.0.0.1
it will not affect on localhost
and vice versa
Keep 2 stacks, let's call them inbox
and outbox
.
Enqueue:
inbox
Dequeue:
If outbox
is empty, refill it by popping each element from inbox
and pushing it onto outbox
Pop and return the top element from outbox
Using this method, each element will be in each stack exactly once - meaning each element will be pushed twice and popped twice, giving amortized constant time operations.
Here's an implementation in Java:
public class Queue<E>
{
private Stack<E> inbox = new Stack<E>();
private Stack<E> outbox = new Stack<E>();
public void queue(E item) {
inbox.push(item);
}
public E dequeue() {
if (outbox.isEmpty()) {
while (!inbox.isEmpty()) {
outbox.push(inbox.pop());
}
}
return outbox.pop();
}
}
It seems like you don't have react-scripts
in your global environment.
Two possibility are available here :
npm install -g react-scripts
or in your package.json change your script part like this :
"scripts": {
"start": "./node_modules/react-scripts/bin/react-scripts.js start",
"start:prod": "pushstate-server build",
"build": "./node_modules/react-scripts/bin/react-scripts.js build",
"test": "./node_modules/react-scripts/bin/react-scripts.js test --env=jsdom",
"eject": "./node_modules/react-scripts/bin/react-scripts.js eject",
"server": "cd client/api && pm2 start server.js --watch",
"proxy": "http://128.199.139.144:3000"
},
Not using nmap... but this is an alternative...
arp -n|grep -i B0:D3:93|awk '{print $1}'
All right, so i'm a serious cryptkeeper here by dragging up this very old question, but there is a much simpler approach to this, which was touched on by @Baserz above. And that is to use a combination of C# Extension methods and caching (Do NOT use session).
In fact, Microsoft has already provided a number of such extensions in the Microsoft.AspNet.Identity.IdentityExtensions
namespace. For instance, GetUserId()
is an extension method that returns the user Id. There is also GetUserName()
and FindFirstValue()
, which returns claims based on the IPrincipal.
So you need only include the namespace, and then call User.Identity.GetUserName()
to get the users name as configured by ASP.NET Identity.
I'm not certain if this is cached, since the older ASP.NET Identity is not open sourced, and I haven't bothered to reverse engineer it. However, if it's not then you can write your own extension method, that will cache this result for a specific amount of time.
Let me make a conclusion. In Swift 5
You can choose to addSubview to keyWindow, if you add the view in the last. Otherwise, you can bringSubViewToFront.
let view = UIView()
UIApplication.shared.keyWindow?.addSubview(view)
UIApplication.shared.keyWindow?.bringSubviewToFront(view)
You can also set the zPosition. But the drawback is that you can not change the gesture responding order.
view.layer.zPosition = 1
You can also do what the "Service Reference" generated code does
public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
public ServiceXClient() { }
public ServiceXClient(string endpointConfigurationName) :
base(endpointConfigurationName) { }
public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
base(binding, remoteAddress) { }
public bool ServiceXWork(string data, string otherParam)
{
return base.Channel.ServiceXWork(data, otherParam);
}
}
Where IServiceX is your WCF Service Contract
Then your client code:
var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");
Perhaps you need to know how urls are mapped too, since I suffered 404
for hours. There are two kinds of handlers handling requests. BeanNameUrlHandlerMapping
and SimpleUrlHandlerMapping
. When we defined a servlet-mapping
, we are using SimpleUrlHandlerMapping
. One thing we need to know is these two handlers share a common property called alwaysUseFullPath
which defaults to false
.
false
here means Spring will not use the full path to mapp a url to a controller. What does it mean? It means when you define a servlet-mapping
:
<servlet-mapping>
<servlet-name>viewServlet</servlet-name>
<url-pattern>/perfix/*</url-pattern>
</servlet-mapping>
the handler will actually use the *
part to find the controller. For example, the following controller will face a 404
error when you request it using /perfix/api/feature/doSomething
@Controller()
@RequestMapping("/perfix/api/feature")
public class MyController {
@RequestMapping(value = "/doSomething", method = RequestMethod.GET)
@ResponseBody
public String doSomething(HttpServletRequest request) {
....
}
}
It is a perfect match, right? But why 404
. As mentioned before, default value of alwaysUseFullPath
is false, which means in your request, only /api/feature/doSomething
is used to find a corresponding Controller, but there is no Controller cares about that path. You need to either change your url to /perfix/perfix/api/feature/doSomething
or remove perfix
from MyController base @RequestingMapping
.
Well, for a simple java like enum in php, I use:
class SomeTypeName {
private static $enum = array(1 => "Read", 2 => "Write");
public function toOrdinal($name) {
return array_search($name, self::$enum);
}
public function toString($ordinal) {
return self::$enum[$ordinal];
}
}
And to call it:
SomeTypeName::toOrdinal("Read");
SomeTypeName::toString(1);
But I'm a PHP beginner, struggling with the syntax so this might not be the best way. I experimented some with Class Constants, using Reflection to get the constant name from it's value, might be neater.
<select class="form-control" name="kategori_id">
<option value="">-- PILIH --</option>
@foreach($kategori as $id => $nama)
@if(old('kategori_id', $produk->kategori_id) == $id )
<option value="{{ $id }}" selected>{{ $nama }}</option>
@else
<option value="{{ $id }}">{{ $nama }}</option>
@endif
@endforeach
</select>
I solved my problem simply using ng-init
for default selection instead of ng-checked
<div ng-init="person.billing=FALSE"></div>
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="FALSE" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="TRUE" />
To find all the matching strings, use String's scan
method.
str = "A 54mpl3 string w1th 7 numb3rs scatter36 ar0und"
str.scan(/\d+/)
#=> ["54", "3", "1", "7", "3", "36", "0"]
If you want, MatchData
, which is the type of the object returned by the Regexp match
method, use:
str.to_enum(:scan, /\d+/).map { Regexp.last_match }
#=> [#<MatchData "54">, #<MatchData "3">, #<MatchData "1">, #<MatchData "7">, #<MatchData "3">, #<MatchData "36">, #<MatchData "0">]
The benefit of using MatchData
is that you can use methods like offset
:
match_datas = str.to_enum(:scan, /\d+/).map { Regexp.last_match }
match_datas[0].offset(0)
#=> [2, 4]
match_datas[1].offset(0)
#=> [7, 8]
See these questions if you'd like to know more:
Reading about special variables $&
, $'
, $1
, $2
in Ruby will be helpful too.
[a-z]
matches a single char between a and z. So, if your string was just "d"
, for example, then it would have matched and been printed out.
You need to change your regex to [a-z]+
to match one or more chars.
This isn't going to be the answer for many people, but EF will chuck this error when it can't connect to the DB. If you're working from home like I am, make sure you're still connected to your VPN!
To insert a single row of data:
INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');
To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.
INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');
To insert multiple rows of data in SQL Server 2008 or later:
INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');
To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:
INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'
Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.
You can pick specific items using destructuring, e.g.:
>>> [first, *middle, last] = range(10)
>>> first
0
>>> middle
[1, 2, 3, 4, 5, 6, 7, 8]
>>> last
9
Note that this is going to consume your generator, so while highly readable, it is less efficient than something like next()
, and ruinous on infinite generators:
>>> [first, *rest] = itertools.count()
The u- prefix just means that you have a Unicode string. When you really use the string, it won't appear in your data. Don't be thrown by the printed output.
For example, try this:
print mail_accounts[0]["i"]
You won't see a u.
The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.
However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).
The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).
For example:
[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
protected override void OnCreate(Bundle bindle)
{
base.OnCreate(bindle);
}
}
Here's my only-somewhat-contrived example of a case where the null
key can be useful:
public class Timer {
private static final Logger LOG = Logger.getLogger(Timer.class);
private static final Map<String, Long> START_TIMES = new HashMap<String, Long>();
public static synchronized void start() {
long now = System.currentTimeMillis();
if (START_TIMES.containsKey(null)) {
LOG.warn("Anonymous timer was started twice without being stopped; previous timer has run for " + (now - START_TIMES.get(null).longValue()) +"ms");
}
START_TIMES.put(null, now);
}
public static synchronized long stop() {
if (! START_TIMES.containsKey(null)) {
return 0;
}
return printTimer("Anonymous", START_TIMES.remove(null), System.currentTimeMillis());
}
public static synchronized void start(String name) {
long now = System.currentTimeMillis();
if (START_TIMES.containsKey(name)) {
LOG.warn(name + " timer was started twice without being stopped; previous timer has run for " + (now - START_TIMES.get(name).longValue()) +"ms");
}
START_TIMES.put(name, now);
}
public static synchronized long stop(String name) {
if (! START_TIMES.containsKey(name)) {
return 0;
}
return printTimer(name, START_TIMES.remove(name), System.currentTimeMillis());
}
private static long printTimer(String name, long start, long end) {
LOG.info(name + " timer ran for " + (end - start) + "ms");
return end - start;
}
}
Note that if you include android:id...
into the <include />
tag, it will override whatever id was defined inside the included layout. For example:
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/some_id_if_needed"
layout="@layout/yourlayout" />
yourlayout.xml:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/some_other_id">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/button1" />
</LinearLayout>
Then you would reference this included layout in code as follows:
View includedLayout = findViewById(R.id.some_id_if_needed);
Button insideTheIncludedLayout = (Button)includedLayout.findViewById(R.id.button1);
Another simple solution is to create a filter:
app.filter('trusted', ['$sce', function ($sce) {
return function(url) {
return $sce.trustAsResourceUrl(url);
};
}]);
Then specify the filter in ng-src
:
<video controls poster="img/poster.png">
<source ng-src="{{object.src | trusted}}" type="video/mp4"/>
</video>
you can accomplish in both these ways.
1.hadoop fs -get <HDFS file path> <Local system directory path>
2.hadoop fs -copyToLocal <HDFS file path> <Local system directory path>
Ex:
My files are located in /sourcedata/mydata.txt I want to copy file to Local file system in this path /user/ravi/mydata
hadoop fs -get /sourcedata/mydata.txt /user/ravi/mydata/
I know this is an old post. But here is how I have done it:
public Form1(string myFile)
{
InitializeComponent();
this.Show();
if (myFile != null)
{
OpenFile(myFile);
}
}
private void OpenFile(string myFile = null)
{
MessageBox.Show(myFile);
}
The two answers are good. And I also suggest you a similar method:
<% @images.each.with_index do |page, index| %>
<% end %>
You might not see the difference between this and the accepted answer. Let me direct your eyes to these method calls: .each.with_index
see how it's .each
and then .with_index
.
It's hard to respond to a statement without examples of how it's not working, but it's crucial to understand that TFVC (in "Server Workspace" mode, which was the mechanism prior to TFS 2012) does not examine the state of your local filesystem. TFVC Server Workspaces are a "checkout-edit-checkin" type of system where this is by-design, an intentional decision made to massively reduce the amount of file I/O required to determine the state of your workspace. Instead, the workspace information is saved on the server.
This allows TFVC Server Workspaces to scale to very large codebases very efficiently. If you are in a multi-gigabyte code base (like Visual Studio or the Windows source tree) then your client does not need to scan your local filesystem, looking for files that may have changed, because the contract you have with TFS is that you will explicitly check a file out when you want to edit it.
You are expected to not mark a file as write-only and change it without explicitly checking it out first. If you go down this route, then the server does not know that you have made changes to your file, and performing a "Get Latest" operation will not update your local workspace, because you haven't told the server that you've made changes.
If you do subvert this mechanism then you can use the tfpt reconcile
command to examine your local workspace for changes that you have made locally.
If you find yourself using "Get Specific Version" and selecting the "force" and "overwrite" options, then it is very likely that you are in the habit of bypassing all of the enforcements that TFS has implemented to keep you from hurting yourself, and you should probably consider TFVC Local Workspaces.
TFVC Local Workspaces provide an "edit-merge-commit" type of version control system, which means that you do not need to explicitly check files out before editing them and they are not read-only on-disk. Instead, you simply need to edit the file, and your client will scan the filesystem, notice the change, and present this as a pending change.
TFVC Local Workspaces are recommended for small projects that do not require fine-grained permissions control, since they present a much nicer workflow. You are not required to be online, and you do not have to explicitly check files out before editing them.
TFVC Local Workspaces are the default in TFS 2012, and if they are not enabled for you, then you should ask your server administrator. (Organizations with very large codebases or strict auditing requirements may disable TFVC Local Workspaces.)
Eric Sink's excellent book Version Control By Example outlines the differences between checkout-edit-checkin and edit-merge-commit systems and when one is more appropriate than the other.
The Professional Team Foundation Server 2013 book also provides excellent information about the differences between TFVC Server Workspaces and TFVC Local Workspaces. The MSDN documentation and blogs also provide detailed information:
@ts-expect-error
TS 3.9 introduces a new magic comment. @ts-expect-error
will:
@ts-ignore
if (false) {
// @ts-expect-error: Let's ignore a single compiler error like this unreachable code
console.log("hello"); // compiles
}
// If @ts-expect-error didn't suppress anything at all, we now get a nice warning
let flag = true;
// ...
if (flag) {
// @ts-expect-error
// ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
console.log("hello");
}
@ts-ignore
and @ts-expect-error
can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:
? Use any
type
// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;
// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;
? Augment JQueryStatic
interface
// ./global.d.ts
interface JQueryStatic {
summernote: any;
}
// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works
In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js
and use --allowJs
with checkJs: false
.