Try this to find de intersection, the keys that is in both dictionarie, if you want the keys not found on second dictionarie, just use the not in...
intersect = filter(lambda x, dictB=dictB.keys(): x in dictB, dictA.keys())
WSDL (Web Services Description Language) describes your service and its operations - what is the service called, which methods does it offer, what kind of in parameters and return values do these methods have?
It's a description of the behavior of the service - it's functionality.
XSD (Xml Schema Definition) describes the static structure of the complex data types being exchanged by those service methods. It describes the types, their fields, any restriction on those fields (like max length or a regex pattern) and so forth.
It's a description of datatypes and thus static properties of the service - it's about data.
Comparison of different approaches to set exact image sizes in pixels
This answer will focus on:
savefig
Here is a quick comparison of some of the approaches I've tried with images showing what the give.
Baseline example without trying to set the image dimensions
Just to have a comparison point:
base.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots()
print('fig.dpi = {}'.format(fig.dpi))
print('fig.get_size_inches() = ' + str(fig.get_size_inches())
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig('base.png', format='png')
run:
./base.py
identify base.png
outputs:
fig.dpi = 100.0
fig.get_size_inches() = [6.4 4.8]
base.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000
My best approach so far: plt.savefig(dpi=h/fig.get_size_inches()[1]
height-only control
I think this is what I'll go with most of the time, as it is simple and scales:
get_size.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'get_size.png',
format='png',
dpi=height/fig.get_size_inches()[1]
)
run:
./get_size.py 431
outputs:
get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000
and
./get_size.py 1293
outputs:
main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000
I tend to set just the height because I'm usually most concerned about how much vertical space the image is going to take up in the middle of my text.
plt.savefig(bbox_inches='tight'
changes image size
I always feel that there is too much white space around images, and tended to add bbox_inches='tight'
from:
Removing white space around a saved image in matplotlib
However, that works by cropping the image, and you won't get the desired sizes with it.
Instead, this other approach proposed in the same question seems to work well:
plt.tight_layout(pad=1)
plt.savefig(...
which gives the exact desired height for height equals 431:
Fixed height, set_aspect
, automatically sized width and small margins
Ermmm, set_aspect
messes things up again and prevents plt.tight_layout
from actually removing the margins...
plt.savefig(dpi=h/fig.get_size_inches()[1]
+ width control
If you really need a specific width in addition to height, this seems to work OK:
width.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
h = int(sys.argv[1])
w = int(sys.argv[2])
fig, ax = plt.subplots()
wi, hi = fig.get_size_inches()
fig.set_size_inches(hi*(w/h), hi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'width.png',
format='png',
dpi=h/hi
)
run:
./width.py 431 869
output:
width.png PNG 869x431 869x431+0+0 8-bit sRGB 10965B 0.000u 0:00.000
and for a small width:
./width.py 431 869
output:
width.png PNG 211x431 211x431+0+0 8-bit sRGB 6949B 0.000u 0:00.000
So it does seem that fonts are scaling correctly, we just get some trouble for very small widths with labels getting cut off, e.g. the 100
on the top left.
I managed to work around those with Removing white space around a saved image in matplotlib
plt.tight_layout(pad=1)
which gives:
width.png PNG 211x431 211x431+0+0 8-bit sRGB 7134B 0.000u 0:00.000
From this, we also see that tight_layout
removes a lot of the empty space at the top of the image, so I just generally always use it.
Fixed magic base height, dpi
on fig.set_size_inches
and plt.savefig(dpi=
scaling
I believe that this is equivalent to the approach mentioned at: https://stackoverflow.com/a/13714720/895245
magic.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
magic_height = 300
w = int(sys.argv[1])
h = int(sys.argv[2])
dpi = 80
fig, ax = plt.subplots(dpi=dpi)
fig.set_size_inches(magic_height*w/(h*dpi), magic_height/dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'magic.png',
format='png',
dpi=h/magic_height*dpi,
)
run:
./magic.py 431 231
outputs:
magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000
And to see if it scales nicely:
./magic.py 1291 693
outputs:
magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000
So we see that this approach also does work well. The only problem I have with it is that you have to set that magic_height
parameter or equivalent.
Fixed DPI + set_size_inches
This approach gave a slightly wrong pixel size, and it makes it is hard to scale everything seamlessly.
set_size_inches.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
w = int(sys.argv[1])
h = int(sys.argv[2])
fig, ax = plt.subplots()
fig.set_size_inches(w/fig.dpi, h/fig.dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(
0,
60.,
'Hello',
# Keep font size fixed independently of DPI.
# https://stackoverflow.com/questions/39395616/matplotlib-change-figsize-but-keep-fontsize-constant
fontdict=dict(size=10*h/fig.dpi),
)
plt.savefig(
'set_size_inches.png',
format='png',
)
run:
./set_size_inches.py 431 231
outputs:
set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000
so the height is slightly off, and the image:
The pixel sizes are also correct if I make it 3 times larger:
./set_size_inches.py 1291 693
outputs:
set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000
We understand from this however that for this approach to scale nicely, you need to make every DPI-dependant setting proportional to the size in inches.
In the previous example, we only made the "Hello" text proportional, and it did retain its height between 60 and 80 as we'd expect. But everything for which we didn't do that, looks tiny, including:
SVG
I could not find how to set it for SVG images, my approaches only worked for PNG e.g.:
get_size_svg.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'get_size_svg.svg',
format='svg',
dpi=height/fig.get_size_inches()[1]
)
run:
./get_size_svg.py 431
and the generated output contains:
<svg height="345.6pt" version="1.1" viewBox="0 0 460.8 345.6" width="460.8pt"
and identify says:
get_size_svg.svg SVG 614x461 614x461+0+0 8-bit sRGB 17094B 0.000u 0:00.000
and if I open it in Chromium 86 the browser debug tools mouse image hover confirm that height as 460.79.
But of course, since SVG is a vector format, everything should in theory scale, so you can just convert to any fixed sized format without loss of resolution, e.g.:
inkscape -h 431 get_size_svg.svg -b FFF -e get_size_svg.png
gives the exact height:
I use Inkscape instead of Imagemagick's convert
here because you need to mess with -density
as well to get sharp SVG resizes with ImageMagick:
And setting <img height=""
on the HTML should also just work for the browser.
Tested on matplotlib==3.2.2.
My suggestions :
For setting the values in the number, use constructors. Do not use like the methods you have used above like :
public void setNumber(double fnum, double snum){ this.fn = fnum; this.sn = snum; }
Constructors exists to initialize the objects.This is their job and they are pretty good at it.
Getters for members of Calculate class seem in place. But setters are not. Getters and setters serves as one important block in the bridge of efficient programming with java. Put setters for fnum and snum as well
In the main class, create a Calculate object using the new operator and the constructor in place.
Call the getAnswer() method with the created Calculate object.
Rest of the code looks fine to me. Be modular. You could read your program in a much better way.
Here is my modular piece of code. Two files : Main.java & Calculate.java
public class Calculate {
private double fn;
private double sn;
private char op;
public double getFn() {
return fn;
}
public void setFn(double fn) {
this.fn = fn;
}
public double getSn() {
return sn;
}
public void setSn(double sn) {
this.sn = sn;
}
public char getOp() {
return op;
}
public void setOp(char op) {
this.op = op;
}
public Calculate(double fn, double sn, char op) {
this.fn = fn;
this.sn = sn;
this.op = op;
}
public void getAnswer(){
double ans;
switch (getOp()){
case '+':
ans = add(getFn(), getSn());
ansOutput(ans);
break;
case '-':
ans = sub (getFn(), getSn());
ansOutput(ans);
break;
case '*':
ans = mul (getFn(), getSn());
ansOutput(ans);
break;
case '/':
ans = div (getFn(), getSn());
ansOutput(ans);
break;
default:
System.out.println("--------------------------");
System.out.println("Invalid choice of operator");
System.out.println("--------------------------");
}
}
public static double add(double x,double y){
return x + y;
}
public static double sub(double x, double y){
return x - y;
}
public static double mul(double x, double y){
return x * y;
}
public static double div(double x, double y){
return x / y;
}
public static void ansOutput(double x){
System.out.println("----------- -------");
System.out.printf("the answer is %.2f\n", x);
System.out.println("-------------------");
}
}
public class Main {
public static void main(String args[])
{
Calculate obj = new Calculate(1,2,'+');
obj.getAnswer();
}
}
The short answer is that history.pushState
(not History.pushState
, which would throw an exception, the window
part is optional) will never do what you suggest.
If pages are refreshing, then it is caused by other things that you are doing (for example, you might have code running that goes to a new location in the case of the address bar changing).
history.pushState({urlPath:'/page2.php'},"",'/page2.php')
works exactly like it is supposed to in the latest versions of Chrome, IE and Firefox for me and my colleagues.
In fact you can put whatever you like into the function: history.pushState({}, '', 'So long and thanks for all the fish.not a real file')
.
If you post some more code (with special attention for code nearby the history.pushState
and anywhere document.location
is used), then we'll be more than happy to help you figure out where exactly this issue is coming from.
If you post more code, I'll update this answer (I have your question favourited) :).
Another way to check on connection attempts is to look at the server's event log. On my Windows 2008 R2 Enterprise machine I opened the server manager (right-click on Computer and select Manage. Then choose Diagnostics -> Event Viewer -> Windows Logs -> Applcation. You can filter the log to isolate the MSSQLSERVER events. I found a number that looked like this
Login failed for user 'bogus'. The user is not associated with a trusted SQL Server connection. [CLIENT: 10.12.3.126]
The -nc
, --no-clobber
option isn't the best solution as newer files will not be downloaded. One should use -N
instead which will download and overwrite the file only if the server has a newer version, so the correct answer is:
wget -N http://www.example.com/images/misc/pic.png
Then running Wget with -N, with or without
-r
or-p
, the decision as to whether or not to download a newer copy of a file depends on the local and remote timestamp and size of the file.-nc
may not be specified at the same time as-N
.
-N
,--timestamping
: Turn on time-stamping.
Or you may use Selenium Action Class to simulate user interaction -- For example
WebDriver = new FirefoxDriver();
WebElement menu = driver.findElement(By.xpath("")); // the triger event element
Actions build = new Actions(driver); // heare you state ActionBuider
build.moveToElement(menu).build().perform(); // Here you perform hover mouse over the needed elemnt to triger the visibility of the hidden
WebElement m2m= driver.findElement(By.xpath(""));//the previous non visible element
m2m.click();
import sys sys.path.append('/Users/{user}/Library/Python/3.7/lib/python/site-packages') import ta
The best way in my eyes is to use the concat()
method provided by the String
class itself.
The useage would, in your case, look like this:
String myConcatedString = cursor.getString(numcol).concat('-').
concat(cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE)));
I wound up writing my own command-line tool to take care of this. It's similar to cut
, except it knows what to do with quoted fields, etc. This tool, paired with @Jimothy's answer, allows me to get a headerless CSV from a remote MySQL server I have no filesystem access to onto my local machine with this command:
$ mysql -N -e "select people, places from things" | csvm -i '\t' -o ','
Bill,"Raleigh, NC"
This is totally system dependent. You should experiment to find the optimum solution.
Try starting with bs=8388608
. (As Hitachi HDDs seems to have 8MB cache.)
#False positive cases
train = pd.merge(X_train, y_train,left_index=True, right_index=True)
y_train_pred = pd.DataFrame(y_train_pred)
y_train_pred.rename(columns={0 :'Predicted'}, inplace=True )
train = train.reset_index(drop=True).merge(y_train_pred.reset_index(drop=True),
left_index=True,right_index=True)
train['FP'] = np.where((train['Banknote']=="Forged") & (train['Predicted']=="Genuine"),1,0)
train[train.FP != 0]
Don't forget the spawn
command to create a background process to execute the specified command. You can even wait for its completion using the Process
class and the returned pid
:
pid = spawn("tar xf ruby-2.0.0-p195.tar.bz2")
Process.wait pid
pid = spawn(RbConfig.ruby, "-eputs'Hello, world!'")
Process.wait pid
The doc says: This method is similar to #system
but it doesn't wait for the command to finish.
Generally, Postman used for debugging and used in the development phase. But in case you want to block it even from postman try this.
const referrer_domain = "[enter-the-domain-name-of-the-referrer]"
//check for the referrer domain
app.all('/*', function(req, res, next) {
if(req.headers.referer.indexOf(referrer_domain) == -1){
res.send('Invalid Request')
}
next();
});
echo date('H:i', mktime(0,257));
Intent intent = new Intent(this, classObject);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
This Will work for all Android versions. Where IntentCompat
the class added in Android Support library.
This is copy my answer from THIS place.
Only need to fill datagrid again like this:
this.XXXTableAdapter.Fill(this.DataSet.XXX);
If you use automaticlly connect from dataGridView this code create automaticlly in Form_Load()
I disagree with the accepted answer being "the easiest", particularly if you want to use virtualenv.
You can use the Unofficial Windows Binaries instead. Download the appropriate wheel from there, and install it with pip
:
pip install pywin32-219-cp27-none-win32.whl
(Make sure you pick the one for the right version and bitness of Python).
You might be able to get the URL and install it via pip
without downloading it first, but they're made it a bit harder to just grab the URL. Probably better to download it and host it somewhere yourself.
Taking @Demosthenex 's answer a step further, if you'd like to also keep track of the code in your Microsoft Excel Objects and UserForms you have to get a little bit tricky.
First I altered my SaveCodeModules()
function to account for the different types of code I plan to export:
Sub SaveCodeModules(dir As String)
'This code Exports all VBA modules
Dim moduleName As String
Dim vbaType As Integer
With ThisWorkbook.VBProject
For i = 1 To .VBComponents.count
If .VBComponents(i).CodeModule.CountOfLines > 0 Then
moduleName = .VBComponents(i).CodeModule.Name
vbaType = .VBComponents(i).Type
If vbaType = 1 Then
.VBComponents(i).Export dir & moduleName & ".vba"
ElseIf vbaType = 3 Then
.VBComponents(i).Export dir & moduleName & ".frm"
ElseIf vbaType = 100 Then
.VBComponents(i).Export dir & moduleName & ".cls"
End If
End If
Next i
End With
End Sub
The UserForms can be exported and imported just like VBA code. The only difference is that two files will be created when a form is exported (you'll get a .frm
and a .frx
file for each UserForm). One of these holds the software you've written and the other is a binary file which (I'm pretty sure) defines the layout of the form.
Microsoft Excel Objects (MEOs) (meaning Sheet1
, Sheet2
, ThisWorkbook
etc) can be exported as a .cls
file. However, when you want to get this code back into your workbook, if you attempt to import it the same way you would a VBA module, you'll get an error if that sheet already exists in the workbook.
To get around this issue, I decided not to try to import the .cls file into Excel, but to read the .cls
file into excel as a string instead, then paste this string into the empty MEO. Here is my ImportCodeModules:
Sub ImportCodeModules(dir As String)
Dim modList(0 To 0) As String
Dim vbaType As Integer
' delete all forms, modules, and code in MEOs
With ThisWorkbook.VBProject
For Each comp In .VBComponents
moduleName = comp.CodeModule.Name
vbaType = .VBComponents(moduleName).Type
If moduleName <> "DevTools" Then
If vbaType = 1 Or _
vbaType = 3 Then
.VBComponents.Remove .VBComponents(moduleName)
ElseIf vbaType = 100 Then
' we can't simply delete these objects, so instead we empty them
.VBComponents(moduleName).CodeModule.DeleteLines 1, .VBComponents(moduleName).CodeModule.CountOfLines
End If
End If
Next comp
End With
' make a list of files in the target directory
Set FSO = CreateObject("Scripting.FileSystemObject")
Set dirContents = FSO.getfolder(dir) ' figure out what is in the directory we're importing
' import modules, forms, and MEO code back into workbook
With ThisWorkbook.VBProject
For Each moduleName In dirContents.Files
' I don't want to import the module this script is in
If moduleName.Name <> "DevTools.vba" Then
' if the current code is a module or form
If Right(moduleName.Name, 4) = ".vba" Or _
Right(moduleName.Name, 4) = ".frm" Then
' just import it normally
.VBComponents.Import dir & moduleName.Name
' if the current code is a microsoft excel object
ElseIf Right(moduleName.Name, 4) = ".cls" Then
Dim count As Integer
Dim fullmoduleString As String
Open moduleName.Path For Input As #1
count = 0 ' count which line we're on
fullmoduleString = "" ' build the string we want to put into the MEO
Do Until EOF(1) ' loop through all the lines in the file
Line Input #1, moduleString ' the current line is moduleString
If count > 8 Then ' skip the junk at the top of the file
' append the current line `to the string we'll insert into the MEO
fullmoduleString = fullmoduleString & moduleString & vbNewLine
End If
count = count + 1
Loop
' insert the lines into the MEO
.VBComponents(Replace(moduleName.Name, ".cls", "")).CodeModule.InsertLines .VBComponents(Replace(moduleName.Name, ".cls", "")).CodeModule.CountOfLines + 1, fullmoduleString
Close #1
End If
End If
Next moduleName
End With
End Sub
In case you're confused by the dir
input to both of these functions, that is just your code repository! So, you'd call these functions like:
SaveCodeModules "C:\...\YourDirectory\Project\source\"
ImportCodeModules "C:\...\YourDirectory\Project\source\"
This problem occurred to me when using nested try- catch and using the $ex->getPrevious() function for logging exception .mabye your code has endless loop. So you first need to check the code and increase the size of the memory if necessary
try {
//get latest product data and latest stock from api
$latestStocksInfo = Product::getLatestProductWithStockFromApi();
} catch (\Exception $error) {
try {
$latestStocksInfo = Product::getLatestProductWithStockFromDb();
} catch (\Exception $ex) {
/*log exception */
Log::channel('report')->error(['message'=>$ex->getMessage(),'file'=>$ex->getFile(),'line'=>$ex->getLine(),'Previous'=>$ex->getPrevious()]);///------------->>>>>>>> this problem when use
Log::channel('report')->error(['message'=>$ex->getMessage(),'file'=>$ex->getFile(),'line'=>$ex->getLine()]);///------------->>>>>>>> this code is ok
}
Log::channel('report')->error(['message'=>$error->getMessage(),'file'=>$error->getFile(),'line'=>$error->getLine()]);
/***log exception ***/
}
Use update
, stop
and receive
events, check it over here
Search for SSH connections for "myusername" account;
Take first result string;
Take 5th column;
Split by ":" and return 1st part (port number don't needed, we want just IP):
netstat -tapen | grep "sshd: myusername" | head -n1 | awk '{split($5, a, ":"); print a[1]}'
Another way:
who am i | awk '{l = length($5) - 2; print substr($5, 2, l)}'
First of all, you need to check that the IIS is installed in your machine, for that you can go to:
Control Panel --> Add or Remove Programs --> Windows Features --> And Check if Internet Information Services is installed with at least the 'Web Administration Tools' Enabled and The 'World Wide Web Service'
If not, check it, and Press Accept to install it.
Once that is done, you need to go to Administrative Tools in Control Panel and the IIS Will be there. Or simply run inetmgr (after Win+R).
Edit: You should have something like this:
For people using swift [2.2] on Linux i.e. Ubuntu, the import is different!
The correct way to do this is to use Glibc. This is because on OS X and iOS, the basic Unix-like API's are in Darwin but in linux, these are located in Glibc. Importing Foundation won't help you here because it doesn't make the distinction by itself. To do this, you have to explicitly import it yourself:
#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
You can follow the development of the Foundation framework here to learn more
As pointed out by @Cœur, starting from swift 3.0 some math functions are now part of the types themselves. For example, Double now has a squareRoot function. Similarly, ceil
, floor
, round
, can all be achieved with Double.rounded(FloatingPointRoundingRule) -> Double
.
Furthermore, I just downloaded and installed the latest stable version of swift on Ubuntu 18.04, and it looks like Foundation
framework is all you need to import to have access to the math functions now. I tried finding documentation for this, but nothing came up.
? swift
Welcome to Swift version 4.2.1 (swift-4.2.1-RELEASE). Type :help for assistance.
1> sqrt(9)
error: repl.swift:1:1: error: use of unresolved identifier 'sqrt'
sqrt(9)
^~~~
1> import Foundation
2> sqrt(9)
$R0: Double = 3
3> floor(9.3)
$R1: Double = 9
4> ceil(9.3)
$R2: Double = 10
Just wanted to add a little more detail to the answers given. You can also use
sheet.Visible = False
to hide and
sheet.Visible = True
to unhide.
No guarantee, but I suspect IE uses the older Protected Storage API.
To those who are stuck wondering why a window flashes and goes away without doing anything, the problem may related to the RELATIVE path in your Python script. e.g. you used ".\". Even the Python script and Excel Workbook is in the same directory, the Current Directory may still be different. If you don't want to modify your code to change it to an absolute path. Just change your current Excel directory before you run the python script by:
ChDir ActiveWorkbook.Path
I'm just giving a example here. If the flash do appear, one of the first issues to check is the Current Working Directory.
window.location.hash = '#tries';
This will scroll to the element in question, essentially "focus"ing it.
https://angular.io/docs/ts/latest/guide/router.html
Add the base element just after the
<head>
tag. If theapp
folder is the application root, as it is for our application, set thehref
value exactly as shown here.
The <base href="/">
tells the Angular router what is the static part of the URL. The router then only modifies the remaining part of the URL.
<head>
<base href="/">
...
</head>
Alternatively add
>= Angular2 RC.6
import {APP_BASE_HREF} from '@angular/common';
@NgModule({
declarations: [AppComponent],
imports: [routing /* or RouterModule */],
providers: [{provide: APP_BASE_HREF, useValue : '/' }]
]);
in your bootstrap.
In older versions the imports had to be like
< Angular2 RC.6
import {APP_BASE_HREF} from '@angular/common';
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
{provide: APP_BASE_HREF, useValue : '/' });
]);
< RC.0
import {provide} from 'angular2/core';
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(APP_BASE_HREF, {useValue : '/' });
]);
< beta.17
import {APP_BASE_HREF} from 'angular2/router';
>= beta.17
import {APP_BASE_HREF} from 'angular2/platform/common';
See also Location and HashLocationStrategy stopped working in beta.16
also this works too
SELECT replace(replace(replace(convert(varchar, getdate(), 120),':',''),'-',''),' ','')
The caller and the callee need to use the same convention at the point of invokation - that's the only way it could reliably work. Both the caller and the callee follow a predefined protocol - for example, who needs to clean up the stack. If conventions mismatch your program runs into undefined behavior - likely just crashes spectacularly.
This is only required per invokation site - the calling code itself can be a function with any calling convention.
You shouldn't notice any real difference in performance between those conventions. If that becomes a problem you usually need to make less calls - for example, change the algorithm.
Perhaps uuid.uuid4()
might do the job. See uuid for more information.
Inside your git repository directory, run git config user.name
.
Why is running this command within your git repo directory important?
If you are outside of a git repository, git config user.name
gives you the value of user.name
at global level. When you make a commit, the associated user name is read at local level.
Although unlikely, let's say user.name
is defined as foo
at global level, but bar
at local level. Then, when you run git config user.name
outside of the git repo directory, it gives bar
. However, when you really commits something, the associated value is foo
.
Git config variables can be stored in 3 different levels. Each level overrides values in the previous level.
1. System level (applied to every user on the system and all their repositories)
git config --list --system
(may need sudo
)git config --system color.ui true
git config --edit --system
2. Global level (values specific personally to you, the user. )
git config --list --global
git config --global user.name xyz
git config --edit --global
3. Repository level (specific to that single repository)
git config --list --local
git config --local core.ignorecase true
(--local
optional)git config --edit --local
(--local
optional)How to view all settings?
git config --list
, showing system, global, and (if inside a repository) local configsgit config --list --show-origin
, also shows the origin file of each config itemHow to read one particular config?
git config user.name
to get user.name
, for example.--system
, --global
, --local
to read that value at a particular level.Reference: 1.6 Getting Started - First-Time Git Setup
For me the dialogue appears more than one if I click the dpFlightDate edit text more than one time same for the timmer dialog . how can I avoid this dialog to appear only once and if the user click's 2nd time the dialog must not appear again ie if dialog is on the screen ?
// perform click event on edit text
dpFlightDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(frmFlightDetails.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
dpFlightDate.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
tpFlightTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog
timePickerDialog = new TimePickerDialog(frmFlightDetails.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
tpFlightTime.setText( selectedHour + ":" + selectedMinute);
}
}, hour, minute, true);//Yes 24 hour time
timePickerDialog.setTitle("Select Time");
timePickerDialog.show();
}
});
_mytexteditingcontroller.value = new TextEditingController.fromValue(new TextEditingValue(text: "My String")).value;
This seems to work if anyone has a better way please feel free to let me know.
1.Generate a war file from your application
2. open tomcat manager, go down the page
3. Click on browse to deploy the war.
4. choose your war file.
There you go!
I'm not 100% sure that I understand your question, so tell me if I'm wrong.
If I got it right, you are reading jbytes that are technically signed chars, but really pixel values ranging from 0 to 255, and you're wondering how you should handle them without corrupting the values in the process.
Then, you should do the following:
convert jbytes to unsigned char before doing anything else, this will definetly restore the pixel values you are trying to manipulate
use a larger signed integer type, such as int while doing intermediate calculations, this to make sure that over- and underflows can be detected and dealt with (in particular, not casting to a signed type could force to compiler to promote every type to an unsigned type in which case you wouldn't be able to detect underflows later on)
when assigning back to a jbyte, you'll want to clamp your value to the 0-255 range, convert to unsigned char and then convert again to signed char: I'm not certain the first conversion is strictly necessary, but you just can't be wrong if you do both
For example:
inline int fromJByte(jbyte pixel) {
// cast to unsigned char re-interprets values as 0-255
// cast to int will make intermediate calculations safer
return static_cast<int>(static_cast<unsigned char>(pixel));
}
inline jbyte fromInt(int pixel) {
if(pixel < 0)
pixel = 0;
if(pixel > 255)
pixel = 255;
return static_cast<jbyte>(static_cast<unsigned char>(pixel));
}
jbyte in = ...
int intermediate = fromJByte(in) + 30;
jbyte out = fromInt(intermediate);
I've found one difference between the two constructions that bit me pretty hard.
Let's say I have:
function MyClass(){
this.property1=[];
this.property2=new Array();
};
var MyObject1=new MyClass();
var MyObject2=new MyClass();
In real life, if I do this:
MyObject1.property1.push('a');
MyObject1.property2.push('b');
MyObject2.property1.push('c');
MyObject2.property2.push('d');
What I end up with is this:
MyObject1.property1=['a','c']
MyObject1.property2=['b']
MyObject2.property1=['a','c']
MyObject2.property2=['d']
I don't know what the language specification says is supposed to happen, but if I want my two objects to have unique property arrays in my objects, I have to use new Array()
.
SYNTAX
alter table table_name rename column old column name to new column name;
Example:
alter table library rename column cost to price;
just in case someone comes to this question, I have the easier version.
public static MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button);
Button b2 = (Button) findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.game);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.stop();
// mp.start();
}
});
}
A Mock is just testing behaviour, making sure certain methods are called. A Stub is a testable version (per se) of a particular object.
What do you mean an Apple way?
As described by the link I've given in comment, this
$('p[MyTag]').each(function(index) {
document.write(index + ': ' + $(this).text() + "<br>");});
works (playable example).
Multiple things can cause this, I didn't bother to check your entire repository, so I'm going out on a limb here.
First off, you could be missing an annotation (@Service or @Component) from the implementation of com.example.my.services.user.UserService
, if you're using annotations for configuration. If you're using (only) xml, you're probably missing the <bean>
-definition for the UserService-implementation.
If you're using annotations and the implementation is annotated correctly, check that the package where the implementation is located in is scanned (check your <context:component-scan base-package=
-value).
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
import os
def disk_stat(path):
disk = os.statvfs(path)
percent = (disk.f_blocks - disk.f_bfree) * 100 / (disk.f_blocks -disk.f_bfree + disk.f_bavail) + 1
return percent
print disk_stat('/')
print disk_stat('/data')
Did you override equals and hashCode in the Block class?
EDIT:
I assumed you mean it doesn't work at runtime... did you mean that or at compile time? If compile time what is the error message? If it crashes at runtime what is the stack trace? If it compiles and runs but doesn't work right then the equals and hashCode are the likely issue.
I error occor. When you are trying to access a file which is not in the director. Carefully check path in the view
$this->load->view('path');
default root path of view function is application/view .
I had the same error. I was trying to access files like this
$this->load->view('pages/view/file.php');
Actually I have the class Pages and function. I built the function with one argument to call the any files from the director application/view/pages . I was put the wrong path. The above path pages/view/files can be used when you are trying to access the controller. Not for the view. MVC gave a lot confusion. I had this problem. I just solve it. Thanks.
In your html :
<a href="javascript:void(0);" ng-click="go_back()">Go Back</a>
On your main controller :
$scope.go_back = function() {
$window.history.back();
};
When user click on Go Back link the controller function is called and it will go back to previous route.
For anyone else arriving at this question:
I was performing the most simple jQuery, trying to hide an element:
('#fileselection').hide();
and I was getting the same type of error, "Uncaught TypeError: Object #fileselection has no method 'hide'
Of course, now it is obvious, but I just left off the jQuery indicator '$'. The code should have been:
$('#fileselection').hide();
This fixes the no-brainer problem. I hope this helps someone save a few minutes debugging!
is null is the syntax I use for such things, when COALESCE is of no help.
Try:
if (@zipCode is null)
begin
([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)
end
else
begin
([Portal].[dbo].[Address].PostalCode=@zipCode )
end
Take a look at http://jqueryui.com/demos/effect/. It has an effect named pulsate that will do exactly what you want.
$("#trigger").change(function() {$("#div_you_want_to_blink").effect("pulsate");});
I like this light weight http request client called `unirest'
gem install unirest
usage:
response = Unirest.post "http://httpbin.org/post",
headers:{ "Accept" => "application/json" },
parameters:{ :age => 23, :foo => "bar" }
response.code # Status code
response.headers # Response headers
response.body # Parsed body
response.raw_body # Unparsed body
select Country_id,country_title from(
select Country_id,country_title,row_number() over (partition by country_title
order by Country_id ) rn from country)a
where rn=1;
Source link: http://www.codeblocq.com/2016/01/Untrack-files-already-added-to-git-repository-based-on-gitignore/
Let’s say you have already added/committed some files to your git repository and you then add them to your .gitignore; these files will still be present in your repository index. This article we will see how to get rid of them.
Before proceeding, make sure all your changes are committed, including your .gitignore file.
To clear your repo, use:
git rm -r --cached .
The rm
command can be unforgiving. If you wish to try what it does beforehand, add the -n
or --dry-run
flag to test things out.
git add .
git commit -m ".gitignore fix"
Your repository is clean :)
Push the changes to your remote to see the changes effective there as well.
you can test a color by writing the CSS inline like <div style="color:red";>...</div>
SELECT DISTINCT (t1.ProdId), t1.Quantity FROM Dummy t1 INNER JOIN
(SELECT ProdId, MAX(Quantity) as MaxQuantity FROM Dummy GROUP BY ProdId) t2
ON t1.ProdId = t2.ProdId
AND t1.Quantity = t2.MaxQuantity
ORDER BY t1.ProdId
this will give you the idea.
There seems to be an issue with select drop down controls not dynamically changing when the controls are dynamically created instead of being in a static HTML page.
In jQuery this solution worked for me.
$('#editAddMake').val(result.data.make_id);
$('#editAddMake').selectmenu('refresh');
Just as an addendum the first line of code without the second line, did actually work transparently in that, retrieving the selected index was correct after setting the index and if you actually clicked the control it would show the correct item but this didn't reflect in the top label of the control.
Hope this helps.
When you write a lambda expression, the argument list to the left of ->
can be either a parenthesized argument list (possibly empty), or a single identifier without any parentheses. But in the second form, the identifier cannot be declared with a type name. Thus:
this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));
is incorrect syntax; but
this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name));
is correct. Or:
this.stops.stream().filter(s -> s.getStation().getName().equals(name));
is also correct if the compiler has enough information to figure out the types.
Using jQuery you can track the window resize and change the width of your canvas using jQuery as well.
Something like that
$( window ).resize(function() {_x000D_
$("#myCanvas").width($( window ).width())_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
_x000D_
From SQL Server 2008 Setup, you have to select "Client Tools Connectivity" to install SQL Server Configuration Manager.
In R2013b or later you can use a table:
>> table = readtable('myfile.txt','Delimiter',';','ReadVariableNames',false)
>> table =
Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10
____ _____ _____ _____ _____ __________ __________ ________ ____ _____
4 'abc' 'def' 'ghj' 'klm' '' '' '' NaN NaN
NaN '' '' '' '' 'Test' 'text' '0xFF' NaN NaN
NaN '' '' '' '' 'asdfhsdf' 'dsafdsag' '0x0F0F' NaN NaN
Here is more info.
Take a look at cavaj.
Here's the script i used on linux for an instance Nexus 5 API 24 x86 WITHOUT GoogleApis.
#!/bin/sh
~/Android/Sdk/tools/emulator @A24x86 -no-boot-anim -writable-system & #where A24x86 is the name i gave to my instance
~/Android/Sdk/platform-tools/adb wait-for-device
~/Android/Sdk/platform-tools/adb root
~/Android/Sdk/platform-tools/adb shell stop
~/Android/Sdk/platform-tools/adb remount
~/Android/Sdk/platform-tools/adb push ~/gapps/PrebuiltGmsCore.apk /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk
~/Android/Sdk/platform-tools/adb push ~/gapps/GoogleServicesFramework.apk /system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk
~/Android/Sdk/platform-tools/adb push ~/gapps/GoogleLoginService.apk /system/priv-app/GoogleLoginService/GoogleLoginService.apk
~/Android/Sdk/platform-tools/adb push ~/gapps/Phonesky.apk /system/priv-app/Phonesky/Phonesky.apk
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/PrebuiltGmsCore /system/priv-app/GoogleServicesFramework"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/GoogleLoginService /system/priv-app/Phonesky"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/GoogleLoginService/GoogleLoginService.apk"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/Phonesky/Phonesky.apk"
~/Android/Sdk/platform-tools/adb shell start
This one did it for me.
IMPORTANT: in order to stop the app from crashing remember to grant google play services location permissions.
Configuration->Apps->Config(Gear icon)->App permissions->Location->(Top right menú)->Show system->Enable Google Play services
I'm not 100% sure what your NonIntersect method is supposed to do (regarding set theory) - is it
B \ A (everything from B that does not occur in A)?
If yes, then you should be able to use the Except operation (B.Except(A)).
Here's a solution that doesn't require rethinking the HTML structure or any additional CSS trickery involving padding:
<html style="height:100%;">
...
<body class="d-flex flex-column h-100">
...
<main class="flex-grow-1">...</main>
<footer>...</footer>
</body>
...
</html>
Note that this solution allows for footers with flexible heights, which particularly comes in handy when designing pages for multiple screen sizes with content wrapping when shrunk.
style="height:100%;"
makes the <html>
tag take the whole space of the document.d-flex
sets display:flex
to our <body>
tag.flex-column
sets flex-direction:column
to our <body>
tag. Its children (<header>
, <main>
, <footer>
and any other direct child) are now aligned vertically.h-100
sets height:100%
to our <body>
tag, meaning it will cover the entire screen vertically.flex-grow-1
sets flex-grow:1
to our <main>
, effectively instructing it to fill any remaining vertical space, thus amounting to the 100% vertical height we set before on our <body>
tag.Working demo here: https://codepen.io/maxencemaire/pen/VwvyRQB
See https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for more information on flexbox.
add and remove text input element dynamically any one can use this this will work Type of Contact Balance Fund Equity Fund Allocation Allocation % is required! Remove Add Contact
userForm: FormGroup;
public contactList: FormArray;
// returns all form groups under contacts
get contactFormGroup() {
return this.userForm.get('funds') as FormArray;
}
ngOnInit() {
this.submitUser();
}
constructor(public fb: FormBuilder,private router: Router,private ngZone: NgZone,private userApi: ApiService) { }
// contact formgroup
createContact(): FormGroup {
return this.fb.group({
fundName: ['', Validators.compose([Validators.required])], // i.e Email, Phone
allocation: [null, Validators.compose([Validators.required])]
});
}
// triggered to change validation of value field type
changedFieldType(index) {
let validators = null;
validators = Validators.compose([
Validators.required,
Validators.pattern(new RegExp('^\\+[0-9]?()[0-9](\\d[0-9]{9})$')) // pattern for validating international phone number
]);
this.getContactsFormGroup(index).controls['allocation'].setValidators(
validators
);
this.getContactsFormGroup(index).controls['allocation'].updateValueAndValidity();
}
// get the formgroup under contacts form array
getContactsFormGroup(index): FormGroup {
// this.contactList = this.form.get('contacts') as FormArray;
const formGroup = this.contactList.controls[index] as FormGroup;
return formGroup;
}
submitUser() {
this.userForm = this.fb.group({
first_name: ['', [Validators.required]],
last_name: [''],
email: ['', [Validators.required]],
company_name: ['', [Validators.required]],
license_start_date: ['', [Validators.required]],
license_end_date: ['', [Validators.required]],
gender: ['Male'],
funds: this.fb.array([this.createContact()])
})
this.contactList = this.userForm.get('funds') as FormArray;
}
addContact() {
this.contactList.push(this.createContact());
}
removeContact(index) {
this.contactList.removeAt(index);
}
Starting with Oracle 12c there is support for Identity columns in one of two ways:
Sequence + Table - In this solution you still create a sequence as you normally would, then you use the following DDL:
CREATE TABLE MyTable (ID NUMBER DEFAULT MyTable_Seq.NEXTVAL, ...)
Table Only - In this solution no sequence is explicitly specified. You would use the following DDL:
CREATE TABLE MyTable (ID NUMBER GENERATED AS IDENTITY, ...)
If you use the first way it is backward compatible with the existing way of doing things. The second is a little more straightforward and is more inline with the rest of the RDMS systems out there.
If you are using the Eclipse ADT plugin for your development, open AndroidManifest.xml
in the Android Manifest Editor (should be the default action for opening AndroidManifest.xml
from the project files list).
Afterwards, select the Permissions
tab along the bottom of the editor (Manifest - Application - Permissions - Instrumentation - AndroidManifest.xml
), then click Add...
a Uses Permission
and select the desired permission from the dropdown on the right, or just copy-paste in the necessary one (such as the android.permission.INTERNET
permission you required).
While I have understood the how and when, I have never understood the why. In case it helps anyone with a background in a language like C++, you want to read this very carefully.
For the lazy, we use the visitor pattern because "while virtual functions are dispatched dynamically in C++, function overloading is done statically".
Or, put another way, to make sure that CollideWith(ApolloSpacecraft&) is called when you pass in a SpaceShip reference that is actually bound to an ApolloSpacecraft object.
class SpaceShip {};
class ApolloSpacecraft : public SpaceShip {};
class ExplodingAsteroid : public Asteroid {
public:
virtual void CollideWith(SpaceShip&) {
cout << "ExplodingAsteroid hit a SpaceShip" << endl;
}
virtual void CollideWith(ApolloSpacecraft&) {
cout << "ExplodingAsteroid hit an ApolloSpacecraft" << endl;
}
}
I had the same issue and I tried everything possible...some of those are
1) Nuking temp files in Temporary ASP.NET Folders in bin and obj folders.
2) Unchecking the Optimize code and Enable my code
3) Navigating and trying to manually load the symbols from module windows.
4) Checking the build flag in the properties of solution. ........
And the list goes on.. I spent like one day on this but what finally worked for me actually was... I knew that the symbols for my project was not being loaded and i could not see any modules with my project name in the modules window either...
so the issue was my symbols were being brought from virtual directory path of the project... and it was mapped to the virtual directory of some other project instead... the web project that was supposed to load in the modules was not there Following are the steps i followed..
Here I'm just doing the difference between today, and a CREATED_DATE
DATE
field in a table, which obviously is a date in the past:
SELECT
((FLOOR(ABS(MONTHS_BETWEEN(CREATED_DATE, SYSDATE))) / 12) * 12) || ' months, ' AS MONTHS,
-- we take total days - years(as days) - months(as days) to get remaining days
FLOOR((SYSDATE - CREATED_DATE) - -- total days
(FLOOR((SYSDATE - CREATED_DATE)/365)*12)*(365/12) - -- years, as days
-- this is total months - years (as months), to get number of months,
-- then multiplied by 30.416667 to get months as days (and remove it from total days)
FLOOR(((SYSDATE - CREATED_DATE)/365)*12 - (FLOOR((SYSDATE - CREATED_DATE)/365)*12)) * (365/12))
|| ' days ' AS DAYS
FROM MyTable
I use (365/12), or 30.416667, as my conversion factor because I'm using total days and removing years and months (as days) to get the remainder number of days. It was good enough for my purposes, anyway.
If I were you I would install the Java SE SDK. Once it is installed make sure you have the JAVA_HOME environment variable set and add the %JAVA_HOME%\bin dir to your path.
There's a few different ways you can tackle this one.
You can set a counter before the foreach() and then just iterate through which is the easiest approach.
$counter = 0;
foreach ($Contents as $item) {
$counter++;
$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
Mal's answer was the only one that worked for me (maybe jqueryUI has changed), here is a variant for dealing with a range:
$( "#slider-range" ).slider('values',0,lowerValue);
$( "#slider-range" ).slider('values',1,upperValue);
$( "#slider-range" ).slider("refresh");
Python 3.x makes a clear distinction between the types:
str
= '...'
literals = a sequence of Unicode characters (Latin-1, UCS-2 or UCS-4, depending on the widest character in the string)bytes
= b'...'
literals = a sequence of octets (integers between 0 and 255)If you're familiar with:
str
as String
and bytes
as byte[]
;str
as NVARCHAR
and bytes
as BINARY
or BLOB
;str
as REG_SZ
and bytes
as REG_BINARY
.If you're familiar with C(++), then forget everything you've learned about char
and strings, because a character is not a byte. That idea is long obsolete.
You use str
when you want to represent text.
print('???? ????')
You use bytes
when you want to represent low-level binary data like structs.
NaN = struct.unpack('>d', b'\xff\xf8\x00\x00\x00\x00\x00\x00')[0]
You can encode a str
to a bytes
object.
>>> '\uFEFF'.encode('UTF-8')
b'\xef\xbb\xbf'
And you can decode a bytes
into a str
.
>>> b'\xE2\x82\xAC'.decode('UTF-8')
'€'
But you can't freely mix the two types.
>>> b'\xEF\xBB\xBF' + 'Text with a UTF-8 BOM'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't concat bytes to str
The b'...'
notation is somewhat confusing in that it allows the bytes 0x01-0x7F to be specified with ASCII characters instead of hex numbers.
>>> b'A' == b'\x41'
True
But I must emphasize, a character is not a byte.
>>> 'A' == b'A'
False
Pre-3.0 versions of Python lacked this kind of distinction between text and binary data. Instead, there was:
unicode
= u'...'
literals = sequence of Unicode characters = 3.x str
str
= '...'
literals = sequences of confounded bytes/characters
struct.pack
output.In order to ease the 2.x-to-3.x transition, the b'...'
literal syntax was backported to Python 2.6, in order to allow distinguishing binary strings (which should be bytes
in 3.x) from text strings (which should be str
in 3.x). The b
prefix does nothing in 2.x, but tells the 2to3
script not to convert it to a Unicode string in 3.x.
So yes, b'...'
literals in Python have the same purpose that they do in PHP.
Also, just out of curiosity, are there more symbols than the b and u that do other things?
The r
prefix creates a raw string (e.g., r'\t'
is a backslash + t
instead of a tab), and triple quotes '''...'''
or """..."""
allow multi-line string literals.
see here
The consumable media types of the mapped request, narrowing the primary mapping.
the producer is used to narrow the primary mapping, you send request should specify the exact header to match it.
This function returns an array regardless of the size of the range.
Ranges will return an array unless the range is only 1 cell and then it returns a single value instead. This function will turn the single value into an array (1 based, the same as the array's returned by ranges)
This answer improves on previous answers as it will return an array from a range no matter what the size. It is also more efficient that other answers as it will return the array generated by the range if possible. Works with single dimension and multi-dimensional arrays
The function works by trying to find the upper bounds of the array. If that fails then it must be a single value so we'll create an array and assign the value to it.
Public Function RangeToArray(inputRange As Range) As Variant()
Dim size As Integer
Dim inputValue As Variant, outputArray() As Variant
' inputValue will either be an variant array for ranges with more than 1 cell
' or a single variant value for range will only 1 cell
inputValue = inputRange
On Error Resume Next
size = UBound(inputValue)
If Err.Number = 0 Then
RangeToArray = inputValue
Else
On Error GoTo 0
ReDim outputArray(1 To 1, 1 to 1)
outputArray(1,1) = inputValue
RangeToArray = outputArray
End If
On Error GoTo 0
End Function
Using jquery:
<form action="upload" enctype="multipart/form-data" method="post">
Upload image:
<input id="image-file" type="file" name="file" />
<input type="submit" value="Upload" />
<script type="text/javascript">
$('#image-file').bind('change', function() {
alert('This file size is: ' + this.files[0].size/1024/1024 + "MiB");
});
</script>
</form>
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
You should write in file:
<script>
//write your JavaScript code here
</script>
save it with .html extension and open with browser.
For example:
// this is test.html
<script>
alert("Hello");
var a = 5;
function incr(arg){
arg++;
return arg;
}
alert(a);
</script>
The solution with guideline works only for this particular case with single line EditText. To make it work for multiline EditText you should use "packed" chain.
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<android.support.design.widget.TextInputLayout
android:id="@+id/client_id_input_layout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="@+id/authenticate"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/login_client_id"
android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="@+id/authenticate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="@string/login_auth"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="@id/client_id_input_layout"
app:layout_constraintRight_toRightOf="@id/client_id_input_layout"
app:layout_constraintTop_toBottomOf="@id/client_id_input_layout" />
</android.support.constraint.ConstraintLayout>
Here's how it looks:
You can read more about using chains in following posts:
DateTime.Now.ToString("yyyyMMddHHmmss"); // case sensitive
If you are really concerned about the execution speed of your apply function and you have a huge dataset to work on, you could use swifter to make faster execution, here is an example for swifter on pandas dataframe:
import pandas as pd
import swifter
def fnc(m):
return m*3+4
df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})
# apply a self created function to a single column in pandas
df["y"] = df.m.swifter.apply(fnc)
This will enable your all CPU cores to compute the result hence it will be much faster than normal apply functions. Try and let me know if it become useful for you.
this is the most general solution
$('body').on('shown.bs.modal', '.modal', function () {
$(this).find(":input:not(:button):visible:enabled:not([readonly]):first").focus();
});
To add to the above points. Using ArrayList
in 64bit operating system takes 2x memory than using in the 32bit operating system. Meanwhile, generic list List<T>
will use much low memory than the ArrayList
.
for example if we use a ArrayList
of 19MB in 32-bit it would take 39MB in the 64-bit. But if you have a generic list List<int>
of 8MB in 32-bit it would take only 8.1MB in 64-bit, which is a whooping 481% difference when compared to ArrayList.
Source: ArrayList’s vs. generic List for primitive types and 64-bits
The compiler doesn't know that spe_context_ptr_t is a type. Check that the appropriate typedef is in scope when this code is compiled. You may have forgotten to include the appropriate header file.
I solved this by:
mysql.server stop
mysqld_safe --skip-grant-tables
mysql -u root
UPDATE mysql.user SET authentication_string=null WHERE User='root';
, then FLUSH PRIVILEGES;
and then exit with exit;
mysql.server stop
and then start the normal one; mysql.server start
Now you can set your new password with
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'yourpasswd';
[INFO] BUILD SUCCESS
Anyway, it works for me:)
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8
<% %>
Executes the ruby code within the brackets.
<%= %>
Prints something into erb file.
<%== %>
Equivalent to <%= raw %>
. Prints something verbatim (i.e. w/o escaping) into erb file. (Taken from Ruby on Rails Guides.)
<% -%>
Avoids line break after expression.
<%# %>
Comments out code within brackets; not sent to client (as opposed to HTML comments).
Visit Ruby Doc for more infos about ERB.
I had this problem. I searched the internet, took all advices, changes configurations, but the problem is still there. Finally with the help of the server administrator, he found that the problem lies in MySQL database column definition. one of the columns in the a table was assigned to 'Longtext' which leads to allocate 4,294,967,295 bites of memory. It seems working OK if you don't use MySqli prepare statement, but once you use prepare statement, it tries to allocate that amount of memory. I changed the column type to Mediumtext which needs 16,777,215 bites of memory space. The problem is gone. Hope this help.
A solution very simple, but you have to know the index of the original position and the index of the new position:
list1[index1],list1[index2]=list1[index2],list1[index1]
I figured everyone looking for this answer was probably just trying to avoid writing out the whole if/else statements, so I wrote it out for you so you can copy/paste. The only caveat with this function is that it goes on the actual number of the month, not a 0-indexed number, so January = 1, not 0.
function getMonthString($m){
if($m==1){
return "January";
}else if($m==2){
return "February";
}else if($m==3){
return "March";
}else if($m==4){
return "April";
}else if($m==5){
return "May";
}else if($m==6){
return "June";
}else if($m==7){
return "July";
}else if($m==8){
return "August";
}else if($m==9){
return "September";
}else if($m==10){
return "October";
}else if($m==11){
return "November";
}else if($m==12){
return "December";
}
}
Actually there is a more simple solution (only on Mac version). Just four steps:
ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. All instances of ArgumentException should carry a meaningful error message describing the invalid argument, as well as the expected range of values for the argument.
A few subclasses also exist for specific types of invalidity. The link has summaries of the subtypes and when they should apply.
This is my 2 cents based on Grax's answer, but with two parameters required for a generic method.
Assume your method is defined as follows in an Helpers class:
public class Helpers
{
public static U ConvertCsvDataToCollection<U, T>(string csvData)
where U : ObservableCollection<T>
{
//transform code here
}
}
In my case, U type is always an observable collection storing object of type T.
As I have my types predefined, I first create the "dummy" objects that represent the observable collection (U) and the object stored in it (T) and that will be used below to get their type when calling the Make
object myCollection = Activator.CreateInstance(collectionType);
object myoObject = Activator.CreateInstance(objectType);
Then call the GetMethod to find your Generic function:
MethodInfo method = typeof(Helpers).
GetMethod("ConvertCsvDataToCollection");
So far, the above call is pretty much identical as to what was explained above but with a small difference when you need have to pass multiple parameters to it.
You need to pass an Type[] array to the MakeGenericMethod function that contains the "dummy" objects' types that were create above:
MethodInfo generic = method.MakeGenericMethod(
new Type[] {
myCollection.GetType(),
myObject.GetType()
});
Once that's done, you need to call the Invoke method as mentioned above.
generic.Invoke(null, new object[] { csvData });
And you're done. Works a charm!
UPDATE:
As @Bevan highlighted, I do not need to create an array when calling the MakeGenericMethod function as it takes in params and I do not need to create an object in order to get the types as I can just pass the types directly to this function. In my case, since I have the types predefined in another class, I simply changed my code to:
object myCollection = null;
MethodInfo method = typeof(Helpers).
GetMethod("ConvertCsvDataToCollection");
MethodInfo generic = method.MakeGenericMethod(
myClassInfo.CollectionType,
myClassInfo.ObjectType
);
myCollection = generic.Invoke(null, new object[] { csvData });
myClassInfo contains 2 properties of type Type
which I set at run time based on an enum value passed to the constructor and will provide me with the relevant types which I then use in the MakeGenericMethod.
Thanks again for highlighting this @Bevan.
This error is usually observed when your machine is low on disk space. Steps to be followed to avoid this error message
Resetting the read-only index block on the index:
$ curl -X PUT -H "Content-Type: application/json" http://127.0.0.1:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
Response
${"acknowledged":true}
Updating the low watermark to at least 50 gigabytes free, a high watermark of at least 20 gigabytes free, and a flood stage watermark of 10 gigabytes free, and updating the information about the cluster every minute
Request
$curl -X PUT "http://127.0.0.1:9200/_cluster/settings?pretty" -H 'Content-Type: application/json' -d' { "transient": { "cluster.routing.allocation.disk.watermark.low": "50gb", "cluster.routing.allocation.disk.watermark.high": "20gb", "cluster.routing.allocation.disk.watermark.flood_stage": "10gb", "cluster.info.update.interval": "1m"}}'
Response
${
"acknowledged" : true,
"persistent" : { },
"transient" : {
"cluster" : {
"routing" : {
"allocation" : {
"disk" : {
"watermark" : {
"low" : "50gb",
"flood_stage" : "10gb",
"high" : "20gb"
}
}
}
},
"info" : {"update" : {"interval" : "1m"}}}}}
After running these two commands, you must run the first command again so that the index does not go again into read-only mode
I would end it with NULL
. Why? Because you can't do either of these:
array[index] == '\0'
array[index] == "\0"
The first one is comparing a char *
to a char
, which is not what you want. You would have to do this:
array[index][0] == '\0'
The second one doesn't even work. You're comparing a char *
to a char *
, yes, but this comparison is meaningless. It passes if the two pointers point to the same piece of memory. You can't use ==
to compare two strings, you have to use the strcmp()
function, because C has no built-in support for strings outside of a few (and I mean few) syntactic niceties. Whereas the following:
array[index] == NULL
Works just fine and conveys your point.
I always prefer let
to an instance variable for a couple of reasons:
nil
, which can lead to subtle bugs and false positives. Since let
creates a method, you'll get a NameError
when you misspell it, which I find preferable. It makes it easier to refactor specs, too.before(:each)
hook will run before each example, even if the example doesn't use any of the instance variables defined in the hook. This isn't usually a big deal, but if the setup of the instance variable takes a long time, then you're wasting cycles. For the method defined by let
, the initialization code only runs if the example calls it.@
).let
and keeping my it
block nice and short.A related link can be found here: http://www.betterspecs.org/#let
It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/
is the same as /../
, and that will get normalized away.
(This is a combination of an answer by bobince and a comment by slowpoison.)
Try Using this query for searching special character records
SELECT *
FROM tableName
WHERE fieldName REGEXP '[^a-zA-Z0-9@:. \'\-`,\&]'
Updated to Swift 3:
Instead of the flow layout, I prefer using custom layout for specific column number and row number. Because:
Normal cell and Header cell: (Add UILabel as a IBOutlet to your xib):
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = UIColor.black
label.textColor = UIColor.white
}
}
class CollectionViewHeadCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = UIColor.darkGray
label.textColor = UIColor.white
}
}
Custom layout:
let cellHeight: CGFloat = 100
let cellWidth: CGFloat = 100
class CustomCollectionViewLayout: UICollectionViewLayout {
private var numberOfColumns: Int!
private var numberOfRows: Int!
// It is two dimension array of itemAttributes
private var itemAttributes = [[UICollectionViewLayoutAttributes]]()
// It is one dimension of itemAttributes
private var cache = [UICollectionViewLayoutAttributes]()
override func prepare() {
if self.cache.isEmpty {
self.numberOfColumns = self.collectionView?.numberOfItems(inSection: 0)
self.numberOfRows = self.collectionView?.numberOfSections
// Dynamically change cellWidth if total cell width is smaller than whole bounds
/* if (self.collectionView?.bounds.size.width)!/CGFloat(self.numberOfColumns) > cellWidth {
self.cellWidth = (self.collectionView?.bounds.size.width)!/CGFloat(self.numberOfColumns)
}
*/
for row in 0..<self.numberOfRows {
var row_temp = [UICollectionViewLayoutAttributes]()
for column in 0..<self.numberOfColumns {
let indexPath = NSIndexPath(item: column, section: row)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath as IndexPath)
attributes.frame = CGRect(x: cellWidth*CGFloat(column), y: cellHeight*CGFloat(row), width: cellWidth, height: cellHeight)
row_temp.append(attributes)
self.cache.append(attributes)
}
self.itemAttributes.append(row_temp)
}
}
}
override var collectionViewContentSize: CGSize {
return CGSize(width: CGFloat(self.numberOfColumns)*cellWidth, height: CGFloat(self.numberOfRows)*cellHeight)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in cache {
if attributes.frame.intersects(rect) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
}
CollectionView:
let CellIdentifier = "CellIdentifier"
let HeadCellIdentifier = "HeadCellIdentifier"
class CollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource {
init() {
let layout = CustomCollectionViewLayout()
super.init(frame: CGRect.zero, collectionViewLayout: layout)
self.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: CellIdentifier)
self.register(UINib(nibName: "CollectionViewHeadCell", bundle: nil), forCellWithReuseIdentifier: HeadCellIdentifier)
self.isDirectionalLockEnabled = true
self.dataSource = self
self.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateCollectionView() {
DispatchQueue.main.async {
self.reloadData()
}
}
// MARK: CollectionView datasource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 20
}
override func numberOfItems(inSection section: Int) -> Int {
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let column = (indexPath as NSIndexPath).row
let row = (indexPath as NSIndexPath).section
if column == 0 {
let cell : CollectionViewHeadCell = collectionView.dequeueReusableCell(withReuseIdentifier: HeadCellIdentifier, for: indexPath) as! CollectionViewHeadCell
cell.label.text = "\(row)"
return cell
}
else if row == 0 {
let cell : CollectionViewHeadCell = collectionView.dequeueReusableCell(withReuseIdentifier: HeadCellIdentifier, for: indexPath) as! CollectionViewHeadCell
cell.label.text = "\(column)"
return cell
}
else {
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier, for: indexPath) as! CollectionViewCell
cell.label.text = String(format: "%d", arguments: [indexPath.section*indexPath.row])
return cell
}
}
// MARK: CollectionView delegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let column = (indexPath as NSIndexPath).row
let row = (indexPath as NSIndexPath).section
print("\(column) \(row)")
}
}
Use CollectionView from ViewController:
class ViewController: UIViewController {
let collectionView = CollectionView()
override func viewDidLoad() {
collectionView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(collectionView)
self.view.backgroundColor = UIColor.red
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[collectionView]|", options: [], metrics: nil, views: ["collectionView": collectionView]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[collectionView]|", options: [], metrics: nil, views: ["collectionView": collectionView]))
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
collectionView.updateCollectionView()
}
}
Finally you can have fancy CollectionView!
In addition to the semaphore technique covered exhaustively in other answers, we can now use XCTest in Xcode 6 to perform asynchronous tests via XCTestExpectation
. This eliminates the need for semaphores when testing asynchronous code. For example:
- (void)testDataTask
{
XCTestExpectation *expectation = [self expectationWithDescription:@"asynchronous request"];
NSURL *url = [NSURL URLWithString:@"http://www.apple.com"];
NSURLSessionTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
XCTAssertNil(error, @"dataTaskWithURL error %@", error);
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *) response statusCode];
XCTAssertEqual(statusCode, 200, @"status code was not 200; was %d", statusCode);
}
XCTAssert(data, @"data nil");
// do additional tests on the contents of the `data` object here, if you want
// when all done, Fulfill the expectation
[expectation fulfill];
}];
[task resume];
[self waitForExpectationsWithTimeout:10.0 handler:nil];
}
For the sake of future readers, while the dispatch semaphore technique is a wonderful technique when absolutely needed, I must confess that I see too many new developers, unfamiliar with good asynchronous programming patterns, gravitate too quickly to semaphores as a general mechanism for making asynchronous routines behave synchronously. Worse I've seen many of them use this semaphore technique from the main queue (and we should never block the main queue in production apps).
I know this isn't the case here (when this question was posted, there wasn't a nice tool like XCTestExpectation
; also, in these testing suites, we must ensure the test does not finish until the asynchronous call is done). This is one of those rare situations where the semaphore technique for blocking the main thread might be necessary.
So with my apologies to the author of this original question, for whom the semaphore technique is sound, I write this warning to all of those new developers who see this semaphore technique and consider applying it in their code as a general approach for dealing with asynchronous methods: Be forewarned that nine times out of ten, the semaphore technique is not the best approach when encounting asynchronous operations. Instead, familiarize yourself with completion block/closure patterns, as well as delegate-protocol patterns and notifications. These are often much better ways of dealing with asynchronous tasks, rather than using semaphores to make them behave synchronously. Usually there are good reasons that asynchronous tasks were designed to behave asynchronously, so use the right asynchronous pattern rather than trying to make them behave synchronously.
The following works:
(
echo "From: ${from}";
echo "To: ${to}";
echo "Subject: ${subject}";
echo "Content-Type: text/html";
echo "MIME-Version: 1.0";
echo "";
echo "${message}";
) | sendmail -t
For troubleshooting msmtp, which is compatible with sendmail
, see:
I just wanted to share that I combined this with my script to move the div so that it always stays in view:
$("#accordion").on('click', '.subLink', function(){
var url = $(this).attr('src');
updateFrame(url);
scrollIntoView();
});
$(window).scroll(function(){
changePos();
});
function scrollIntoView()
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $("#divPos").offset().top;
var elemBottom = elemTop + $("#divPos").height();
if (elemTop < docViewTop){
$("#divPos").offset({top:docViewTop});
}
}
function changePos(){
var scrTop = $(window).scrollTop();
var frmHeight = $("#divPos").height()
if ((scrTop < 200) || (frmHeight > 800)){
$("#divPos").attr("style","position:absolute;");
}else{
$("#divPos").attr("style","position:fixed;top:5px;");
}
}
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server
argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)
#include <sys/types.h>
library
is an object, not an array. You push things onto arrays. Unlike PHP, Javascript makes a distinction.
Your code tries to make a string that looks like the source code for a key-value pair, and then "push" it onto the object. That's not even close to how it works.
What you want to do is add a new key-value pair to the object, where the key is the title and the value is another object. That looks like this:
library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds};
"JSON object" is a vague term. You must be careful to distinguish between an actual object in memory in your program, and a fragment of text that is in JSON format.
Wrapping your list of objects with another object containing a property that matches the name of the parameter which is expected by the MVC controller works. The important bit being the wrapper around the object list.
$(document).ready(function () {
var employeeList = [
{ id: 1, name: 'Bob' },
{ id: 2, name: 'John' },
{ id: 3, name: 'Tom' }
];
var Employees = {
EmployeeList: employeeList
}
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Employees/Process',
data: Employees,
success: function () {
$('#InfoPanel').html('It worked!');
},
failure: function (response) {
$('#InfoPanel').html(response);
}
});
});
public void Process(List<Employee> EmployeeList)
{
var emps = EmployeeList;
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
This is how i solve it.:
items: [
{ title: 'Dashboard', icon: require('@/assets/icons/sidebar/dashboard.svg') },
{ title: 'Projects', icon: require('@/assets/icons/sidebar/projects.svg') },
{ title: 'Clients', icon: require('@/assets/icons/sidebar/clients.svg') },
],
And on the template part:
<img :src="item.icon" />
a <div> is a logical division in your content, semantically this would be my first choice if I wanted to group the heading with the list:
<div class="mydiv">
<h3>The heading</h3>
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>
then you can use the following css to style everything together as one unit
.mydiv{}
.mydiv h3{}
.mydiv ul{}
.mydiv ul li{}
etc...
Maybe you mean like this? I like to make an object and use Format-Table:
> $array = @()
> $object = New-Object -TypeName PSObject
> $object | Add-Member -Name 'Name' -MemberType Noteproperty -Value 'Joe'
> $object | Add-Member -Name 'Age' -MemberType Noteproperty -Value 32
> $object | Add-Member -Name 'Info' -MemberType Noteproperty -Value 'something about him'
> $array += $object
> $array | Format-Table
Name Age Info
---- --- ----
Joe 32 something about him
This will put all objects you have in the array in columns according to their properties.
Tip: Using -auto
sizes the table better
> $array | Format-Table -Auto
Name Age Info
---- --- ----
Joe 32 something about him
You can also specify which properties you want in the table. Just separate each property name with a comma:
> $array | Format-Table Name, Age -Auto
Name Age
---- ---
Joe 32
All you need to do is run
pip install /opt/mypackage
and pip will search /opt/mypackage
for a setup.py
, build a wheel, then install it.
The problem with using the -e
flag for pip install
as suggested in the comments and this answer is that this requires that the original source directory stay in place for as long as you want to use the module. It's great if you're a developer working on the source, but if you're just trying to install a package, it's the wrong choice.
Alternatively, you don't even need to download the repo from Github at all. pip supports installing directly from git repos using a variety of protocols including HTTP, HTTPS, and SSH, among others. See the docs I linked to for examples.
For Java 1.6 and lower, I believe the safest and cleanest API for this is Guava's Files.move.
Example:
File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());
The first line makes sure that the location of the new file is the same directory, i.e. the parent directory of the old file.
EDIT: I wrote this before I started using Java 7, which introduced a very similar approach. So if you're using Java 7+, you should see and upvote kr37's answer.
There should be svn
utility on you box, if installed:
$ svn checkout http://example.com/svn/somerepo somerepo
This will check out a working copy from a specified repository to a directory somerepo
on our file system.
You may want to print commands, supported by this utility:
$ svn help
uname -a
output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm
or the following command:
$ sudo yum install subversion
The OP says, for unknown reasons, "I prefer it without an arraylist or list."
If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int
or Integer
), then you can use one of the NIO Buffer classes like java.nio.IntBuffer
. These act a lot like StringBuffer
does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.
Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate()
a larger one and use put()
to dump the old buffer into the new one.
If it's not a primitive, you should probably just use List
, or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.
string[] coleccion = Directory.GetFiles(inputPath)
.Select(x => new FileInfo(x).Name)
.ToArray();
To determine if a String contains an upper case and a lower case char, you can use the following:
boolean hasUppercase = !password.equals(password.toLowerCase());
boolean hasLowercase = !password.equals(password.toUpperCase());
This allows you to check:
if(!hasUppercase)System.out.println("Must have an uppercase Character");
if(!hasLowercase)System.out.println("Must have a lowercase Character");
Essentially, this works by checking if the String is equal to its entirely lowercase, or uppercase equivalent. If this is not true, then there must be at least one character that is uppercase or lowercase.
As for your other conditions, these can be satisfied in a similar way:
boolean isAtLeast8 = password.length() >= 8;//Checks for at least 8 characters
boolean hasSpecial = !password.matches("[A-Za-z0-9 ]*");//Checks at least one char is not alpha numeric
boolean noConditions = !(password.contains("AND") || password.contains("NOT"));//Check that it doesn't contain AND or NOT
With suitable error messages as above.
You can also pull the latest commit and just undo until the commit you desire:
git pull origin master
git reset --hard HEAD~1
Replace master
with your desired branch.
Use git log to see to which commit you would like to revert:
git log
Personally, this has worked for me better.
Basically, what this does is pulls the latest commit, and you manually revert commits one by one. Use git log in order to see commit history.
Good points: Works as advertised. You don't have to use commit hash or pull unneeded branches.
Bad points: You need to revert commits on by one.
WARNING: Commit/stash all your local changes, because with --hard
you are going to lose them. Use at your own risk!
Since this is the first result of google this error, I want to remind that simply click the bottom window error message blue link "Fix Gradle wrapper and re-import project Gradle settings" will auto fix for you now.
Try to remove the .idea
folder and .gradle
folder, then click Sync Project with Gradle Files
, when the process finished, try to run app again.
Hope it works.
Here is a complete example
#include <thread>
#include <iostream>
class Wrapper {
public:
void member1() {
std::cout << "i am member1" << std::endl;
}
void member2(const char *arg1, unsigned arg2) {
std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
}
std::thread member1Thread() {
return std::thread([=] { member1(); });
}
std::thread member2Thread(const char *arg1, unsigned arg2) {
return std::thread([=] { member2(arg1, arg2); });
}
};
int main(int argc, char **argv) {
Wrapper *w = new Wrapper();
std::thread tw1 = w->member1Thread();
std::thread tw2 = w->member2Thread("hello", 100);
tw1.join();
tw2.join();
return 0;
}
Compiling with g++ produces the following result
g++ -Wall -std=c++11 hello.cc -o hello -pthread
i am member1
i am member2 and my first arg is (hello) and second arg is (100)
Calendar now = new Calendar() // or new GregorianCalendar(), or whatever flavor you need
now.MONTH now.HOUR
etc.
To add to what others have said, you could also create an alias in your .bashrc or .bash_aliases file:
alias svnlog='svn log -l 30 | less'
or whatever you want as your default
You can use ConnectivityManager.
val cm = getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
val dialogBuilder = AlertDialog.Builder(this)
if (activeNetwork!=null) // Some network is available
{
if (activeNetwork.isConnected) { // Network is connected to internet
}else{ // Network is NOT connected to internet
}
In my case adding PHP directory to PATH in user environment didn't work. After some testing I've found that it should be added to system PATH (I don't know what's the name of this part of system setting windows, 'couse I have Polish Windows).
I know you said you don't care about how secure it is, but if you chose DES you might as well take AES it is the more up-to-date encryption method.
public ActionResult Index(int id,string value)
This function get values form URL After that you can use below function
Request.RawUrl
- Return complete URL of Current page
RouteData.Values
- Return Collection of Values of URL
Request.Params
- Return Name Value Collections
This is an sample restclient class
public class RestClient
{
public enum RequestMethod
{
GET,
POST
}
public int responseCode=0;
public String message;
public String response;
public void Execute(RequestMethod method,String url,ArrayList<NameValuePair> headers,ArrayList<NameValuePair> params) throws Exception
{
switch (method)
{
case GET:
{
// add parameters
String combinedParams = "";
if (params!=null)
{
combinedParams += "?";
for (NameValuePair p : params)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
if (combinedParams.length() > 1)
combinedParams += "&" + paramString;
else
combinedParams += paramString;
}
}
HttpGet request = new HttpGet(url + combinedParams);
// add headers
if (headers!=null)
{
headers=addCommonHeaderField(headers);
for (NameValuePair h : headers)
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
// add headers
if (headers!=null)
{
headers=addCommonHeaderField(headers);
for (NameValuePair h : headers)
request.addHeader(h.getName(), h.getValue());
}
if (params!=null)
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
executeRequest(request, url);
break;
}
}
}
private ArrayList<NameValuePair> addCommonHeaderField(ArrayList<NameValuePair> _header)
{
_header.add(new BasicNameValuePair("Content-Type","application/x-www-form-urlencoded"));
return _header;
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try
{
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
instream.close();
}
}
catch (Exception e)
{ }
}
private static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
}
catch (IOException e)
{ }
return sb.toString();
}
}
You should check out Idiorm and Paris.
you shoud do like this form your code
DataGridView.DataSource = yourlist;
DataGridView.DataBind();
If you haven't used Update-Database
you can just delete it. If you've run the update then roll it back using Update-Database -TargetMigration "NameOfPreviousMigration"
, then delete it.
Reference: http://elegantcode.com/2012/04/12/entity-framework-migrations-tips/
I copied this text directly from here: How do I undo the last Add-Migration command?
You can use sudo gem install -n /usr/local/bin cocoapods
This works for me.
The Eclipse Word-Wrap plugin works for any type of file for me.
If you are using FireFox you can use the File HandleAPI
https://developer.mozilla.org/en-US/docs/Web/API/File_Handle_API
I had just tested it out and it works!
These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit
for Chrome, Safari; -moz
for Firefox, -o
for Opera, -ms
for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.
This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.
To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:
.elementClass {
-moz-border-radius: 2em;
-ms-border-radius: 2em;
-o-border-radius: 2em;
-webkit-border-radius: 2em;
border-radius: 2em;
}
Specifically, to address the CSS in your question, the lines you quote:
-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;
Specify the column-count
, column-gap
and column-fill
properties for Webkit browsers and Firefox.
References:
<div class="container">
<h1>About me</h1>
<div class="row">
<div class="pull-left ">
<img src="http://lorempixel.com/200/200" class="col-lg-3" class="img- responsive" alt="Responsive image">
<p class="col-md-4">Lots of text here... </p>
</div>
</div>
</div>
</div>
For any React Router v4 users arriving here following a search, optional parameters in a <Route>
are denoted with a ?
suffix.
Here's the relevant documentation:
https://reacttraining.com/react-router/web/api/Route/path-string
path: string
Any valid URL path that path-to-regexp understands.
<Route path="/users/:id" component={User}/>
https://www.npmjs.com/package/path-to-regexp#optional
Optional
<Route path="/section/:page?" component={Section} />
Rule of thumb: Use -a
and -o
inside square brackets, &&
and ||
outside.
It's important to understand the difference between shell syntax and the syntax of the [
command.
&&
and ||
are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.
[
is not special syntax. It's actually a command with the name [
, also known as test
. Since [
is just a regular command, it uses -a
and -o
for its and and or operators. It can't use &&
and ||
because those are shell syntax that commands don't get to see.
But wait! Bash has a fancier test syntax in the form of [[ ]]
. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&
, ||
, <
, and >
freely inside the brackets because, unlike [
, the double bracketed form is special shell syntax. Bash parses [[
itself so you can write things like [[ $foo == 5 && $bar == 6 ]]
.
In my case tomcat was configured to start not on localhost(guess it came from servers.xml connector entry) so Eclipse fails to find it running after start. Changed Host name
on Servers
tab to my 192.168.xxx.yyy
ip.
Had the same error message, though tomcat did start sucessfully, but then Eclipse shuts it down.
Install Tidy2 plugin. I have Notepad++ v6.2.2, and Tidy2 works fine so far.
my string
var obj = {"Status":0,"Data":{"guid":"","invitationGuid":"","entityGuid":"387E22AD69-4910-430C-AC16-8044EE4A6B24443545DD"},"Extension":null}
Following code to get guid:
var userObj = JObject.Parse(obj);
var userGuid = Convert.ToString(userObj["Data"]["guid"]);
In OS X, mv -f
shows "same file" error, so I rename twice:
for i in `find . -name "*" -type f |grep -e "[A-Z]"`; do j=`echo $i | tr '[A-Z]' '[a-z]' | sed s/\-1$//`; mv $i $i-1; mv $i-1 $j; done
You can use the .some
method referenced here.
The
some()
method tests whether at least one element in the array passes the test implemented by the provided function.
// test cases
var str1 = 'hi, how do you do?';
var str2 = 'regular string';
// do the test strings contain these terms?
var conditions = ["hello", "hi", "howdy"];
// run the tests against every element in the array
var test1 = conditions.some(el => str1.includes(el));
var test2 = conditions.some(el => str2.includes(el));
// display results
console.log(str1, ' ===> ', test1);
console.log(str2, ' ===> ', test2);
_x000D_
FWIW, I got this error when I was implementing core data in to an existing project. It turned out I forgot to link CoreData.h to my project. I had already added the CoreData framework to my project but solved the issue by linking to the framework in my pre-compiled header just like Apple's templates do:
#import <Availability.h>
#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#endif
There is a better answer to this problem, though I could just break this down step-by-step.
You will need to fetch and checkout the latest upstream changes like so, e.g.:
git fetch upstream
git checkout upstream/master -b revert/john/foo_and_bar
Taking a look at the commit log, you should find something similar to this:
commit b76a5f1f5d3b323679e466a1a1d5f93c8828b269 Merge: 9271e6e a507888 Author: Tim Tom <[email protected]> Date: Mon Apr 29 06:12:38 2013 -0700 Merge pull request #123 from john/foo_and_bar Add foo and bar commit a507888e9fcc9e08b658c0b25414d1aeb1eef45e Author: John Doe <[email protected]> Date: Mon Apr 29 12:13:29 2013 +0000 Add bar commit 470ee0f407198057d5cb1d6427bb8371eab6157e Author: John Doe <[email protected]> Date: Mon Apr 29 10:29:10 2013 +0000 Add foo
Now you want to revert the entire pull request with the ability to unrevert later. To do so, you will need to take the ID of the merge commit.
In the above example the merge commit is the top one where it says "Merged pull request #123...".
Do this to revert the both changes ("Add bar" and "Add foo") and you will end up with in one commit reverting the entire pull request which you can unrevert later on and keep the history of changes clean:
git revert -m 1 b76a5f1f5d3b323679e466a1a1d5f93c8828b269
~
is the bitwise complement operator in python which essentially calculates -x - 1
So a table would look like
i ~i
0 -1
1 -2
2 -3
3 -4
4 -5
5 -6
So for i = 0
it would compare s[0]
with s[len(s) - 1]
, for i = 1
, s[1]
with s[len(s) - 2]
.
As for your other question, this can be useful for a range of bitwise hacks.
I've just finished developing the plugin and it is available for everyone to use! Hope you will enjoy it.
First of all, make sure you have the jQuery
library is included. The best way to get the latest jQuery version is to update your head tag with:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
After downloading the files, make sure you include them in your project:
<link rel="stylesheet" type="text/css" href="css/splitchar.css">
<script type="text/javascript" src="js/splitchar.js"></script>
All you have to do is to asign the class splitchar
, followed by the desired style to the element wrapping your text. e.g
<h1 class="splitchar horizontal">Splitchar</h1>
After all this is done, just make sure you call the jQuery function in your document ready file like this:
$(".splitchar").splitchar();
In order to make the text look exactly as you want it to, all you have to do is apply your design like this:
.horizontal { /* Base CSS - e.g font-size */ }
.horizontal:before { /* CSS for the left half */ }
.horizontal:after { /* CSS for the right half */ }
That's it! Now you have the Splitchar
plugin all set. More info about it at http://razvanbalosin.com/Splitchar.js/.
I have done good research on the save() vs. persist() including running it on my local machine several times. All the previous explanations are confusing and incorrect. I compare save() and persist() methods below after a thorough research.
Save()
Serializable
;session.save()
for a detached object will create a new row in the table.Persist()
void
;session.persist()
for a detached object will throw a PersistentObjectException
, as it is not allowed.All these are tried/tested on Hibernate v4.0.1
.
Use traceback.extract_stack()
if you want convenient access to module and function names and line numbers.
Use ''.join(traceback.format_stack())
if you just want a string that looks like the traceback.print_stack()
output.
Notice that even with ''.join()
you will get a multi-line string, since the elements of format_stack()
contain \n
. See output below.
Remember to import traceback
.
Here's the output from traceback.extract_stack()
. Formatting added for readability.
>>> traceback.extract_stack()
[
('<string>', 1, '<module>', None),
('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
('<pyshell#1>', 1, '<module>', None)
]
Here's the output from ''.join(traceback.format_stack())
. Formatting added for readability.
>>> ''.join(traceback.format_stack())
' File "<string>", line 1, in <module>\n
File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
ret = method(*args, **kwargs)\n
File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
exec(code, self.locals)\n File "<pyshell#2>", line 1, in <module>\n'
Based on the error you showed ('footballforum' is missing required Java project: 'ApiDemos'), I would check your build path. Right-click the footballforum project and choose Build Path > Configure Build Path. Make sure ApiDemos is on the projects tab of the build path options.
Functions mysql_
are not supported any longer and have been removed in PHP 7
. You must use mysqli_
instead. However it's not recommended method now. You should consider PDO
with better security solutions.
$result = mysqli_query($con, "SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysqli_fetch_assoc($result);
echo $row['option_value'];
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_node("D")
G.add_node("E")
G.add_node("F")
G.add_node("G")
G.add_edge("A","B")
G.add_edge("B","C")
G.add_edge("C","E")
G.add_edge("C","F")
G.add_edge("D","E")
G.add_edge("F","G")
print(G.nodes())
print(G.edges())
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edge_color='r', arrows = True)
plt.show()
sort
has been replaced in v0.20 by DataFrame.sort_values
and DataFrame.sort_index
. Aside from this, we also have argsort
.
Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.
# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})
df
A B
0 a 7
1 c 9
2 c 3
3 a 5
4 b 2
For example, to sort df
by column "A", use sort_values
with a single column name:
df.sort_values(by='A')
A B
0 a 7
3 a 5
4 b 2
1 c 9
2 c 3
If you need a fresh RangeIndex, use DataFrame.reset_index
.
For example, to sort by both col "A" and "B" in df
, you can pass a list to sort_values
:
df.sort_values(by=['A', 'B'])
A B
3 a 5
0 a 7
4 b 2
2 c 3
1 c 9
df2 = df.sample(frac=1)
df2
A B
1 c 9
0 a 7
2 c 3
3 a 5
4 b 2
You can do this using sort_index
:
df2.sort_index()
A B
0 a 7
1 c 9
2 c 3
3 a 5
4 b 2
df.equals(df2)
# False
df.equals(df2.sort_index())
# True
Here are some comparable methods with their performance:
%timeit df2.sort_index()
%timeit df2.iloc[df2.index.argsort()]
%timeit df2.reindex(np.sort(df2.index))
605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
For example,
idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])
This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc
will do.
df.iloc[idx]
A B
1 c 9
0 a 7
2 c 3
3 a 5
4 b 2
This would use less memory, but probably take longer
int count = 0;
string line;
TextReader reader = new StreamReader("file.txt");
while ((line = reader.ReadLine()) != null)
{
count++;
}
reader.Close();
For me, I was upgrading the existing code into new setup by installing Anaconda from fresh with latest python version(3.7) For this,
from sklearn import cross_validation,
from sklearn.grid_search import GridSearchCV
to
from sklearn.model_selection import GridSearchCV,cross_validate
I think this code will help you:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
MailAddress SendFrom = new MailAddress(txtFrom.Text);
MailAddress SendTo = new MailAddress(txtTo.Text);
MailMessage MyMessage = new MailMessage(SendFrom, SendTo);
MyMessage.Subject = txtSubject.Text;
MyMessage.Body = txtBody.Text;
Attachment attachFile = new Attachment(txtAttachmentPath.Text);
MyMessage.Attachments.Add(attachFile);
SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);
emailClient.Send(MyMessage);
litStatus.Text = "Message Sent";
}
catch (Exception ex)
{
litStatus.Text = ex.ToString();
}
}
}
Go to project then
Right click on project---> Build Path-->Configure build path
Now there are 4 tabs Source, Projects, Libraries, Order and Export
Go to
Libraries tab --> Click on Add Library (shown at the right side) -->
select JRE System Library --> Next-->click Alternate JRE --> select
Installed JRE--> Finish --> Apply--> OK.
If you want to get database encodings:
psql -U postgres -h somehost --list
You'll see something like:
List of databases
Name | Owner | Encoding
------------------------+----------+----------
db1 | postgres | UTF8
git rebase -i
will do it.
First, start with a clean working directory: git status
should show no pending modifications, deletions, or additions.
Now, you have to decide which commit(s) you want to split.
To split apart your most recent commit, first:
$ git reset HEAD~
Now commit the pieces individually in the usual way, producing as many commits as you need.
This requires rebasing, that is, rewriting history. To find the correct commit, you have several choices:
If it was three commits back, then
$ git rebase -i HEAD~3
where 3
is how many commits back it is.
If it was farther back in the tree than you want to count, then
$ git rebase -i 123abcd~
where 123abcd
is the SHA1 of the commit you want to split up.
If you are on a different branch (e.g., a feature branch) that you plan to merge into master:
$ git rebase -i master
When you get the rebase edit screen, find the commit you want to break apart. At the beginning of that line, replace pick
with edit
(e
for short). Save the buffer and exit. Rebase will now stop just after the commit you want to edit. Then:
$ git reset HEAD~
Commit the pieces individually in the usual way, producing as many commits as you need, then
$ git rebase --continue
public static string ToFormattedCurrencyString(
this decimal currencyAmount,
string isoCurrencyCode,
CultureInfo userCulture)
{
var userCurrencyCode = new RegionInfo(userCulture.Name).ISOCurrencySymbol;
if (userCurrencyCode == isoCurrencyCode)
{
return currencyAmount.ToString("C", userCulture);
}
return string.Format(
"{0} {1}",
isoCurrencyCode,
currencyAmount.ToString("N2", userCulture));
}
For those (like me) who was looking for the same solution in Kotlin and were pointed to Java only - how to trim in Kotlin:
fun main(args: Array<String>) {
// array definition
val array = arrayListOf<String>(" String", "Tom Selleck "," Fish ")
println(array) // print original -> [ String, Tom Selleck , Fish ]
// remove leading and trailing spaces, result is arrayList
val sol1 = array.map { it.trim() }
println("sol1 = $sol1") // -> sol1 = [String, Tom Selleck, Fish]
// remove leading and trailing spaces, result is String
val sol2 = array.joinToString { it.trim() }
println("sol2 = $sol2") // -> sol2 = String, Tom Selleck, Fish
}
BigInteger has a constructor where you can pass string as an argument.
try below,
private void sum(String newNumber) {
// BigInteger is immutable, reassign the variable:
this.sum = this.sum.add(new BigInteger(newNumber));
}
package-lock.json
is written to when a numerical value in a property such as the "version" property, or a dependency property is changed in package.json
.
If these numerical values in package.json
and package-lock.json
match, package-lock.json
is read from.
If these numerical values in package.json
and package-lock.json
do not match, package-lock.json
is written to with those new values, and new modifiers such as the caret and tilde if they are present. But it is the numeral that is triggering the change to package-lock.json
.
To see what I mean, do the following. Using package.json
without package-lock.json
, run npm install
with:
{
"name": "test",
"version": "1.0.0",
...
"devDependencies": {
"sinon": "7.2.2"
}
}
package-lock.json
will now have:
"sinon": {
"version": "7.2.2",
Now copy/paste both files to a new directory. Change package.json
to (only adding caret):
{
"name": "test",
"version": "1.0.0",
...
"devDependencies": {
"sinon": "^7.2.2"
}
}
run npm install
. If there were no package-lock.json
file, [email protected] would be installed. npm install
is reading from package-lock.json
and installing 7.2.2.
Now change package.json
to:
{
"name": "test",
"version": "1.0.0",
...
"devDependencies": {
"sinon": "^7.3.0"
}
}
run npm install
. package-lock.json
has been written to, and will now show:
"sinon": {
"version": "^7.3.0",
I think Semaphore is what you are looking for, it will block the main process after counting down to 0. Sample code:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# simulate a time-consuming task by sleeping
time.sleep(5)
# `release` will add 1 to `sema`, allowing other
# processes blocked on it to continue
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
# once 20 processes are running, the following `acquire` call
# will block the main process since `sema` has been reduced
# to 0. This loop will continue only after one or more
# previously created processes complete.
sema.acquire()
p = Process(target=f, args=(i, sema))
all_processes.append(p)
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The following code is more structured since it acquires and releases sema
in the same function. However, it will consume too much resources if total_task_num
is very large:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# `sema` is acquired and released in the same
# block of code here, making code more readable,
# but may lead to problem.
sema.acquire()
time.sleep(5)
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
p = Process(target=f, args=(i, sema))
all_processes.append(p)
# the following line won't block after 20 processes
# have been created and running, instead it will carry
# on until all 1000 processes are created.
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The above code will create total_task_num
processes but only concurrency
processes will be running while other processes are blocked, consuming precious system resources.
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
Just to close this
foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
//textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Changes to this
foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
//textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
textBox3.Text += string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
This is a solution with no deprecated class or method : (Java 8 approved)
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
Important information : Using NoopHostnameVerifier is a security risk
myString.substring(str.length,str.length-1)
You should be able to do something like the above - which will get the last character
startService(new Intent(this, MyService.class));
Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
...
<service
android:name=".MyService"
android:label="My Service" >
</service>
</application>
TL;DR Remember, all git branches are themselves used for tracking the history of a set of files. Therefore, isn't every branch actually a "tracking branch", because that's what these branches are used for: to track the history of files over time. Thus we should probably be calling normal git "branches", "tracking-branches", but we don't. Instead we shorten their name to just "branches".
So that's partly why the term "tracking-branches" is so terribly confusing: to the uninitiated it can easily mean 2 different things.
In git the term "Tracking-branch" is a short name for the more complete term: "Remote-tracking-branch".
It's probably better at first if you substitute the more formal terms until you get more comfortable with these concepts.
Let's rephrase your question to this:
The key word here is 'Remote', so skip down to where you get confused and I'll describe what a Remote Tracking branch is and how it's used.
To better understand git terminology, including branches and tracking, which can initially be very confusing, I think it's easiest if you first get crystal clear on what git is and the basic structure of how it works. Without a solid understand like this I promise you'll get lost in the many details, as git has lots of complexity; (translation: lots of people use it for very important things).
The following is an introduction/overview, but you might find this excellent article also informative.
WHAT GIT IS, AND WHAT IT'S FOR
A git repository is like a family photo album: It holds historical snapshots showing how things were in past times. A "snapshot" being a recording of something, at a given moment in time.
A git repository is not limited to holding human family photos. It, rather can be used to record and organize anything that is evolving or changing over time.
The basic idea is to create a book so we can easily look backwards in time,
When you get mired down in the complexity and terminology, try to remember that a git repository is first and foremost, a repository of snapshots, and just like a photo album, it's used to both store and organize these snapshots.
SNAPSHOTS AND TRACKING
tracked - to follow a person or animal by looking for proof that they have been somewhere (dictionary.cambridge.org)
In git, "your project" refers to a directory tree of files (one or more, possibly organized into a tree structure using sub-directories), which you wish to keep a history of.
Git, via a 3 step process, records a "snapshot" of your project's directory tree at a given moment in time.
Each git snapshot of your project, is then organized by "links" pointing to previous snapshots of your project.
One by one, link-by-link, we can look backwards in time to find any previous snapshot of you, or your heritage.
For example, we can start with today's most recent snapshot of you, and then using a link, seek backwards in time, for a photo of you taken perhaps yesterday or last week, or when you were a baby, or even who your mother was, etc.
This is refereed to as "tracking; in this example it is tracking your life, or seeing where you have left a footprint, and where you have come from.
COMMITS
A commit is similar to one page in your photo album with a single snapshot, in that its not just the snapshot contained there, but also has the associated meta information about that snapshot. It includes:
A commit is the most important part of a well organized photo album.
THE FAMILY TREE OVER TIME, WITH BRANCHES AND MERGES
Disambiguation: "Tree" here refers not to a file directory tree, as used above, but rather to a family tree of related parent and child commits over time.
The git family tree structure is modeled on our own, human family trees.
In what follows to help understand links in a simple way, I'll refer to:
You should understand this instinctively, as it is based on the tree of life:
Thus all commits except brand new commits, (you could say "juvenile commits"), have one or more children pointing back at them.
With no children are pointing to a parent, then this commit is only a "growing tip", or where the next child will be born from.
With just one child pointing at a parent, this is just a simple, single parent <-- child relationship.
Line diagram of a simple, single parent chain linking backwards in time:
(older) ... <--link1-- Commit1 <--link2-- Commit2 <--link3-- Commit3 (newest)
BRANCHES
branch - A "branch" is an active line of development. The most recent commit on a branch is referred to as the tip of that branch. The tip of the branch is referenced by a branch head, which moves forward as additional development is done on the branch. A single Git repository can track an arbitrary number of branches, but your working tree is associated with just one of them (the "current" or "checked out" branch), and HEAD points to that branch. (gitglossary)
A git branch also refers to two things:
More than one child pointing --at a--> parent, is what git calls "branching".
NOTE: In reality any child, of any parent, weather first, second, or third, etc., can be seen as their own little branch, with their own growing tip. So a branch is not necessarily a long thing with many nodes, rather it is a little thing, created with just one or more commits from a given parent.
The first child of a parent might be said to be part of that same branch, whereas the successive children of that parent are what are normally called "branches".
In actuality, all children (not just the first) branch from it's parent, or you could say link, but I would argue that each link is actually the core part of a branch.
Formally, a git "branch" is just a name, like 'foo' for example, given to a specific growing tip of a family hierarchy. It's one type of what they call a "ref". (Tags and remotes which I'll explain later are also refs.)
ref - A name that begins with refs/ (e.g. refs/heads/master) that points to an object name or another ref (the latter is called a symbolic ref). For convenience, a ref can sometimes be abbreviated when used as an argument to a Git command; see gitrevisions(7) for details. Refs are stored in the repository.
The ref namespace is hierarchical. Different subhierarchies are used for different purposes (e.g. the refs/heads/ hierarchy is used to represent local branches). There are a few special-purpose refs that do not begin with refs/. The most notable example is HEAD. (gitglossary)
(You should take a look at the file tree inside your .git directory. It's where the structure of git is saved.)
So for example, if your name is Tom, then commits linked together that only include snapshots of you, might be the branch we name "Tom".
So while you might think of a tree branch as all of it's wood, in git a branch is just a name given to it's growing tips, not to the whole stick of wood leading up to it.
The special growing tip and it's branch which an arborist (a guy who prunes fruit trees) would call the "central leader" is what git calls "master".
The master branch always exists.
Line diagram of: Commit1 with 2 children (or what we call a git "branch"):
parent children
+-- Commit <-- Commit <-- Commit (Branch named 'Tom')
/
v
(older) ... <-- Commit1 <-- Commit (Branch named 'master')
Remember, a link only points from child to parent. There is no link pointing the other way, i.e. from old to new, that is from parent to child.
So a parent-commit has no direct way to list it's children-commits, or in other words, what was derived from it.
MERGING
Children have one or more parents.
With just one parent this is just a simple parent <-- child commit.
With more than one parent this is what git calls "merging". Each child can point back to more than one parent at the same time, just as in having both a mother AND father, not just a mother.
Line diagram of: Commit2 with 2 parents (or what we call a git "merge", i.e. Procreation from multiple parents):
parents child
... <-- Commit
v
\
(older) ... <-- Commit1 <-- Commit2
REMOTE
This word is also used to mean 2 different things:
remote repository - A repository which is used to track the same project but resides somewhere else. To communicate with remotes, see fetch or push. (gitglossary)
(The remote repository can even be another git repository on our own computer.) Actually there are two URLS for each remote name, one for pushing (i.e. uploading commits) and one for pulling (i.e. downloading commits) from that remote git repository.
A "remote" is a name (an identifier) which has an associated URL which points to a remote git repository. (It's been described as an alias for a URL, although it's more than that.)
You can setup multiple remotes if you want to pull or push to multiple remote repositories.
Though often you have just one, and it's default name is "origin" (meaning the upstream origin from where you cloned).
origin - The default upstream repository. Most projects have at least one upstream project which they track. By default origin is used for that purpose. New upstream updates will be fetched into remote-tracking branches named origin/name-of-upstream-branch, which you can see using git branch -r. (gitglossary)
Origin represents where you cloned the repository from.
That remote repository is called the "upstream" repository, and your cloned repository is called the "downstream" repository.
upstream - In software development, upstream refers to a direction toward the original authors or maintainers of software that is distributed as source code wikipedia
upstream branch - The default branch that is merged into the branch in question (or the branch in question is rebased onto). It is configured via branch..remote and branch..merge. If the upstream branch of A is origin/B sometimes we say "A is tracking origin/B". (gitglossary)
This is because most of the water generally flows down to you.
From time to time you might push some software back up to the upstream repository, so it can then flow down to all who have cloned it.
REMOTE TRACKING BRANCH
A remote-tracking-branch is first, just a branch name, like any other branch name.
It points at a local growing tip, i.e. a recent commit in your local git repository.
But note that it effectively also points to the same commit in the remote repository that you cloned the commit from.
remote-tracking branch - A ref that is used to follow changes from another repository. It typically looks like refs/remotes/foo/bar (indicating that it tracks a branch named bar in a remote named foo), and matches the right-hand-side of a configured fetch refspec. A remote-tracking branch should not contain direct modifications or have local commits made to it. (gitglossary)
Say the remote you cloned just has 2 commits, like this: parent42 <== child-of-4, and you clone it and now your local git repository has the same exact two commits: parent4 <== child-of-4.
Your remote tracking branch named origin now points to child-of-4.
Now say that a commit is added to the remote, so it looks like this: parent42 <== child-of-4 <== new-baby. To update your local, downstream repository you'll need to fetch new-baby, and add it to your local git repository. Now your local remote-tracking-branch points to new-baby. You get the idea, the concept of a remote-tracking-branch is simply to keep track of what had previously been the tip of a remote branch that you care about.
TRACKING IN ACTION
First we begin tracking a file with git.
Here are the basic commands involved with file tracking:
$ mkdir mydir && cd mydir && git init # create a new git repository
$ git branch # this initially reports no branches
# (IMHO this is a bug!)
$ git status -bs # -b = branch; -s = short # master branch is empty
## No commits yet on master
# ...
$ touch foo # create a new file
$ vim foo # modify it (OPTIONAL)
$ git add foo; commit -m 'your description' # start tracking foo
$ git rm --index foo; commit -m 'your description' # stop tracking foo
$ git rm foo; commit -m 'your description' # stop tracking foo & also delete foo
REMOTE TRACKING IN ACTION
$ git pull # Essentially does: get fetch; git merge # to update our clone
There is much more to learn about fetch, merge, etc, but this should get you off in the right direction I hope.
I had the same problem. But just restarting my computer after setting up the Maven path resolved the issue.
Variable Name: M2_Home Variable Value:C:\Apache\apache-maven-3.3.9
Variable Name: Path Variable Value:C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%JAVA_HOME%\bin\;%M2_HOME%\bin\
2007 is more powerful with ribbon..:=) To add new series in chart do: Select Chart, then click Design in Chart Tools on the ribbon, On the Design ribbon, select "Select Data" in Data Group, Then you will see the button for Add to add new series.
Hope that will help.
You can give this simple jQuery plugin (AnimateScroll) a whirl. It is quite easy to use.
1. Scroll to the top of the page:
$('body').animatescroll();
2. Scroll to an element with ID section-1
:
$('#section-1').animatescroll({easing:'easeInOutBack'});
Disclaimer: I am the author of this plugin.
from manual:
: [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.
As this returns always zero therefore is is similar to be used as true
Check out this answer: What Is the Purpose of the `:' (colon) GNU Bash Builtin?
You call tarfile.open with mode='w:gz'
, meaning "Open for gzip compressed writing."
You'll probably want to end the filename (the name
argument to open
) with .tar.gz
, but that doesn't affect compression abilities.
BTW, you usually get better compression with a mode of 'w:bz2'
, just like tar
can usually compress even better with bzip2
than it can compress with gzip
.
Have you looked at the Maven Dependency Plugin ? That won't remove stuff for you but has tools to allow you to do the analysis yourself. I'm thinking particularly of
mvn dependency:tree
The maximum SqlDbType.VarChar size is 2147483647.
If you would use a generic oledb connection instead of sql, I found here there is also a LongVarChar datatype. Its max size is 2147483647.
cmd.Parameters.Add("@blah", OleDbType.LongVarChar, -1).Value = "very big string";
You can use setenv.bat or .sh to pass the environment variables to the Tomcat.
Create CATALINA_BASE/bin/setenv.bat or .sh file and put the following line in it, and then start the Tomcat.
On Windows:
set APP_MASTER_PASSWORD=foo
On Unix like systems:
export APP_MASTER_PASSWORD=foo
if params[:one] && params[:two]
... do something ...
elsif params[:one]
... do something ...
end
Add new column and fill it with ascending numbers. Then filter by ([column] mod 7 = 0) or something like that (don't have Excel in front of me to actually try this);
If you can't filter by formula, add one more column and use the formula =MOD([column; 7]) in it then filter zeros and you'll get all seventh rows.
In Bootstrap 4: Try this way with Flexbox. See documentation in getbootstrap
<div class="row">
<div class="col-md">
<div class="d-flex justify-content-end">
<button type="button" class="btn btn-default">Example 1</button>
<button type="button" class="btn btn-default">Example 2</button>
</div>
</div>
</div>
In the example above. For me, this if($response.success==false)
thing does not work. Here is correct PHP code:
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "--your_key--";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {
// everything is ok!
} else {
// spam
}
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).look at this: https://developer.mozilla.org/en-US/docs/Web/API/event.keyCode
In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, never both. If the key pressed generates a character (e.g. 'a'), charCode is set to the code of that character, respecting the letter case. (i.e. charCode takes into account whether the shift key is held down). Otherwise, the code of the pressed key is stored in keyCode. keyCode is always set in the keydown and keyup events. In these cases, charCode is never set. To get the code of the key regardless of whether it was stored in keyCode or charCode, query the which property. Characters entered through an IME do not register through keyCode or charCode.
The good solution for this error please run this command
composer install --ignore-platform-reqs
The PHP manual explains both quite well:
http://php.net/manual/en/reserved.variables.server.php # REQUEST_URI
http://php.net/manual/en/reserved.variables.get.php # for the $_GET["q"] variable
$('#multiselect1').on('change', function(){
var selected = $(this).find("option:selected");
var arrSelected = [];
selected.each(function(){
arrSelected.push($(this).val());
});
});
if you want to be sure its created then this:
final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
final boolean logsDirExists = logsDir.exists();
assertThat(logsDirExists).isTrue();
}
beacuse mkDir()
returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...
mkDir()
returns only true if mkDir()
creates it.
If the dir exists, it returns false, so to verify the dir you created, only call exists()
if mkDir()
return false.
assertThat()
will checks the result and fails if exists()
returns false. ofc you can use other things to handle the uncreated directory.
You can only get the URI arguments with JavaScript.
// get query arguments
var $_GET = {},
args = location.search.substr(1).split(/&/);
for (var i=0; i<args.length; ++i) {
var tmp = args[i].split(/=/);
if (tmp[0] != "") {
$_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
}
}
The best answer is...
The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.
Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?
For many tasks, using Beautiful Soup will be far faster and easier to use:
>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser') # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['http://example.com', 'http://example2.com']
If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser
that does exactly what you want:
from html.parser import HTMLParser
class MyParser(HTMLParser):
def __init__(self, output_list=None):
HTMLParser.__init__(self)
if output_list is None:
self.output_list = []
else:
self.output_list = output_list
def handle_starttag(self, tag, attrs):
if tag == 'a':
self.output_list.append(dict(attrs).get('href'))
Test:
>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['http://example.com', 'http://example2.com']
You could even create a new method that accepts a string, calls feed
, and returns output_list
. This is a vastly more powerful and extensible way than regular expressions to extract information from html.
You can create temp stored procedures like:
create procedure #mytemp as
begin
select getdate() into #mytemptable;
end
in an SQL script, but not functions. You could have the proc store it's result in a temp table though, then use that information later in the script ..
You could make the variables public fields:
public int width;
public int height;
DrawFrame() {
this.width = 400;
this.height = 400;
}
You could then access the variables like so:
DrawFrame frame = new DrawFrame();
int theWidth = frame.width;
int theHeight = frame.height;
A better solution, however, would be to make the variables private fields add two accessor methods to your class, keeping the data in the DrawFrame class encapsulated:
private int width;
private int height;
DrawFrame() {
this.width = 400;
this.height = 400;
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
Then you can get the width/height like so:
DrawFrame frame = new DrawFrame();
int theWidth = frame.getWidth();
int theHeight = frame.getHeight();
I strongly suggest you use the latter method.
If you don't care about the difference between an unset variable or a variable with an empty value, you can use the default-value parameter expansion:
foo=${DEPLOY_ENV:-default}
If you do care about the difference, drop the colon
foo=${DEPLOY_ENV-default}
You can also use the -v
operator to explicitly test if a parameter is set.
if [[ ! -v DEPLOY_ENV ]]; then
echo "DEPLOY_ENV is not set"
elif [[ -z "$DEPLOY_ENV" ]]; then
echo "DEPLOY_ENV is set to the empty string"
else
echo "DEPLOY_ENV has the value: $DEPLOY_ENV"
fi
Use textView
instead then conform with its delegate, call the textViewDidChange
method inside of that method call tableView.beginUpdates()
and tableView.endUpdates()
and don't forget to set rowHeight
and estimatedRowHeight
to UITableView.automaticDimension
.
I use this trick, pretty sure I already posted it to a duplicate of this question:
-(void)tableViewDidLoadRows:(UITableView *)tableView{
// do something after loading, e.g. select a cell.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// trick to detect when table view has finished loading.
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tableViewDidLoadRows:) object:tableView];
[self performSelector:@selector(tableViewDidLoadRows:) withObject:tableView afterDelay:0];
// specific to your controller
return self.objects.count;
}
Try these simple steps:
ObjectMapper mapper = new ObjectMapper();
String newJsonData = mapper.writeValueAsString(cartList);
return newJsonData;
ObjectMapper() is com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper();
Call a Javascript function every 2 second continuously for 10 second.
_x000D__x000D__x000D__x000D__x000D_var intervalPromise;_x000D_ $scope.startTimer = function(fn, delay, timeoutTime) {_x000D_ intervalPromise = $interval(function() {_x000D_ fn();_x000D_ var currentTime = new Date().getTime() - $scope.startTime;_x000D_ if (currentTime > timeoutTime){_x000D_ $interval.cancel(intervalPromise);_x000D_ } _x000D_ }, delay);_x000D_ };_x000D_ _x000D_ $scope.startTimer(hello, 2000, 10000);_x000D_ _x000D_ hello(){_x000D_ console.log("hello");_x000D_ }