For me (ubuntu 16.04) the winner was:
sudo apt install php7.0-mysql
I know its been a while since the question was asked but I was able to find a solution:
int sockfd;
int option = 1;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
This set the socket able to be reused immediately.
I apologize if this is "wrong". I'm not very experienced with sockets
You can use Python as a quick way to host static content. On Windows, there are many options for running Python, I've personally used CygWin and ActivePython.
To use Python as a simple HTTP server just change your working directory to the folder with your static content and type python -m SimpleHTTPServer 8000
, everything in the directory will be available at http:/localhost:8000/
To do this with Python, 3.4.1 (and probably other versions of Python 3), use the http.server
module:
python -m http.server <PORT>
# or possibly:
python3 -m http.server <PORT>
# example:
python -m http.server 8080
On Windows:
py -m http.server <PORT>
The answers using grep are wrong. You need to add an -x option to match the entire line otherwise lines like #text to add
will still match when looking to add exactly text to add
.
So the correct solution is something like:
grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar
Try this.
dpkg -s apache2 | grep Status
dpkg -s php5 | grep Status
APC segfaults all day and all night, got no experience with eAccelerator but XCache is very reliable with loads of options and constant development.
Both will generate the same columns when you run the migration. In rails console, you can see that this is the case:
:001 > Micropost
=> Micropost(id: integer, user_id: integer, created_at: datetime, updated_at: datetime)
The second command adds a belongs_to :user
relationship in your Micropost model whereas the first does not. When this relationship is specified, ActiveRecord will assume that the foreign key is kept in the user_id
column and it will use a model named User
to instantiate the specific user.
The second command also adds an index on the new user_id
column.
This a problem with the CORS configuration on the server. It is not clear what server are you using, but if you are using Node+express you can solve it with the following code
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
that code was an answer of @jvandemo to a very similar question.
Here is what I did
var domainNames =["fiddle.jshell.net"]; // we replace this by our production domain.
var logger = {
force:false,
original:null,
log:function(obj)
{
var hostName = window.location.hostname;
if(domainNames.indexOf(hostName) > -1)
{
if(window.myLogger.force === true)
{
window.myLogger.original.apply(this,arguments);
}
}else {
window.myLogger.original.apply(this,arguments);
}
},
forceLogging:function(force){
window.myLogger.force = force;
},
original:function(){
return window.myLogger.original;
},
init:function(){
window.myLogger.original = console.log;
console.log = window.myLogger.log;
}
}
window.myLogger = logger;
console.log("this should print like normal");
window.myLogger.init();
console.log("this should not print");
window.myLogger.forceLogging(true);
console.log("this should print now");
Also posted about it here. http://bhavinsurela.com/naive-way-of-overriding-console-log/
The issue noted clearly in https://dev.mysql.com/doc/refman/8.0/en/too-many-connections.html:
If clients encounter Too many connections errors when attempting to connect to the MySQL server, all available connections are in use by other clients.
I got resolved the issue after a few minutes, it seems that connection was been released by other clients, also I tried with restarting vs and workbench at same time.
You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL. Example:
<?php
$var1 = '';
if(isset($var1)){
echo 'This line is printed, because the $var1 is set.';
}
?>
This code will output "This line is printed, because the $var1 is set."
read more in https://stackhowto.com/how-to-check-if-a-variable-is-undefined-in-php/
Here is my solution with jQuery... You have to add maxlength to your input type=number
$('body').on('keypress', 'input[type=number][maxlength]', function(event){
var key = event.keyCode || event.charCode;
var charcodestring = String.fromCharCode(event.which);
var txtVal = $(this).val();
var maxlength = $(this).attr('maxlength');
var regex = new RegExp('^[0-9]+$');
// 8 = backspace 46 = Del 13 = Enter 39 = Left 37 = right Tab = 9
if( key == 8 || key == 46 || key == 13 || key == 37 || key == 39 || key == 9 ){
return true;
}
// maxlength allready reached
if(txtVal.length==maxlength){
event.preventDefault();
return false;
}
// pressed key have to be a number
if( !regex.test(charcodestring) ){
event.preventDefault();
return false;
}
return true;
});
And handle copy and paste:
$('body').on('paste', 'input[type=number][maxlength]', function(event) {
//catch copy and paste
var ref = $(this);
var regex = new RegExp('^[0-9]+$');
var maxlength = ref.attr('maxlength');
var clipboardData = event.originalEvent.clipboardData.getData('text');
var txtVal = ref.val();//current value
var filteredString = '';
var combined_input = txtVal + clipboardData;//dont forget old data
for (var i = 0; i < combined_input.length; i++) {
if( filteredString.length < maxlength ){
if( regex.test(combined_input[i]) ){
filteredString += combined_input[i];
}
}
}
setTimeout(function(){
ref.val('').val(filteredString)
},100);
});
I hope it helps somebody.
This is a long post, but I was tired of all these examples that weren't working for me because they used Promise objects or an errant this
that has a different meaning when you are using Reactjs. My implementation was using a DropZone with reactjs, and I got the bytes using a framework similar to what is posted at this following site, when nothing else above would work: https://www.mokuji.me/article/drop-upload-tutorial-1 . There were 2 keys, for me:
I tried various combinations, but in the end, what worked was:
const bytes = e.target.result.split('base64,')[1];
Where e
is the event. React requires const
, you could use var
in plain Javascript. But that gave me the base64 encoded byte string.
So I'm just going to include the applicable lines for integrating this as if you were using React, because that's how I was building it, but try to also generalize this, and add comments where necessary, to make it applicable to a vanilla Javascript implementation - caveated that I did not use it like that in such a construct to test it.
These would be your bindings at the top, in your constructor, in a React framework (not relevant to a vanilla Javascript implementation):
this.uploadFile = this.uploadFile.bind(this);
this.processFile = this.processFile.bind(this);
this.errorHandler = this.errorHandler.bind(this);
this.progressHandler = this.progressHandler.bind(this);
And you'd have onDrop={this.uploadFile}
in your DropZone element. If you were doing this without React, this is the equivalent of adding the onclick event handler you want to run when you click the "Upload File" button.
<button onclick="uploadFile(event);" value="Upload File" />
Then the function (applicable lines... I'll leave out my resetting my upload progress indicator, etc.):
uploadFile(event){
// This is for React, only
this.setState({
files: event,
});
console.log('File count: ' + this.state.files.length);
// You might check that the "event" has a file & assign it like this
// in vanilla Javascript:
// var files = event.target.files;
// if (!files && files.length > 0)
// files = (event.dataTransfer ? event.dataTransfer.files :
// event.originalEvent.dataTransfer.files);
// You cannot use "files" as a variable in React, however:
const in_files = this.state.files;
// iterate, if files length > 0
if (in_files.length > 0) {
for (let i = 0; i < in_files.length; i++) {
// use this, instead, for vanilla JS:
// for (var i = 0; i < files.length; i++) {
const a = i + 1;
console.log('in loop, pass: ' + a);
const f = in_files[i]; // or just files[i] in vanilla JS
const reader = new FileReader();
reader.onerror = this.errorHandler;
reader.onprogress = this.progressHandler;
reader.onload = this.processFile(f);
reader.readAsDataURL(f);
}
}
}
There was this question on that syntax, for vanilla JS, on how to get that file object:
Note that React's DropZone will already put the File object into this.state.files
for you, as long as you add files: [],
to your this.state = { .... }
in your constructor. I added syntax from an answer on that post on how to get your File object. It should work, or there are other posts there that can help. But all that Q/A told me was how to get the File
object, not the blob data, itself. And even if I did fileData = new Blob([files[0]]);
like in sebu's answer, which didn't include var
with it for some reason, it didn't tell me how to read that blob's contents, and how to do it without a Promise object. So that's where the FileReader came in, though I actually tried and found I couldn't use their readAsArrayBuffer
to any avail.
You will have to have the other functions that go along with this construct - one to handle onerror
, one for onprogress
(both shown farther below), and then the main one, onload
, that actually does the work once a method on reader
is invoked in that last line. Basically you are passing your event.dataTransfer.files[0]
straight into that onload
function, from what I can tell.
So the onload
method calls my processFile()
function (applicable lines, only):
processFile(theFile) {
return function(e) {
const bytes = e.target.result.split('base64,')[1];
}
}
And bytes
should have the base64 bytes.
Additional functions:
errorHandler(e){
switch (e.target.error.code) {
case e.target.error.NOT_FOUND_ERR:
alert('File not found.');
break;
case e.target.error.NOT_READABLE_ERR:
alert('File is not readable.');
break;
case e.target.error.ABORT_ERR:
break; // no operation
default:
alert('An error occurred reading this file.');
break;
}
}
progressHandler(e) {
if (e.lengthComputable){
const loaded = Math.round((e.loaded / e.total) * 100);
let zeros = '';
// Percent loaded in string
if (loaded >= 0 && loaded < 10) {
zeros = '00';
}
else if (loaded < 100) {
zeros = '0';
}
// Display progress in 3-digits and increase bar length
document.getElementById("progress").textContent = zeros + loaded.toString();
document.getElementById("progressBar").style.width = loaded + '%';
}
}
And applicable progress indicator markup:
<table id="tblProgress">
<tbody>
<tr>
<td><b><span id="progress">000</span>%</b> <span className="progressBar"><span id="progressBar" /></span></td>
</tr>
</tbody>
</table>
And CSS:
.progressBar {
background-color: rgba(255, 255, 255, .1);
width: 100%;
height: 26px;
}
#progressBar {
background-color: rgba(87, 184, 208, .5);
content: '';
width: 0;
height: 26px;
}
EPILOGUE:
Inside processFile()
, for some reason, I couldn't add bytes
to a variable I carved out in this.state
. So, instead, I set it directly to the variable, attachments
, that was in my JSON object, RequestForm
- the same object as my this.state
was using. attachments
is an array so I could push multiple files. It went like this:
const fileArray = [];
// Collect any existing attachments
if (RequestForm.state.attachments.length > 0) {
for (let i=0; i < RequestForm.state.attachments.length; i++) {
fileArray.push(RequestForm.state.attachments[i]);
}
}
// Add the new one to this.state
fileArray.push(bytes);
// Update the state
RequestForm.setState({
attachments: fileArray,
});
Then, because this.state
already contained RequestForm
:
this.stores = [
RequestForm,
]
I could reference it as this.state.attachments
from there on out. React feature that isn't applicable in vanilla JS. You could build a similar construct in plain JavaScript with a global variable, and push, accordingly, however, much easier:
var fileArray = new Array(); // place at the top, before any functions
// Within your processFile():
var newFileArray = [];
if (fileArray.length > 0) {
for (var i=0; i < fileArray.length; i++) {
newFileArray.push(fileArray[i]);
}
}
// Add the new one
newFileArray.push(bytes);
// Now update the global variable
fileArray = newFileArray;
Then you always just reference fileArray
, enumerate it for any file byte strings, e.g. var myBytes = fileArray[0];
for the first file.
1: Create a class WebMvcConfig and extend it as shown from the WebMvcConfiguration and override addCorsMappings method.
2: Most importantly don't forget to make it @Configuration annotation because it should be loaded with Main Spring class to allow Cross-Origin.
@Configuration
public class WebMvcCofig implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true);
}
}
My take on it...obviously, you've got to do something with the data you read in. If it involves writing it to the sheet, that'll be deadly slow with a normal For Loop. I came up with the following based upon a rehash of some of the items there, plus some help from the Chip Pearson website.
Reading in the text file (assuming you don't know the length of the range it will create, so only the startingCell is given):
Public Sub ReadInPlainText(startCell As Range, Optional textfilename As Variant)
If IsMissing(textfilename) Then textfilename = Application.GetOpenFilename("All Files (*.*), *.*", , "Select Text File to Read")
If textfilename = "" Then Exit Sub
Dim filelength As Long
Dim filenumber As Integer
filenumber = FreeFile
filelength = filelen(textfilename)
Dim text As String
Dim textlines As Variant
Open textfilename For Binary Access Read As filenumber
text = Space(filelength)
Get #filenumber, , text
'split the file with vbcrlf
textlines = Split(text, vbCrLf)
'output to range
Dim outputRange As Range
Set outputRange = startCell
Set outputRange = outputRange.Resize(UBound(textlines), 1)
outputRange.Value = Application.Transpose(textlines)
Close filenumber
End Sub
Conversely, if you need to write out a range to a text file, this does it quickly in one print statement (note: the file 'Open' type here is in text mode, not binary..unlike the read routine above).
Public Sub WriteRangeAsPlainText(ExportRange As Range, Optional textfilename As Variant)
If IsMissing(textfilename) Then textfilename = Application.GetSaveAsFilename(FileFilter:="Text Files (*.txt), *.txt")
If textfilename = "" Then Exit Sub
Dim filenumber As Integer
filenumber = FreeFile
Open textfilename For Output As filenumber
Dim textlines() As Variant, outputvar As Variant
textlines = Application.Transpose(ExportRange.Value)
outputvar = Join(textlines, vbCrLf)
Print #filenumber, outputvar
Close filenumber
End Sub
URL url = new URL(yourUrl, "/api/v1/status.xml");
According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:
URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");
Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html
which may be useful
Update
A INNER JOIN B ON A.COL1=B.COL3
SET
A.COL2='CHANGED', A.COL4=B.COL4,......
WHERE ....;
I'm going to offer up a way to return a boolean based on passing an argument of a reflection Kinds to a local type receiver (because I couldn't find anything like this).
First, we declare our anonymous type of type reflect.Value:
type AnonymousType reflect.Value
Then we add a builder for our local type AnonymousType which can take in any potential type (as an interface):
func ToAnonymousType(obj interface{}) AnonymousType {
return AnonymousType(reflect.ValueOf(obj))
}
Then we add a function for our AnonymousType struct which asserts against a reflect.Kind:
func (a AnonymousType) IsA(typeToAssert reflect.Kind) bool {
return typeToAssert == reflect.Value(a).Kind()
}
This allows us to call the following:
var f float64 = 3.4
anon := ToAnonymousType(f)
if anon.IsA(reflect.String) {
fmt.Println("Its A String!")
} else if anon.IsA(reflect.Float32) {
fmt.Println("Its A Float32!")
} else if anon.IsA(reflect.Float64) {
fmt.Println("Its A Float64!")
} else {
fmt.Println("Failed")
}
Can see a longer, working version here:https://play.golang.org/p/EIAp0z62B7
The python-espeak package is available in Debian, Ubuntu, Redhat, and other Linux distributions. It has recent updates, and works fine.
from espeak import espeak
espeak.synth("Hello world.")
Jonathan Leaders notes that it also works on Windows, and you can install the mbrola voices as well. See the espeak website at http://espeak.sourceforge.net
You should check out the UINavigationBarDelegate Protocol. In this case you might want to use the navigationBar:shouldPopItem: method.
Simply call InetAddress.getByName(String host)
passing in your textual IP address.
From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.
The standard numpy function for what you want is np.column_stack
:
>>> np.column_stack(([1, 2, 3], [4, 5, 6]))
array([[1, 4],
[2, 5],
[3, 6]])
So with your portfolio
and index
arrays, doing
np.column_stack((portfolio, index))
would yield something like:
[[portfolio_value1, index_value1],
[portfolio_value2, index_value2],
[portfolio_value3, index_value3],
...]
You can try dotImage, one of my company's products, which includes an object for resampling images that has 18 filter types for various levels of quality.
Typical usage is:
// BiCubic is one technique available in PhotoShop
ResampleCommand resampler = new ResampleCommand(newSize, ResampleMethod.BiCubic);
AtalaImage newImage = resampler.Apply(oldImage).Image;
in addition, dotImage includes 140 some odd image processing commands including many filters similar to those in PhotoShop, if that's what you're looking for.
Since the Logical Address space is 32-bit long that means program size is 2^32 bytes i.e. 4GB. Now we have the page size of 4KB i.e.2^12 bytes.Thus the number of pages in program are 2^20.(no. of pages in program = program size/page size).Now the size of page table entry is 4 byte hence the size of page table is 2^20*4 = 4MB(size of page table = no. of pages in program * page table entry size). Hence 4MB space is required in Memory to store the page table.
It looks like your Spring component scan Base is missing UserServiceImpl
<context:component-scan base-package="org.assessme.com.controller." />
Open sFileName For Input As iFileNum
Dim LineNum As Long
LineNum = 0
Do While Not EOF(iFileNum)
LineNum = LineNum + 1
Line Input #iFileNum, Fields
If LineNum > 2 Then
DoStuffWith(Fields)
End If
Loop
I'm assuming you're using express
, given the logs you have in your question. The key is to set the timeout
property on server (the following sets the timeout to one second, use whatever value you want):
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;
If you're not using express and are only working with vanilla node, the principle is the same. The following will not return data:
var http = require('http');
var server = http.createServer(function (req, res) {
setTimeout(function() {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}, 200);
}).listen(1337, '127.0.0.1');
server.timeout = 20;
console.log('Server running at http://127.0.0.1:1337/');
For "simple" strings (typically what fits into a line) the simplest solution is using fmt.Sprintf()
and friends (fmt.Sprint()
, fmt.Sprintln()
). These are analogous to the functions without the starter S
letter, but these Sxxx()
variants return the result as a string
instead of printing them to the standard output.
For example:
s := fmt.Sprintf("Hi, my name is %s and I'm %d years old.", "Bob", 23)
The variable s
will be initialized with the value:
Hi, my name is Bob and I'm 23 years old.
Tip: If you just want to concatenate values of different types, you may not automatically need to use Sprintf()
(which requires a format string) as Sprint()
does exactly this. See this example:
i := 23
s := fmt.Sprint("[age:", i, "]") // s will be "[age:23]"
For concatenating only string
s, you may also use strings.Join()
where you can specify a custom separator string
(to be placed between the strings to join).
Try these on the Go Playground.
If the string you're trying to create is more complex (e.g. a multi-line email message), fmt.Sprintf()
becomes less readable and less efficient (especially if you have to do this many times).
For this the standard library provides the packages text/template
and html/template
. These packages implement data-driven templates for generating textual output. html/template
is for generating HTML output safe against code injection. It provides the same interface as package text/template
and should be used instead of text/template
whenever the output is HTML.
Using the template
packages basically requires you to provide a static template in the form of a string
value (which may be originating from a file in which case you only provide the file name) which may contain static text, and actions which are processed and executed when the engine processes the template and generates the output.
You may provide parameters which are included/substituted in the static template and which may control the output generation process. Typical form of such parameters are struct
s and map
values which may be nested.
Example:
For example let's say you want to generate email messages that look like this:
Hi [name]!
Your account is ready, your user name is: [user-name]
You have the following roles assigned:
[role#1], [role#2], ... [role#n]
To generate email message bodies like this, you could use the following static template:
const emailTmpl = `Hi {{.Name}}!
Your account is ready, your user name is: {{.UserName}}
You have the following roles assigned:
{{range $i, $r := .Roles}}{{if $i}}, {{end}}{{.}}{{end}}
`
And provide data like this for executing it:
data := map[string]interface{}{
"Name": "Bob",
"UserName": "bob92",
"Roles": []string{"dbteam", "uiteam", "tester"},
}
Normally output of templates are written to an io.Writer
, so if you want the result as a string
, create and write to a bytes.Buffer
(which implements io.Writer
). Executing the template and getting the result as string
:
t := template.Must(template.New("email").Parse(emailTmpl))
buf := &bytes.Buffer{}
if err := t.Execute(buf, data); err != nil {
panic(err)
}
s := buf.String()
This will result in the expected output:
Hi Bob!
Your account is ready, your user name is: bob92
You have the following roles assigned:
dbteam, uiteam, tester
Try it on the Go Playground.
Also note that since Go 1.10, a newer, faster, more specialized alternative is available to bytes.Buffer
which is: strings.Builder
. Usage is very similar:
builder := &strings.Builder{}
if err := t.Execute(builder, data); err != nil {
panic(err)
}
s := builder.String()
Try this one on the Go Playground.
Note: you may also display the result of a template execution if you provide os.Stdout
as the target (which also implements io.Writer
):
t := template.Must(template.New("email").Parse(emailTmpl))
if err := t.Execute(os.Stdout, data); err != nil {
panic(err)
}
This will write the result directly to os.Stdout
. Try this on the Go Playground.
This answer is not the answer for the above mentioned question but it is related to same topic and might be useful for people searching for same error.
I faced the same error when I executed below mentioned query.
select OR.* from ORDER_REL_STAT OR
problem with above query was OR is keyword so it was expecting other values when I replaced with some other alias it worked fine.
if (new DateTime(5000) > new DateTime(1000))
{
Console.WriteLine("i win");
}
Here's a variant that uses fancy indexing and has the actual values as an intermediate:
p31 = numpy.asarray(o31)
values = p31[p31<200]
za = len(values)
You can easily do the following:
FlatButton(
onPressed: () {
},
child: new Icon(
Icons.arrow_forward,
color: Colors.white,
size: 20.0,
),
shape: new CircleBorder(),
color: Colors.black12,
)
Use DateTime.AddDays()
(MSDN Documentation DateTime.AddDays Method).
DateTime tomorrow = DateTime.Now.AddDays(1);
DateTime yesterday = DateTime.Now.AddDays(-1);
ElektroStudios answer is a bit misleading.
"when you launch a bat file the working dir is the dir where it was launched" This is true if the user clicks on the batch file in the explorer.
However, if the script is called from another script using the CALL command, the current working directory does not change.
Thus, inside your script, it is better to use %~dp0subfolder\file1.txt
Please also note that %~dp0 will end with a backslash when the current script is not in the current working directory. Thus, if you need the directory name without a trailing backslash, you could use something like
call :GET_THIS_DIR
echo I am here: %THIS_DIR%
goto :EOF
:GET_THIS_DIR
pushd %~dp0
set THIS_DIR=%CD%
popd
goto :EOF
Replace each loop with any closure.
def list = [1, 2, 3, 4, 5]
list.any { element ->
if (element == 2)
return // continue
println element
if (element == 3)
return true // break
}
Output
1
3
Apply following line in your EditText in XML.
android:inputType="textCapSentences|textMultiLine"
It will also allow multi-line support.
You can also left pad with zeros. For example if you want number
to have 9 characters length, left padded with zeros use:
print('{:09.3f}'.format(number))
Thus, if number = 4.656
, the output is: 00004.656
For your example the output will look like this:
numbers = [23.2300, 0.1233, 1.0000, 4.2230, 9887.2000]
for x in numbers:
print('{:010.4f}'.format(x))
prints:
00023.2300
00000.1233
00001.0000
00004.2230
09887.2000
One example where this may be useful is when you want to properly list filenames in alphabetical order. I noticed in some linux systems, the number is: 1,10,11,..2,20,21,...
Thus if you want to enforce the necessary numeric order in filenames, you need to left pad with the appropriate number of zeros.
There is also a shorthand of doing this:
NSArray *persons = @[person1, person2, person3];
It's equivalent to
NSArray *persons = [NSArray arrayWithObjects:person1, person2, person3, nil];
As iiFreeman said, you still need to do proper memory management if you're not using ARC.
You can do something like this:
.flex {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.flex>div {_x000D_
flex: 1 0 50%;_x000D_
}_x000D_
_x000D_
.flex>div:first-child {_x000D_
flex: 0 1 100%;_x000D_
}
_x000D_
<div class="flex">_x000D_
<div>Hi</div>_x000D_
<div>Hello</div>_x000D_
<div>Hello 2</div>_x000D_
</div>
_x000D_
Here is a demo: http://jsfiddle.net/73574emn/1/
This model relies on the line-wrap after one "row" is full. Since we set the first item's flex-basis
to be 100% it fills the first row completely. Special attention on the flex-wrap: wrap;
I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "="
in the scope. Here's three solutions depending on your situation.
I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.
If your variable is changing, or is fetched through a request, you should use $observe
or $watch
:
app.directive('yourDirective', function () {
return {
restrict: 'A',
// NB: no isolated scope!!
link: function (scope, element, attrs) {
// observe changes in attribute - could also be scope.$watch
attrs.$observe('yourDirective', function (value) {
if (value) {
console.log(value);
// pass value to app controller
scope.variable = value;
}
});
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: ['$scope', '$element', '$attrs',
function ($scope, $element, $attrs) {
// observe changes in attribute - could also be scope.$watch
$attrs.$observe('yourDirective', function (value) {
if (value) {
console.log(value);
// pass value to app controller
$scope.variable = value;
}
});
}
]
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$watch('variable', function (value) {
if (value) {
console.log(value);
}
});
}]);
And here's the html (remember the brackets!):
<div ng-controller="MyCtrl">
<div your-directive="{{ someObject.someVariable }}"></div>
<!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
Note that you should not set the variable to "="
in the scope, if you are using the $observe
function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn)
(, or #3 if your variable is not changing).
If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout
to wait until the $apply
has run. Also we need to use $emit
to send it to the parent scope app controller (due to the isolated scope in the directive):
app.directive('yourDirective', ['$timeout', function ($timeout) {
return {
restrict: 'A',
// NB: isolated scope!!
scope: {
yourDirective: '='
},
link: function (scope, element, attrs) {
// wait until after $apply
$timeout(function(){
console.log(scope.yourDirective);
// use scope.$emit to pass it to controller
scope.$emit('notification', scope.yourDirective);
});
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: [ '$scope', function ($scope) {
// wait until after $apply
$timeout(function(){
console.log($scope.yourDirective);
// use $scope.$emit to pass it to controller
$scope.$emit('notification', scope.yourDirective);
});
}]
};
}])
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$on('notification', function (evt, value) {
console.log(value);
$scope.variable = value;
});
}]);
And here's the html (no brackets!):
<div ng-controller="MyCtrl">
<div your-directive="someObject.someVariable"></div>
<!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
If your variable is not changing and you need to evaluate it in your directive, you can use the $eval
function:
app.directive('yourDirective', function () {
return {
restrict: 'A',
// NB: no isolated scope!!
link: function (scope, element, attrs) {
// executes the expression on the current scope returning the result
// and adds it to the scope
scope.variable = scope.$eval(attrs.yourDirective);
console.log(scope.variable);
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: ['$scope', '$element', '$attrs',
function ($scope, $element, $attrs) {
// executes the expression on the current scope returning the result
// and adds it to the scope
scope.variable = scope.$eval($attrs.yourDirective);
console.log($scope.variable);
}
]
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$watch('variable', function (value) {
if (value) {
console.log(value);
}
});
}]);
And here's the html (remember the brackets!):
<div ng-controller="MyCtrl">
<div your-directive="{{ someObject.someVariable }}"></div>
<!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519
Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED
For the interested: here's an article on the angular life cycle
do a phpinfo(), and look for session.save_path. the directory there needs to have the correct permissions for the user and/or group that your webserver runs as
Modern browsers today seem to block (by default) these autoplay features. They are somewhat treated as pop-ops. Very intrusive. So yeah, users now have the complete control on when the sounds are played. [1,2,3]
<audio controls autoplay loop hidden>
<source src="audio.mp3" type="audio/mpeg">
</audio>
<embed src="audio.mp3" style="visibility:hidden" />
You instruction require call to get, because is it bring the records and orderBy the catalog
$results = Project::orderBy('name')
->get();
Example:
$results = Result::where ('id', '>=', '20')
->orderBy('id', 'desc')
->get();
In the example the data is filtered by "where" and bring records greater than 20 and orderBy catalog by order from high to low.
http://www.bootply.com/3iSOTAyumP in this example the button for collapse was not clickable because the .navbar-brand was in front.
http://www.bootply.com/RfnEgu45qR there is an updated version where the collapse buttons is actually clickable.
I came across a similar problem (wanting to pull a commit that included some binary files which caused conflicts when merged), but came across a different solution that can be done entirely using git (i.e. not having to manually copy files over). I figured I'd include it here so at the very least I can remember it the next time I need it. :) The steps look like this:
% git fetch
This fetches the latest commit(s) from the remote repository (you may need to specify a remote branch name, depending on your setup), but doesn't try to merge them. It records the the commit in FETCH_HEAD
% git checkout FETCH_HEAD stuff/to/update
This takes the copy of the binary files I want and overwrites what's in the working tree with the version fetched from the remote branch. git doesn't try to do any merging, so you just end up with an exact copy of the binary file from the remote branch. Once that's done, you can add/commit the new copy just like normal.
The "table-column" display type means it acts like the <col>
tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.
See the W3C standard for more information about the CSS table model.
* And a few other properties like borders, backgrounds.
I found this very helpful doc at Angular 2's website. It finally let me get things working properly, whereas the other answers here, to install typings, failed me with various errors. (But helped lead me in the right direction.)
Instead of including es6-promise and es6-collections, it includes core-js, which did the trick for me... no conflicts with Angular2's core ts definitions. Additionally the document explained how to set up all this to happen automatically when installing NPM, and how to modify your typings.json file.
If you don't want to get involved with locales here is a function that formats numbers:
def int_format(value, decimal_points=3, seperator=u'.'):
value = str(value)
if len(value) <= decimal_points:
return value
# say here we have value = '12345' and the default params above
parts = []
while value:
parts.append(value[-decimal_points:])
value = value[:-decimal_points]
# now we should have parts = ['345', '12']
parts.reverse()
# and the return value should be u'12.345'
return seperator.join(parts)
Creating a custom template filter from this function is trivial.
for me, this worked
exec utl_mail.send@myotherdb(
sender => '[email protected]',recipients => '[email protected],
cc => null, subject => 'my subject', message => 'my message'
);
var str = "How are you doing today?";
var res = str.split(" ");
Here the variable "res" is kind of array.
You can also take this explicity by declaring it as
var res[]= str.split(" ");
Now you can access the individual words of the array. Suppose you want to access the third element of the array you can use it by indexing array elements.
var FirstElement= res[0];
Now the variable FirstElement contains the value 'How'
try this
<iframe name="myIframe" id="myIframe" width="400px" height="400px" runat="server"></iframe>
Expose this iframe in the master page's codebehind:
public HtmlControl iframe
{
get
{
return this.myIframe;
}
}
Add the MasterType directive for the content page to strongly typed Master Page.
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>
In code behind
protected void Page_Load(object sender, EventArgs e)
{
this.Master.iframe.Attributes.Add("src", "some.aspx");
}
SynchronousQueue
( Taken from another question )SynchronousQueue
is more of a handoff, whereas the LinkedBlockingQueue
just allows a single element. The difference being that the put()
call to a SynchronousQueue
will not return until there is a corresponding take()
call, but with a LinkedBlockingQueue
of size 1, the put()
call (to an empty queue) will return immediately. It's essentially the BlockingQueue
implementation for when you don't really want a queue (you don't want to maintain any pending data).
LinkedBlockingQueue
(LinkedList
Implementation but Not Exactly JDK Implementation of LinkedList
It uses static inner class Node to maintain Links between elements )Constructor for LinkedBlockingQueue
public LinkedBlockingQueue(int capacity)
{
if (capacity < = 0) throw new IllegalArgumentException();
this.capacity = capacity;
last = head = new Node< E >(null); // Maintains a underlying linkedlist. ( Use when size is not known )
}
Node class Used to Maintain Links
static class Node<E> {
E item;
Node<E> next;
Node(E x) { item = x; }
}
3 . ArrayBlockingQueue ( Array Implementation )
Constructor for ArrayBlockingQueue
public ArrayBlockingQueue(int capacity, boolean fair)
{
if (capacity < = 0)
throw new IllegalArgumentException();
this.items = new Object[capacity]; // Maintains a underlying array
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
IMHO Biggest Difference between ArrayBlockingQueue
and LinkedBlockingQueue
is clear from constructor one has underlying data structure Array and other linkedList.
ArrayBlockingQueue
uses single-lock double condition algorithm and LinkedBlockingQueue
is variant of the "two lock queue" algorithm and it has 2 locks 2 conditions ( takeLock , putLock)
For 'Hello' at the start of the string:
SELECT STUFF('Hello World', 1, 6, '')
This will work for 'Hello' anywhere in the string:
SELECT REPLACE('Hello World', 'Hello ', '')
This is an old question but you can also use express-validator package to check request params
express-validator version 4 (latest):
validator = require('express-validator/check');
app.get('/show/:id', [
validator.param('id').isMongoId().trim()
], function(req, res) {
// validation result
var errors = validator.validationResult(req);
// check if there are errors
if ( !errors.isEmpty() ) {
return res.send('404');
}
// else
model.findById(req.params.id, function(err, doc) {
return res.send(doc);
});
});
express-validator version 3:
var expressValidator = require('express-validator');
app.use(expressValidator(middlewareOptions));
app.get('/show/:id', function(req, res, next) {
req.checkParams('id').isMongoId();
// validation result
req.getValidationResult().then(function(result) {
// check if there are errors
if ( !result.isEmpty() ) {
return res.send('404');
}
// else
model.findById(req.params.id, function(err, doc) {
return res.send(doc);
});
});
});
OK, from background knowledge and from reading the Wikipedia page to which you pointed, it appears that reactive programming is something like dataflow computing but with specific external "stimuli" triggering a set of nodes to fire and perform their computations.
This is pretty well suited to UI design, for example, in which touching a user interface control (say, the volume control on a music playing application) might need to update various display items and the actual volume of audio output. When you modify the volume (a slider, let's say) that would correspond to modifying the value associated with a node in a directed graph.
Various nodes having edges from that "volume value" node would automatically be triggered and any necessary computations and updates would naturally ripple through the application. The application "reacts" to the user stimulus. Functional reactive programming would just be the implementation of this idea in a functional language, or generally within a functional programming paradigm.
For more on "dataflow computing", search for those two words on Wikipedia or using your favorite search engine. The general idea is this: the program is a directed graph of nodes, each performing some simple computation. These nodes are connected to each other by graph links that provide the outputs of some nodes to the inputs of others.
When a node fires or performs its calculation, the nodes connected to its outputs have their corresponding inputs "triggered" or "marked". Any node having all inputs triggered/marked/available automatically fires. The graph might be implicit or explicit depending on exactly how reactive programming is implemented.
Nodes can be looked at as firing in parallel, but often they are executed serially or with limited parallelism (for example, there may be a few threads executing them). A famous example was the Manchester Dataflow Machine, which (IIRC) used a tagged data architecture to schedule execution of nodes in the graph through one or more execution units. Dataflow computing is fairly well suited to situations in which triggering computations asynchronously giving rise to cascades of computations works better than trying to have execution be governed by a clock (or clocks).
Reactive programming imports this "cascade of execution" idea and seems to think of the program in a dataflow-like fashion but with the proviso that some of the nodes are hooked to the "outside world" and the cascades of execution are triggered when these sensory-like nodes change. Program execution would then look like something analogous to a complex reflex arc. The program may or may not be basically sessile between stimuli or may settle into a basically sessile state between stimuli.
"non-reactive" programming would be programming with a very different view of the flow of execution and relationship to external inputs. It's likely to be somewhat subjective, since people will likely be tempted to say anything that responds to external inputs "reacts" to them. But looking at the spirit of the thing, a program that polls an event queue at a fixed interval and dispatches any events found to functions (or threads) is less reactive (because it only attends to user input at a fixed interval). Again, it's the spirit of the thing here: one can imagine putting a polling implementation with a fast polling interval into a system at a very low level and program in a reactive fashion on top of it.
try staring jboss with ./standalone.sh -c standalone-full.xml or any other alternative that allows you to start with the full profile
Once I changed Options -Index
to Options +Index
in my conf file, I removed the welcome page and restarted services.
$ sudo rm -f /etc/httpd/conf.d/welcome.conf
$ sudo service httpd restart
I was able to see directory listings after that.
If you have Notepad++ and you get this .sh Error Message: "command not found" or this autoconf Error Message "line 615: ../../autoconf/bin/autom4te: No such file or directory".
On your Notepad++, Go to Edit -> EOL Conversion then check Macinthos(CR). This will edit your files. I also encourage to check all files with this command, because soon such an error will occur.
As an addition to Yorro's answer, it can also be done by using attributes.
Sample for int
type unique key combination:
[Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
public int UniqueKeyIntPart1 { get; set; }
[Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
public int UniqueKeyIntPart2 { get; set; }
If the data type is string
, then MaxLength
attribute must be added:
[Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
[MaxLength(50)]
public string UniqueKeyStringPart1 { get; set; }
[Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
[MaxLength(50)]
public string UniqueKeyStringPart2 { get; set; }
If there is a domain/storage model separation concern, using Metadatatype
attribute/class can be an option: https://msdn.microsoft.com/en-us/library/ff664465%28v=pandp.50%29.aspx?f=255&MSPPError=-2147217396
A quick console app example:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace EFIndexTest
{
class Program
{
static void Main(string[] args)
{
using (var context = new AppDbContext())
{
var newUser = new User { UniqueKeyIntPart1 = 1, UniqueKeyIntPart2 = 1, UniqueKeyStringPart1 = "A", UniqueKeyStringPart2 = "A" };
context.UserSet.Add(newUser);
context.SaveChanges();
}
}
}
[MetadataType(typeof(UserMetadata))]
public class User
{
public int Id { get; set; }
public int UniqueKeyIntPart1 { get; set; }
public int UniqueKeyIntPart2 { get; set; }
public string UniqueKeyStringPart1 { get; set; }
public string UniqueKeyStringPart2 { get; set; }
}
public class UserMetadata
{
[Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
public int UniqueKeyIntPart1 { get; set; }
[Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
public int UniqueKeyIntPart2 { get; set; }
[Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
[MaxLength(50)]
public string UniqueKeyStringPart1 { get; set; }
[Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
[MaxLength(50)]
public string UniqueKeyStringPart2 { get; set; }
}
public class AppDbContext : DbContext
{
public virtual DbSet<User> UserSet { get; set; }
}
}
I was able to get this to work by using the Invoke-Expression
cmdlet.
Invoke-Expression "& `"$scriptPath`" test -r $number -b $testNumber -f $FileVersion -a $ApplicationID"
// this class will authenticate LDAP UserName or Email
// simply call LdapAuth.authenticateUserAndGetInfo (username,password);
//Note: Configure ldapURI ,requiredAttributes ,ADSearchPaths,accountSuffex
import java.util.*;
import javax.naming.*;
import java.util.regex.*;
import javax.naming.directory.*;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class LdapAuth {
private final static String ldapURI = "ldap://20.200.200.200:389/DC=corp,DC=local";
private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
private static String[] requiredAttributes = {"cn","givenName","sn","displayName","userPrincipalName","sAMAccountName","objectSid","userAccountControl"};
// see you active directory user OU's hirarchy
private static String[] ADSearchPaths =
{
"OU=O365 Synced Accounts,OU=ALL USERS",
"OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",
"OU=In-House,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",
"OU=Torbram Users,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",
"OU=Migrated Users,OU=TES-Users"
};
private static String accountSuffex = "@corp.local"; // this will be used if user name is just provided
private static void authenticateUserAndGetInfo (String user, String password) throws Exception {
try {
Hashtable<String,String> env = new Hashtable <String,String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
env.put(Context.PROVIDER_URL, ldapURI);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, user);
env.put(Context.SECURITY_CREDENTIALS, password);
DirContext ctx = new InitialDirContext(env);
String filter = "(sAMAccountName="+user+")"; // default for search filter username
if(user.contains("@")) // if user name is a email then
{
//String parts[] = user.split("\\@");
//use different filter for email
filter = "(userPrincipalName="+user+")";
}
SearchControls ctrl = new SearchControls();
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctrl.setReturningAttributes(requiredAttributes);
NamingEnumeration userInfo = null;
Integer i = 0;
do
{
userInfo = ctx.search(ADSearchPaths[i], filter, ctrl);
i++;
} while(!userInfo.hasMore() && i < ADSearchPaths.length );
if (userInfo.hasMore()) {
SearchResult UserDetails = (SearchResult) userInfo.next();
Attributes userAttr = UserDetails.getAttributes();System.out.println("adEmail = "+userAttr.get("userPrincipalName").get(0).toString());
System.out.println("adFirstName = "+userAttr.get("givenName").get(0).toString());
System.out.println("adLastName = "+userAttr.get("sn").get(0).toString());
System.out.println("name = "+userAttr.get("cn").get(0).toString());
System.out.println("AdFullName = "+userAttr.get("cn").get(0).toString());
}
userInfo.close();
}
catch (javax.naming.AuthenticationException e) {
}
}
}
C# 4.0 also supports optional parameters, which could be useful in some other situations. See this article.
The use of extending application just make your application sure for any kind of operation that you want throughout your application running period. Now it may be any kind of variables and suppose if you want to fetch some data from server then you can put your asynctask in application so it will fetch each time and continuously, so that you will get a updated data automatically.. Use this link for more knowledge....
http://www.intridea.com/blog/2011/5/24/how-to-use-application-object-of-android
I have this generic utility method. I pass in a list of a given type (Assuming you have a supporting class) and it generates a datatable with the properties as column headers and the list items as data.
Just like in standard MVC, if you dont have DisplayName attribute defined, it will fall back to the property name so you only have to include DisplayName where it is different to the property name.
public DataTable BuildDataTable<T>(IList<T> data)
{
//Get properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
//.Where(p => !p.GetGetMethod().IsVirtual && !p.GetGetMethod().IsFinal).ToArray(); //Hides virtual properties
//Get column headers
bool isDisplayNameAttributeDefined = false;
string[] headers = new string[Props.Length];
int colCount = 0;
foreach (PropertyInfo prop in Props)
{
isDisplayNameAttributeDefined = Attribute.IsDefined(prop, typeof(DisplayNameAttribute));
if (isDisplayNameAttributeDefined)
{
DisplayNameAttribute dna = (DisplayNameAttribute)Attribute.GetCustomAttribute(prop, typeof(DisplayNameAttribute));
if (dna != null)
headers[colCount] = dna.DisplayName;
}
else
headers[colCount] = prop.Name;
colCount++;
isDisplayNameAttributeDefined = false;
}
DataTable dataTable = new DataTable(typeof(T).Name);
//Add column headers to datatable
foreach (var header in headers)
dataTable.Columns.Add(header);
dataTable.Rows.Add(headers);
//Add datalist to datatable
foreach (T item in data)
{
object[] values = new object[Props.Length];
for (int col = 0; col < Props.Length; col++)
values[col] = Props[col].GetValue(item, null);
dataTable.Rows.Add(values);
}
return dataTable;
}
If there's a more efficient / safer way of doing this, I'd appreicate any feedback. The commented //Where clause will filter out virtual properties. Useful if you are using model classes directly as EF puts in "Navigation" properties as virtual. However it will also filter out any of your own virtual properties if you choose to extend such classes. For this reason, I prefer to make a ViewModel and decorate it with only the needed properties and display name attributes as required, then make a list of them.
Hope this helps.
Just for row, but try referencing a cell just below the selected cell and subtracting one from row.
=ROW(A2)-1
Yields the Row of cell A1 (This formula would go in cell A1.
This avoids all the indirect() and index() use but still works.
If your input string doesn't contain forward slashes then you can use basename
and a subshell:
$ basename "$(echo 'maps.google.com' | tr '.' '/')"
This doesn't use sed
or awk
but it also doesn't use cut
either, so I'm not quite sure if it qualifies as an answer to the question as its worded.
This doesn't work well if processing input strings that can contain forward slashes. A workaround for that situation would be to replace forward slash with some other character that you know isn't part of a valid input string. For example, the pipe (|
) character is also not allowed in filenames, so this would work:
$ basename "$(echo 'maps.google.com/some/url/things' | tr '/' '|' | tr '.' '/')" | tr '|' '/'
Right click the database itself, Tasks -> Generate Scripts...
Then follow the wizard.
For SSMS2008+, if you want to also export the data, on the "Set Scripting Options" step, select the "Advanced" button and change "Types of data to script" from "Schema Only" to "Data Only" or "Schema and Data".
In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.
In this case, you don't need to add any wrapper functions around lists.
You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.
According to the page:
This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.
Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.
Alright so for me, the error being fixed is when there are different versions of python installed and yum can't find a certain .so file and throws an exception.
yum wants 2.7.5 according to the error.
which python gives me /usr/bin/python
python --version gives me 2.7.5
The fix for me was append /lib64 to the LD_LIBRARY_PATH environment variable. The relevant content is /lib64/python2.7 and /lib64/python3.6.
export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH
Fixed the yum error for me with multiple python versions installed.
Update 2019-01-23
If you’re repeatedly getting the following error The workspace wkspaceEg does not exist…
even after employing the correct username (wkspcOwnerDomain\wkspcOwnerUsername
) in the tf workspace
command, e.g.,
tf workspace "wkspaceEg;wkspcOwnerDomain\wkspcOwnerUsername" /collection:http://tfs.example.com:8080/tfs/collectionEg /login:TFSUsername,TFSPassword
then the tf workfold
command may help fix it. See this question.
If even that doesn’t work and you’re unable/unwilling to use TFS Sidekicks, proceed to the risky last-ditch option below.
I’m using TFS 2012. I tried everything that was suggested online: deleted cache folder, used the workspaces dropdown, tf workspaces /remove:*, cleared credentials from Control Panel, IE, etc.
Nothing worked, I believe my workspace got corrupted somehow. Finally, I went to the TFS database and ran the following queries. That worked! Of course be very careful when messing with the database, take backups, etc.
The database is called Tfs_<<your_TFS_collection_name>>
. Ignore the Tfs_Configuration
MSSQL database. I'm not sure but if you don't have a Tfs_<<your_TFS_collection_name>>
database, settings might be in the Tfs_DefaultCollection
database. Mapping is stored in tbl_WorkingFolder.LocalItem
.
/*Find correct workspace*/
SELECT WorkspaceId, *
FROM tbl_Workspace
ORDER BY WorkspaceName
/*View the existing mapping*/
SELECT LocalItem, *
FROM tbl_WorkingFolder
WHERE WorkspaceId = <<WorkspaceId from above>>
/*Update mapping*/
UPDATE tbl_WorkingFolder
SET LocalItem = 'D:\Legacy.00\TFS\Source\Workspaces\teamProjEg' WHERE
/*LocalItem = NULL might work too but I haven't tried it*/
WorkspaceId = <<WorkspaceId from above>>
I don't know that what you want to do is possible. From my understanding, sending an email from a web form requires a server side language to communicate with a mail server and send messages.
Are you running PHP or ASP.NET?
If you're running Linux I would suggest two tools:
align_image_stack from package hugin-tools - is a commandline program that can automatically correct rotation, scaling, and other distortions (it's mostly intended for compositing HDR photography, but works for video frames and other documents too). More information: http://hugin.sourceforge.net/docs/manual/Align_image_stack.html
compare from package imagemagick - a program that can find and count the amount of different pixels in two images. Here's a neat tutorial: http://www.imagemagick.org/Usage/compare/ uising the -fuzz N% you can increase the error tolerance. The higher the N the higher the error tolerance to still count two pixels as the same.
align_image_stack should correct any offset so the compare command will actually have a chance of detecting same pixels.
If you just want to check if that item exists:
IEnumerable<DataGridViewRow> rows = grdPdfs.Rows
.Cast<DataGridViewRow>()
.Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue));
if (rows.Count() == 0)
{
// Not Found
}
else
{
// Found
}
How about a bitwise operator? Instead of strings, you're dealing with "enums", which looks more "elegant."
// Declare slider's state "enum"
var SliderOne = {
A: 1,
B: 2,
C: 4,
D: 8,
E: 16
};
var SliderTwo = {
A: 32,
B: 64,
C: 128,
D: 256,
E: 512
};
// Set state
var s1 = SliderOne.A,
s2 = SliderTwo.B;
// Switch state
switch (s1 | s2) {
case SliderOne.A | SliderTwo.A :
case SliderOne.A | SliderTwo.C :
// Logic when State #1 is A, and State #2 is either A or C
break;
case SliderOne.B | SliderTwo.C :
// Logic when State #1 is B, and State #2 is C
break;
case SliderOne.E | SliderTwo.E :
default:
// Logic when State #1 is E, and State #2 is E or
// none of above match
break;
}
I however agree with others, 25 cases in a switch-case logic is not too pretty, and if-else might, in some cases, "look" better. Anyway.
$('#checkbox').change(function(){
(this.checked)?$('p').css('color','#0099ff'):$('p').css('color','another_color');
});
The problem with your code is that the your script is executed prior to the html element being available. Because of the that var comment
is an empty array.
So you should move your script after the html element is available.
Also, getElementsByClassName
returns html collection, so if you need to add event Listener to an element, you will need to do something like following
comment[0].addEventListener('click' , showComment , false ) ;
If you want to add event listener to all the elements, then you will need to loop through them
for (var i = 0 ; i < comment.length; i++) {
comment[i].addEventListener('click' , showComment , false ) ;
}
Tested on both spark-shell
version 1.6.3
and spark2-shell
version 2.3.0.2.6.5.179-4
, you can directly pipe to the shell's stdin like
spark-shell <<< "1+1"
or in your use case,
spark-shell < file.spark
As of cocoapods 1.7.2 you can use the cdn instead of github. It's blazing fast and it won't hang. :) The cdn is default from cocopods 1.8.0 onwards.
To use the CDN source in your Podfile:
If you don't have private specs:
source 'https://cdn.cocoapods.org/'
If you have private specs:
source 'https://github.com/artsy/Specs.git' - source 'https://github.com/CocoaPods/Specs.git' + source 'https://cdn.cocoapods.org/'
Doing this will break your Podfile.lock, so you are likely to need to run pod update to see the changes (be careful, this may update your Pods also).
If you have a CI setup, it is recommended to cache the new repo dir as it is very small and would save even more time. With 1.7.2 it should be located at ~/.cocoapods/repos/cocoapods- (yes, with a -), but we're looking to improve the naming in an upcoming release.
More info:
If you want movie details api you can consider
OMDB API which is Open movies Database Returns IBDB Rating, IMDB Votes and you can include Rotten Tomato rating too.
Or else You can use
My Api Films which allows you to search with IMDB ID and returns detailed information but it has request limits.
Use the same process. You already have the variable iDiv
which still refers to the original element <div id='block'>
you've created. You just need to create another <div>
and call appendChild()
.
// Your existing code unmodified...
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);
// Now create and append to iDiv
var innerDiv = document.createElement('div');
innerDiv.className = 'block-2';
// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);
The order of event creation doesn't have to be as I have it above. You can alternately append the new innerDiv
to the outer div before you add both to the <body>
.
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
// Create the inner div before appending to the body
var innerDiv = document.createElement('div');
innerDiv.className = 'block-2';
// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);
// Then append the whole thing onto the body
document.getElementsByTagName('body')[0].appendChild(iDiv);
With openssl
:
openssl x509 -enddate -noout -in file.pem
The output is on the form:
notAfter=Nov 3 22:23:50 2014 GMT
Also see MikeW's answer for how to easily check whether the certificate has expired or not, or whether it will within a certain time period, without having to parse the date above.
While LIKE
is suitable for this case, a more general purpose solution is to use instr
, which doesn't require characters in the search string to be escaped. Note: instr
is available starting from Sqlite 3.7.15.
SELECT *
FROM TABLE
WHERE instr(column, 'cats') > 0;
Also, keep in mind that LIKE
is case-insensitive, whereas instr
is case-sensitive.
double RoundTo2Decimals(double val) {
DecimalFormat df2 = new DecimalFormat("###.##");
return Double.valueOf(df2.format(val));
}
See full gist here and live example here.
#hero { width:100%;height:100%;background:url('{$img_ps_dir}cms/how-it-works/hero.jpg') no-repeat top center; }
.videoWrapper { position:relative;padding-bottom:56.25%;padding-top:25px;max-width:100%; }
<div id="hero">
<div class="container">
<div class="row-fluid">
<script src="https://www.youtube.com/iframe_api"></script>
<center>
<div class="videoWrapper">
<div id="player"></div>
</div>
</center>
<script>
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId:'xxxxxxxxxxx',playerVars: { controls:0,autoplay:0,disablekb:1,enablejsapi:1,iv_load_policy:3,modestbranding:1,showinfo:0,rel:0,theme:'light' }
} );
resizeHeroVideo();
}
</script>
</div>
</div>
</div>
var player = null;
$( document ).ready(function() {
resizeHeroVideo();
} );
$(window).resize(function() {
resizeHeroVideo();
});
function resizeHeroVideo() {
var content = $('#hero');
var contentH = viewportSize.getHeight();
contentH -= 158;
content.css('height',contentH);
if(player != null) {
var iframe = $('.videoWrapper iframe');
var iframeH = contentH - 150;
if (isMobile) {
iframeH = 163;
}
iframe.css('height',iframeH);
var iframeW = iframeH/9 * 16;
iframe.css('width',iframeW);
}
}
resizeHeroVideo is called only after the Youtube player has fully loaded (on page load does not work), and whenever the browser window is resized. When it runs, it calculates the height and width of the iframe and assigns the appropriate values maintaining the correct aspect ratio. This works whether the window is resized horizontally or vertically.
In large part, pointers are arrays (in C/C++) - they are addresses in memory, and can be accessed like an array if desired (in "normal" cases).
Since they're the address of an item, they're small: they take up only the space of an address. Since they're small, sending them to a function is cheap. And then they allow that function to work on the actual item rather than a copy.
If you want to do dynamic storage allocation (such as for a linked-list), you must use pointers, because they're the only way to grab memory from the heap.
I need to somehow query Google and ask: Is this access token valid for [email protected]?
No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.
The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.
So you need be from same domain as 'public interface'.
And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.
These data types are synonyms.
Simple:
byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);
<div class="example" align="center">
<div class="menuholder">
<ul class="menu slide">
<li><a href="index.php?id=1" class="blue">Home</a></li>
<li><a href="index.php?id=14" class="blue">About Us</a></li>
<li><a href="index.php?id=4" class="blue">Mens</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=15">Coats & Jackets</a></dd>
<dd><a href="index.php?id=22">Chinos</a></dd>
<dd><a href="index.php?id=23">Jeans</a></dd>
<dd><a href="index.php?id=24">Jumpers & Cardigans</a></dd>
<dd><a href="index.php?id=25">Linen</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=26">Polo Shirts</a></dd>
<dd><a href="index.php?id=16">Shirts Casual</a></dd>
<dd><a href="index.php?id=27">Shirts Formal</a></dd>
<dd><a href="index.php?id=28">Shorts</a></dd>
<dd><a href="index.php?id=18">Sportswear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=19">Tops & T-Shirts</a></dd>
<dd><a href="index.php?id=20">Trousers Casual</a></dd>
<dd><a href="index.php?id=29">Trousers Formal</a></dd>
<dd><a href="index.php?id=30">Nightwear</a></dd>
<dd><a href="index.php?id=17">Socks</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=21">Underwear</a></dd>
<dd><a href="index.php?id=31">Swimwear</a></dd>
</dl>
</div>
</li>
<!--menu-->
<li><a href="index.php?id=5" class="blue">Ladie's</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=32">Coats & Jackets</a></dd>
<dd><a href="index.php?id=33">Dresses</a></dd>
<dd><a href="index.php?id=34">Jeans</a></dd>
<dd><a href="index.php?id=35">Jumpers & Cardigans</a></dd>
<dd><a href="index.php?id=36">Jumpsuits</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=37">Leggings & Jeggings</a></dd>
<dd><a href="index.php?id=38">Linen</a></dd>
<dd><a href="index.php?id=39">Lingerie & Underwear</a></dd>
<dd><a href="index.php?id=40">Maternity Wear</a></dd>
<dd><a href="index.php?id=41">Nightwear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=42">Shorts</a></dd>
<dd><a href="index.php?id=43">Skirts</a></dd>
<dd><a href="index.php?id=44">Sportswear</a></dd>
<dd><a href="index.php?id=45">Suits & Tailoring</a></dd>
<dd><a href="index.php?id=46">Swimwear & Beachwear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=47">Thermals</a></dd>
<dd><a href="index.php?id=48">Tops & T-Shirts</a></dd>
<dd><a href="index.php?id=49">Trousers & Chinos</a></dd>
<dd><a href="index.php?id=50">Socks</a></dd>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=7" class="blue">Girls</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=51">Coats & Jackets</a></dd>
<dd><a href="index.php?id=52">Dresses</a></dd>
<dd><a href="index.php?id=53">Jeans</a></dd>
<dd><a href="index.php?id=54">Joggers & Sweatshirts</a></dd>
<dd><a href="index.php?id=55">Jumpers & Cardigans</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=56">Jumpsuits & Playsuits</a></dd>
<dd><a href="index.php?id=57">Leggings</a></dd>
<dd><a href="index.php?id=58">Nightwear</a></dd>
<dd><a href="index.php?id=59">Shorts</a></dd>
<dd><a href="index.php?id=60">Skirts</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=61">Swimwear</a></dd>
<dd><a href="index.php?id=62">Tops & T-Shirts</a></dd>
<dd><a href="index.php?id=63">Trousers & Jeans</a></dd>
<dd><a href="index.php?id=64">Socks</a></dd>
<dd><a href="index.php?id=65">Underwear</a></dd>
</dl>
<dl>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=8" class="blue">Boys</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=66">Coats & Jackets</a></dd>
<dd><a href="index.php?id=67">Jeans</a></dd>
<dd><a href="index.php?id=68">Joggers & Sweatshirts</a></dd>
<dd><a href="index.php?id=69">Jumpers & Cardigans</a></dd>
<dd><a href="index.php?id=70">Nightwear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=71">Shirts</a></dd>
<dd><a href="index.php?id=72">Shorts</a></dd>
<dd><a href="index.php?id=73">Sportswear</a></dd>
<dd><a href="index.php?id=74">Swimwear</a></dd>
<dd><a href="index.php?id=75">T-Shirts & Polo Shirts</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=76">Trousers & Jeans</a></dd>
<dd><a href="index.php?id=77">Socks</a></dd>
<dd><a href="index.php?id=78">Underwear</a></dd>
</dl>
<dl>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=9" class="blue">Toddlers</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=79">Newborn</a></dd>
<dd><a href="index.php?id=80">0-2 Years</a></dd>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=10" class="blue">Accessories</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=81">Shoes</a></dd>
<dd><a href="index.php?id=82">Ties</a></dd>
<dd><a href="index.php?id=83">Caps</a></dd>
<dd><a href="index.php?id=84">Belts</a></dd>
</dl>
</div>
</li><!--menu end-->
<li><a href="index.php?id=13" class="blue">Contact Us</a></li>
</ul>
<div class="back"></div>
<div class="shadow"></div>
</div>
<div style="clear:both"></div>
</div>
CSS 3 Coding- Copy and Paste
<style>
body{margin:0px;}
.example {
width:980px;
height:40px;
margin:0px auto;
position:absolute;
margin-bottom:60px;
top:95px;
}
.menuholder {
float:left;
font:normal bold 11px/35px verdana, sans-serif;
overflow:hidden;
position:relative;
}
.menuholder .shadow {
-moz-box-shadow:0 0 20px rgba(0, 0, 0, 1);
-o-box-shadow:0 0 20px rgba(0, 0, 0, 1);
-webkit-box-shadow:0 0 20px rgba(0, 0, 0, 1);
background:#888;
box-shadow:0 0 20px rgba(0, 0, 0, 1);
height:10px;
left:5%;
position:absolute;
top:-9px;
width:100%;
z-index:100;
}
.menuholder .back {
-moz-transition-duration:.4s;
-o-transition-duration:.4s;
-webkit-transition-duration:.4s;
background-color:rgba(0, 0, 0, 0.88);
height:0;
width:980px; /*100%*/
}
.menuholder:hover div.back {
height:280px;
}
ul.menu {
display:block;
float:left;
list-style:none;
margin:0;
padding:0 125px;
position:relative;
}
ul.menu li {
float:left;
margin:0 10px 0 0;
}
ul.menu li > a {
-moz-border-radius:0 0 10px 10px;
-moz-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
-moz-transition:all 0.3s ease-in-out;
-o-border-radius:0 0 10px 10px;
-o-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
-o-transition:all 0.3s ease-in-out;
-webkit-border-bottom-left-radius:10px;
-webkit-border-bottom-right-radius:10px;
-webkit-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
-webkit-transition:all 0.3s ease-in-out;
border-radius:0 0 10px 10px;
box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
color:#eee;
display:block;
padding:0 10px;
text-decoration:none;
transition:all 0.3s ease-in-out;
}
ul.menu li a.red {
background:#a00;
}
ul.menu li a.orange {
background:#da0;
}
ul.menu li a.yellow {
background:#aa0;
}
ul.menu li a.green {
background:#060;
}
ul.menu li a.blue {
background:#073263;
}
ul.menu li a.violet {
background:#682bc2;
}
.menu li div.subs {
left:0;
overflow:hidden;
position:absolute;
top:35px;
width:0;
}
.menu li div.subs dl {
-moz-transition-duration:.2s;
-o-transition-duration:.2s;
-webkit-transition-duration:.2s;
float:left;
margin:0 130px 0 0;
overflow:hidden;
padding:40px 0 5% 2%;
width:0;
}
.menu dt {
color:#fc0;
font-family:arial, sans-serif;
font-size:12px;
font-weight:700;
height:20px;
line-height:20px;
margin:0;
padding:0 0 0 10px;
white-space:nowrap;
}
.menu dd {
margin:0;
padding:0;
text-align:left;
}
.menu dd a {
background:transparent;
color:#fff;
font-size:12px;
height:20px;
line-height:20px;
padding:0 0 0 10px;
text-align:left;
white-space:nowrap;
width:80px;
}
.menu dd a:hover {
color:#fc0;
}
.menu li:hover div.subs dl {
-moz-transition-delay:0.2s;
-o-transition-delay:0.2s;
-webkit-transition-delay:0.2s;
margin-right:2%;
width:21%;
}
ul.menu li:hover > a,ul.menu li > a:hover {
background:#aaa;
color:#fff;
padding:10px 10px 0;
}
ul.menu li a.red:hover,ul.menu li:hover a.red {
background:#c00;
}
ul.menu li a.orange:hover,ul.menu li:hover a.orange {
background:#fc0;
}
ul.menu li a.yellow:hover,ul.menu li:hover a.yellow {
background:#cc0;
}
ul.menu li a.green:hover,ul.menu li:hover a.green {
background:#080;
}
ul.menu li a.blue:hover,ul.menu li:hover a.blue {
background:#00c;
}
ul.menu li a.violet:hover,ul.menu li:hover a.violet {
background:#8a2be2;
}
.menu li:hover div.subs,.menu li a:hover div.subs {
width:100%;
}
In my opinion this is the simplest solution
$orderby = 'name';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
);
$product_categories = get_terms( 'product_cat', $cat_args );
if( !empty($product_categories) ){
echo '
<ul>';
foreach ($product_categories as $key => $category) {
echo '
<li>';
echo '<a href="'.get_term_link($category).'" >';
echo $category->name;
echo '</a>';
echo '</li>';
}
echo '</ul>
';
}
This is how I make it work.
My Environment:
Angular CLI Global : 6.0.0, Local: 1.7.4, Angular: 5.2, Typescript 2.5.3
Note: To enable
ng Update
you need to install Angular CLI 6.0 firstnpm install -g @angular/cli or npm install @angular/cli
ng update //update Angular Package core/common/complier... to 6.0.0
ng update @angular/cli //change angular-cli.json to angular.json
optional if you have angular-material 5.4.2, ngx-translate 9.1.1, ng-bootstrap/ng-bootstrap 1.1.1:
ng update @angular/material //upgrade to 6.0.1
npm install @ngx-translate/[email protected] --save //upgrade ngX translate to 10.0.1 for Angular 6
5 npm install --save @ng-bootstrap/[email protected] //for ng-bootstrap
If you use Observable and get the error:
ERROR in node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Observable'. node_modules/rxjs/observable/of.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/observable/of'.
Change: import { Observable } from "rxjs/Observable"; import { of } from 'rxjs/observable/of';
To
import { Observable, of } from "rxjs";
Angular CLI issue: https://github.com/angular/angular-cli/issues/10621
There's a short discussion of what appears to be this issue here. The page it links to appears to be gone, but one of the responses might be what you need:
Indeed, copying US_export_policy.jar and local_policy.jar from core/lib/jce to $JAVA_HOME/jre/lib/security helped. Thanks.
You should be able to access the local database by using the name localhost
. There is also a way to determine the hostname of the computer you're running on, but it doesn't sound like you need that. As for the username, you can either (1) give permissions to the account that PHP runs under to access the database without a password, or (2) store the username and password that you need to connect with (hard-coded or stored in a config file), and pass those as arguments to mysql_connect
. See http://php.net/manual/en/function.mysql-connect.php.
Adding to Winnie's great answer,
If anyone is not able to find the postgresql.conf file location in your setup, you can always ask the postgres itself.
SHOW config_file;
For me changing the max_connections alone made the trick.
var params= new Dictionary<string, string>();
var url ="Please enter URLhere";
params.Add("key1", "value1");
params.Add("key2", "value2");
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(dict)).Result;
var tokne= response.Content.ReadAsStringAsync().Result;
}
//Get response as expected
Take an array containing months name.
String[] str = {"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"};
Then where you wanna take month use like follow:
if(i<str.length)
monthString = str[i-1];
else
monthString = "Invalid month";
I have not found a perfect solution but the best I could do was to use type="tel" and disable html5 validation (formnovalidate):
<input name="txtTest" type="tel" value="1,200.00" formnovalidate="formnovalidate" />
If the user puts in a comma it will output with the comma in every modern browser i tried (latest FF, IE, edge, opera, chrome, safari desktop, android chrome).
The main problem is:
For my use case I only had to:
If you have a similar requirement this should work for you.
Note: I did not like the support of the pattern attribute. The formnovalidate seems to work much better.
Well, for just getting the filename of your batch the easiest way would be to just use %~n0
.
@echo %~n0
will output the name (without the extension) of the currently running batch file (unless executed in a subroutine called by call
). The complete list of such “special” substitutions for path names can be found with help for
, at the very end of the help:
In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a fully qualified path name %~dI - expands %I to a drive letter only %~pI - expands %I to a path only %~nI - expands %I to a file name only %~xI - expands %I to a file extension only %~sI - expanded path contains short names only %~aI - expands %I to file attributes of file %~tI - expands %I to date/time of file %~zI - expands %I to size of file %~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only %~nxI - expands %I to a file name and extension only %~fsI - expands %I to a full path name with short names only
To precisely answer your question, however: Substrings are done using the :~start,length
notation:
%var:~10,5%
will extract 5 characters from position 10 in the environment variable %var%
.
NOTE: The index of the strings is zero based, so the first character is at position 0, the second at 1, etc.
To get substrings of argument variables such as %0
, %1
, etc. you have to assign them to a normal environment variable using set
first:
:: Does not work:
@echo %1:~10,5
:: Assign argument to local variable first:
set var=%1
@echo %var:~10,5%
The syntax is even more powerful:
%var:~-7%
extracts the last 7 characters from %var%
%var:~0,-4%
would extract all characters except the last four which would also rid you of the file extension (assuming three characters after the period [.
]).See help set
for details on that syntax.
In my humble opinion the best way is to just add a full day in milliseconds, depending on how you factor your code it can mess up if your on the last day of the month.
for example Feb 28 or march 31.
Here is an example of how i would do it:
var current = new Date(); //'Mar 11 2015' current.getTime() = 1426060964567
var followingDay = new Date(current.getTime() + 86400000); // + 1 day in ms
followingDay.toLocaleDateString();
imo this insures accuracy
here is another example i Do not like that can work for you but not as clean that dose the above
var today = new Date('12/31/2015');
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate()+1);
tomorrow.toLocaleDateString();
imho this === 'POOP'
So some of you have had gripes about my millisecond approach because of day light savings time. So Im going to bash this out. First, Some countries and states do not have Day light savings time. Second Adding exactly 24 hours is a full day. If the date number dose not change once a year but then gets fixed 6 months later i don't see a problem there. But for the purpose of being definite and having to deal with allot the evil Date() i have thought this through and now thoroughly hate Date. So this is my new Approach
var dd = new Date(); // or any date and time you care about
var dateArray = dd.toISOString().split('T')[0].split('-').concat( dd.toISOString().split('T')[1].split(':') );
// ["2016", "07", "04", "00", "17", "58.849Z"] at Z
Now for the fun part!
var date = {
day: dateArray[2],
month: dateArray[1],
year: dateArray[0],
hour: dateArray[3],
minutes: dateArray[4],
seconds:dateArray[5].split('.')[0],
milliseconds: dateArray[5].split('.')[1].replace('Z','')
}
now we have our Official Valid international Date Object clearly written out at Zulu meridian. Now to change the date
dd.setDate(dd.getDate()+1); // this gives you one full calendar date forward
tomorrow.setDate(dd.getTime() + 86400000);// this gives your 24 hours into the future. do what you want with it.
But if the elements are objects then as Kshitij Mehta mentioned you need to implement (override) the method "toString" within that object - if it is not already implemented - and let it return something meaning full from within the object, example:
class Person {
private String firstName;
private String lastName;
@Override
public String toString() {
return this.firstName + " " + this.lastName;
}
}
Some elaboration, in the hope of clarifying what has already been said:
As stated above, Webcams are supported natively in the current SDK, but only on recent android versions (4.0 and higher)
Webcam detection is automatic where present. In 4.0.3, the camera defaults to the front-facing camera so a lot of applications (especially pre-2.3 applications, which can only fetch the default camera, i.e. the back-facing one) will still show you the old checkerbox-with-moving-square stand-in instead.
I think some more info is available in the following post: Camera on Android Eclipse emulator:
Or at least, that's the most information I've been able to find--aside from the brief, uninformative statements in the release notes for the SDK tools.
Use BindingFlags.NonPublic
and BindingFlags.Instance
flags
FieldInfo[] fields = myType.GetFields(
BindingFlags.NonPublic |
BindingFlags.Instance);
Probably you instance old fragment it is keeping a reference. See this interesting article Memory leaks in Android — identify, treat and avoid
If you use addToBackStack, this keeps a reference to instance fragment avoiding to Garbage Collector erase the instance. The instance remains in fragments list in fragment manager. You can see the list by
ArrayList<Fragment> fragmentList = fragmentManager.getFragments();
The next code is not the best solution (because don´t remove the old fragment instance in order to avoid memory leaks) but removes the old fragment from fragmentManger fragment list
int index = fragmentManager.getFragments().indexOf(oldFragment);
fragmentManager.getFragments().set(index, null);
You cannot remove the entry in the arrayList because apparenly FragmentManager works with index ArrayList to get fragment.
I usually use this code for working with fragmentManager
public void replaceFragment(Fragment fragment, Bundle bundle) {
if (bundle != null)
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment oldFragment = fragmentManager.findFragmentByTag(fragment.getClass().getName());
//if oldFragment already exits in fragmentManager use it
if (oldFragment != null) {
fragment = oldFragment;
}
fragmentTransaction.replace(R.id.frame_content_main, fragment, fragment.getClass().getName());
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.commit();
}
Your use case would be :
$ArrayCollectionOfActiveUsers = $customer->users->filter(function($user) {
return $user->getActive() === TRUE;
});
if you add ->first() you'll get only the first entry returned, which is not what you want.
@ Sjwdavies You need to put () around the variable you pass to USE. You can also shorten as in_array return's a boolean already:
$member->getComments()->filter( function($entry) use ($idsToFilter) {
return in_array($entry->getId(), $idsToFilter);
});
I am describing a simple method which worked very smoothly in Python (Django Framework).
1. While sending the request, send the request like this
http://server/action?id=a,b
2. Now in my backend, I split the value received with a split function which always creates a list.
id_filter = id.split(',')
Example: So if I send two values in the request,
http://server/action?id=a,b
then the filter on the data is
id_filter = ['a', 'b']
If I send only one value in the request,
http://server/action?id=a
then the filter outcome is
id_filter = ['a']
3. To actually filter the data, I simply use the 'in' function
queryset = queryset.filter(model_id__in=id_filter)
which roughly speaking performs the SQL equivalent of
WHERE model_id IN ('a', 'b')
with the first request and,
WHERE model_id IN ('a')
with the second request.
This would work with more than 2 parameter values in the request as well !
for (int i = 1; i*i <= num; ++i)
{
if (num % i == 0)
cout << i << endl;
if (num/i!=i)
cout << num/i << endl;
}
Potatoswatter's answer is all right, but I prefer to use find
or lower_bound
instead. lower_bound
is especially useful because the iterator returned can subsequently be used for a hinted insertion, should you wish to insert something with the same key.
map<K, V>::iterator iter(my_map.lower_bound(key));
if (iter == my_map.end() || key < iter->first) { // not found
// ...
my_map.insert(iter, make_pair(key, value)); // hinted insertion
} else {
// ... use iter->second here
}
There is no OOTB feature at this moment which allows this. One way to achieve that could be to write a custom InputFormat and/or SerDe that will do this for you. You might this JIRA useful : https://issues.apache.org/jira/browse/HIVE-3751. (not related directly to your problem though).
Following up on the comment ron posted, here is the detailed solution. Let's say you have registered a repeating alarm with a pending intent like this:
Intent intent = new Intent("com.my.package.MY_UNIQUE_ACTION");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 1);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60, pendingIntent);
The way you would check to see if it is active is to:
boolean alarmUp = (PendingIntent.getBroadcast(context, 0,
new Intent("com.my.package.MY_UNIQUE_ACTION"),
PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp)
{
Log.d("myTag", "Alarm is already active");
}
The key here is the FLAG_NO_CREATE
which as described in the javadoc: if the described PendingIntent **does not** already exists, then simply return null
(instead of creating a new one)
Actually emberjs
supports two-way binding, which is one of the most powerful feature for a javascript MVC framework. You can check it out where it mentioning binding
in its user guide.
for emberjs, to create two way binding is by creating a new property with the string Binding at the end, then specifying a path from the global scope:
App.wife = Ember.Object.create({
householdIncome: 80000
});
App.husband = Ember.Object.create({
householdIncomeBinding: 'App.wife.householdIncome'
});
App.husband.get('householdIncome'); // 80000
// Someone gets raise.
App.husband.set('householdIncome', 90000);
App.wife.get('householdIncome'); // 90000
Note that bindings don't update immediately. Ember waits until all of your application code has finished running before synchronizing changes, so you can change a bound property as many times as you'd like without worrying about the overhead of syncing bindings when values are transient.
Hope it helps in extend of original answer selected.
m2eclipse has moved from sonatype to eclipse.
The correct update site is http://download.eclipse.org/technology/m2e/releases/
If this is not working, one possibility is you have an older version of Eclipse (< 3.6). The other - if you see timeout related errors - could be that you are behind a proxy server.
In my Notepad++ 7.2.2
, the Preferences
section it's a bit different.
The option is located at: Settings
/ Preferences
/ Language
/ Replace by space
as in the Screenshot.
For what it's worth, here's the previously provided code encapsulated within a function.
openWindowWithPost("http://www.example.com/index.php", {
p: "view.map",
coords: encodeURIComponent(coords)
});
Function definition:
function openWindowWithPost(url, data) {
var form = document.createElement("form");
form.target = "_blank";
form.method = "POST";
form.action = url;
form.style.display = "none";
for (var key in data) {
var input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = data[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
Below worked for me:
When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {_x000D_
"name":"jonsa",_x000D_
"e-mail":"[email protected]",_x000D_
"phone":1223456789_x000D_
};_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
type: 'POST',_x000D_
url: '/form/',_x000D_
data: Data,_x000D_
success: function(data) { alert('data: ' + data); },_x000D_
contentType: "application/json",_x000D_
dataType: 'json'_x000D_
});
_x000D_
What if you just wrap your code into function?
So this:
cd ~/documents
mkdir test
echo "useless script" > about.txt
Becomes this:
CommentedOutBlock() {
cd ~/documents
mkdir test
echo "useless script" > about.txt
}
You can make this much simpler by using one dictionary and a try/except clause like this:
num2words = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \
6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', \
11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', \
15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', \
19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty', \
50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', \
90: 'Ninety', 0: 'Zero'}
>>> def n2w(n):
try:
print num2words[n]
except KeyError:
try:
print num2words[n-n%10] + num2words[n%10].lower()
except KeyError:
print 'Number out of range'
>>> n2w(0)
Zero
>>> n2w(13)
Thirteen
>>> n2w(91)
Ninetyone
>>> n2w(21)
Twentyone
>>> n2w(33)
Thirtythree
The easiest might be:
Array(1, 2, 3) :+ 4
Actually, Array can be implcitly transformed in a WrappedArray
Yes user-agent is used to detect mobile browsers. There are lots of free scripts available to check this. Here is one such php code which will help you redirect mobile users to different website.
Then just delete it:
x = [0, 1, 2, 3, 4]
del x[0]
print x
# [1, 2, 3, 4]
Modulus - Divides left hand operand by right hand operand and returns remainder.
If it helps:
1:0> 2%6
=> 2
2:0> 8%6
=> 2
3:0> 2%6 == 8%6
=> true
... and so on.
Jackson appears to support some amount of JSON parsing straight from an InputStream
. My understanding is that it runs on Android and is fairly quick. On the other hand, it is an extra JAR to include with your app, increasing download and on-flash size.
Use this gem: https://rubygems.org/gems/active_record_importer
class Moulding < ActiveRecord::Base
acts_as_importable
end
Then you may now use:
Moulding.import!(file: File.open(PATH_TO_FILE))
Just be sure to that your headers match the column names of your table
Echo inside an HTML element with class
and style the element:
echo "<span class='name'>" . $ip['cityName'] . "</span>";
I wrote an unzipper in Javascript. It works.
It relies on Andy G.P. Na's binary file reader and some RFC1951 inflate logic from notmasteryet. I added the ZipFile class.
working example:
http://cheeso.members.winisp.net/Unzip-Example.htm (dead link)
The source:
http://cheeso.members.winisp.net/srcview.aspx?dir=js-unzip (dead link)
NB: the links are dead; I'll find a new host soon.
Included in the source is a ZipFile.htm demonstration page, and 3 distinct scripts, one for the zipfile class, one for the inflate class, and one for a binary file reader class. The demo also depends on jQuery and jQuery UI. If you just download the js-zip.zip file, all of the necessary source is there.
Here's what the application code looks like in Javascript:
// In my demo, this gets attached to a click event.
// it instantiates a ZipFile, and provides a callback that is
// invoked when the zip is read. This can take a few seconds on a
// large zip file, so it's asynchronous.
var readFile = function(){
$("#status").html("<br/>");
var url= $("#urlToLoad").val();
var doneReading = function(zip){
extractEntries(zip);
};
var zipFile = new ZipFile(url, doneReading);
};
// this function extracts the entries from an instantiated zip
function extractEntries(zip){
$('#report').accordion('destroy');
// clear
$("#report").html('');
var extractCb = function(id) {
// this callback is invoked with the entry name, and entry text
// in my demo, the text is just injected into an accordion panel.
return (function(entryName, entryText){
var content = entryText.replace(new RegExp( "\\n", "g" ), "<br/>");
$("#"+id).html(content);
$("#status").append("extract cb, entry(" + entryName + ") id(" + id + ")<br/>");
$('#report').accordion('destroy');
$('#report').accordion({collapsible:true, active:false});
});
}
// for each entry in the zip, extract it.
for (var i=0; i<zip.entries.length; i++) {
var entry = zip.entries[i];
var entryInfo = "<h4><a>" + entry.name + "</a></h4>\n<div>";
// contrive an id for the entry, make it unique
var randomId = "id-"+ Math.floor((Math.random() * 1000000000));
entryInfo += "<span class='inputDiv'><h4>Content:</h4><span id='" + randomId +
"'></span></span></div>\n";
// insert the info for one entry as the last child within the report div
$("#report").append(entryInfo);
// extract asynchronously
entry.extract(extractCb(randomId));
}
}
The demo works in a couple of steps: The readFile
fn is triggered by a click, and instantiates a ZipFile object, which reads the zip file. There's an asynchronous callback for when the read completes (usually happens in less than a second for reasonably sized zips) - in this demo the callback is held in the doneReading local variable, which simply calls extractEntries
, which
just blindly unzips all the content of the provided zip file. In a real app you would probably choose some of the entries to extract (allow the user to select, or choose one or more entries programmatically, etc).
The extractEntries
fn iterates over all entries, and calls extract()
on each one, passing a callback. Decompression of an entry takes time, maybe 1s or more for each entry in the zipfile, which means asynchrony is appropriate. The extract callback simply adds the extracted content to an jQuery accordion on the page. If the content is binary, then it gets formatted as such (not shown).
It works, but I think that the utility is somewhat limited.
For one thing: It's very slow. Takes ~4 seconds to unzip the 140k AppNote.txt file from PKWare. The same uncompress can be done in less than .5s in a .NET program. EDIT: The Javascript ZipFile unpacks considerably faster than this now, in IE9 and in Chrome. It is still slower than a compiled program, but it is plenty fast for normal browser usage.
For another: it does not do streaming. It basically slurps in the entire contents of the zipfile into memory. In a "real" programming environment you could read in only the metadata of a zip file (say, 64 bytes per entry) and then read and decompress the other data as desired. There's no way to do IO like that in javascript, as far as I know, therefore the only option is to read the entire zip into memory and do random access in it. This means it will place unreasonable demands on system memory for large zip files. Not so much a problem for a smaller zip file.
Also: It doesn't handle the "general case" zip file - there are lots of zip options that I didn't bother to implement in the unzipper - like ZIP encryption, WinZip encryption, zip64, UTF-8 encoded filenames, and so on. (EDIT - it handles UTF-8 encoded filenames now). The ZipFile class handles the basics, though. Some of these things would not be hard to implement. I have an AES encryption class in Javascript; that could be integrated to support encryption. Supporting Zip64 would probably useless for most users of Javascript, as it is intended to support >4gb zipfiles - don't need to extract those in a browser.
I also did not test the case for unzipping binary content. Right now it unzips text. If you have a zipped binary file, you'd need to edit the ZipFile class to handle it properly. I didn't figure out how to do that cleanly. It does binary files now, too.
EDIT - I updated the JS unzip library and demo. It now does binary files, in addition to text. I've made it more resilient and more general - you can now specify the encoding to use when reading text files. Also the demo is expanded - it shows unzipping an XLSX file in the browser, among other things.
So, while I think it is of limited utility and interest, it works. I guess it would work in Node.js.
I created an enhanced version, based on Trey Copland's fiddle, that I think is more like what you wanted. Added here for future reference to those who come here later. Fiddle example
<body>
<style>
.modal {
height: 390px;
border: 5px solid green;
}
.heading {
padding: 10px;
}
.content {
height: 300px;
overflow:auto;
border: 5px solid red;
}
.scrollable {
height: 1200px;
border: 5px solid yellow;
}
.footer {
height: 2em;
padding: .5em;
}
</style>
<div class="modal">
<div class="heading">
<h4>Heading</h4>
</div>
<div class="content">
<div class="scrollable" >hello</div>
</div>
<div class="footer">
Footer
</div>
</div>
</body>
You should let the Activity deal with adding and removing Fragments, as CommonsWare says, use a listener. Here is an example:
public class MyActivity extends FragmentActivity implements SuicidalFragmentListener {
// onCreate etc
@Override
public void onFragmentSuicide(String tag) {
// Check tag if you do this with more than one fragmen, then:
getSupportFragmentManager().popBackStack();
}
}
public interface SuicidalFragmentListener {
void onFragmentSuicide(String tag);
}
public class MyFragment extends Fragment {
// onCreateView etc
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
suicideListener = (SuicidalFragmentListener) activity;
} catch (ClassCastException e) {
throw new RuntimeException(getActivity().getClass().getSimpleName() + " must implement the suicide listener to use this fragment", e);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Attach the close listener to whatever action on the fragment you want
addSuicideTouchListener();
}
private void addSuicideTouchListener() {
getView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
suicideListener.onFragmentSuicide(getTag());
}
});
}
}
If you're using vue-router, you can append to the list of routes:
{
path: '/_=_',
redirect: '/', // <-- or other default route
},
For those looking for an SCSS mixin instead, including woff2:
@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
@font-face {
font-family: $family;
@if $svg == '' {
// with OTF without SVG and EOT
src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
} @else {
// traditional src inclusions
src: url('#{$path}#{$type}.eot');
src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
}
font-weight: $weight;
font-style: $style;
}
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);
$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
font-family: Inter;
font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
font-family: AmaticSC;
font-weight: 700; // default font is loaded
}
The $type
parameter is useful for stacking related families with different weights.
The @if
is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.
If you get a can't resolve error, remember to double check your fonts directory ($dir
).
Both commands are correct :
mvn clean install -Pdev1
mvn clean install -P dev1
The problem is most likely not profile activation, but the profile not accomplishing what you expect it to.
It is normal that the command :
mvn help:active-profiles
does not display the profile, because is does not contain -Pdev1
. You could add it to make the profile appear, but it would be pointless because you would be testing maven itself.
What you should do is check the profile behavior by doing the following :
activeByDefault
to true
in the profile configuration,mvn help:active-profiles
(to make sure it is effectively
activated even without -Pdev1
),mvn install
.It should give the same results as before, and therefore confirm that the problem is the profile not doing what you expect.
For completude, you can also easily do it without calling any heavy library function (no snprintf, no strcat, not even memcpy). It can be useful, say if you are programming some microcontroller or OS kernel where libc is not available.
Nothing really fancy you can find similar code around if you google for it. Really it's not much more complicated than calling snprintf and much faster.
#include <stdio.h>
int main(){
unsigned char buf[] = {0, 1, 10, 11};
/* target buffer should be large enough */
char str[12];
unsigned char * pin = buf;
const char * hex = "0123456789ABCDEF";
char * pout = str;
int i = 0;
for(; i < sizeof(buf)-1; ++i){
*pout++ = hex[(*pin>>4)&0xF];
*pout++ = hex[(*pin++)&0xF];
*pout++ = ':';
}
*pout++ = hex[(*pin>>4)&0xF];
*pout++ = hex[(*pin)&0xF];
*pout = 0;
printf("%s\n", str);
}
Here is another slightly shorter version. It merely avoid intermediate index variable i and duplicating laste case code (but the terminating character is written two times).
#include <stdio.h>
int main(){
unsigned char buf[] = {0, 1, 10, 11};
/* target buffer should be large enough */
char str[12];
unsigned char * pin = buf;
const char * hex = "0123456789ABCDEF";
char * pout = str;
for(; pin < buf+sizeof(buf); pout+=3, pin++){
pout[0] = hex[(*pin>>4) & 0xF];
pout[1] = hex[ *pin & 0xF];
pout[2] = ':';
}
pout[-1] = 0;
printf("%s\n", str);
}
Below is yet another version to answer to a comment saying I used a "trick" to know the size of the input buffer. Actually it's not a trick but a necessary input knowledge (you need to know the size of the data that you are converting). I made this clearer by extracting the conversion code to a separate function. I also added boundary check code for target buffer, which is not really necessary if we know what we are doing.
#include <stdio.h>
void tohex(unsigned char * in, size_t insz, char * out, size_t outsz)
{
unsigned char * pin = in;
const char * hex = "0123456789ABCDEF";
char * pout = out;
for(; pin < in+insz; pout +=3, pin++){
pout[0] = hex[(*pin>>4) & 0xF];
pout[1] = hex[ *pin & 0xF];
pout[2] = ':';
if (pout + 3 - out > outsz){
/* Better to truncate output string than overflow buffer */
/* it would be still better to either return a status */
/* or ensure the target buffer is large enough and it never happen */
break;
}
}
pout[-1] = 0;
}
int main(){
enum {insz = 4, outsz = 3*insz};
unsigned char buf[] = {0, 1, 10, 11};
char str[outsz];
tohex(buf, insz, str, outsz);
printf("%s\n", str);
}
This worked for me
On the tab "Workloads" check ".Net Core cross-platform development" and click on "Modify"
Don't forget to check ".NET Core 2.0 development tools" on the left menu.
I installed the Asp Net Core before, however not appeared on my Visual Studio, just after I installed using the installation of Visual Studio appeared for me.
Please store your JSON file with the .js extension and make sure that your JSON should be in same directory.
You should just scope your * selector to the specific areas that need the reset. .legacy * { }
, etc.
Since November 2017, one can use tomcat8-maven-plugin:
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat8-maven-plugin -->
<dependency>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat8-maven-plugin</artifactId>
<version>2.2</version>
</dependency>
Note that this plugin resides in ICM repo (not in Maven Central), hence you should add the repo to your pluginsRepositories in your pom.xml:
<pluginRepositories>
<pluginRepository>
<id>icm</id>
<name>Spring Framework Milestone Repository</name>
<url>http://maven.icm.edu.pl/artifactory/repo</url>
</pluginRepository>
</pluginRepositories>
Have a look at using FileInfo.Name Property
something like
string[] files = Directory.GetFiles(dir);
for (int iFile = 0; iFile < files.Length; iFile++)
string fn = new FileInfo(files[iFile]).Name;
Also have a look at using DirectoryInfo Class and FileInfo Class
I got a easy solution which will select from database table and let you do easily.
SELECT b.FirstName + b.LastName FROM tbl_Users b WHERE b.Id='11'
You can easily add a space there if you try
SELECT b.FirstName +' '+ b.LastName FROM Users b WHERE b.Id='23'
Here you can combine as much as your table have.
$("button").click(function(){_x000D_
alert($("li").length);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>_x000D_
<meta charset="utf-8">_x000D_
<title>Count the number of specific elements</title>_x000D_
</head>_x000D_
<body>_x000D_
<ul>_x000D_
<li>List - 1</li>_x000D_
<li>List - 2</li>_x000D_
<li>List - 3</li>_x000D_
</ul>_x000D_
<button>Display the number of li elements</button>_x000D_
</body>_x000D_
</html>
_x000D_
Best way to do this is to use a function:
<div ng-repeat="product in products | filter: myFilter">
$scope.myFilter = function (item) {
return item === 'red' || item === 'blue';
};
Alternatively, you can use ngHide or ngShow to dynamically show and hide elements based on a certain criteria.
Displaying a video is much the same as displaying an image. The minor differences are to do with onload events and the fact that you need to render the video every frame or you will only see one frame not the animated frames.
The demo below has some minor differences to the example. A mute function (under the video click mute/sound on to toggle sound) and some error checking to catch IE9+ and Edge if they don't have the correct drivers.
Keeping answers current.The previous answers by user372551 is out of date (December 2010) and has a flaw in the rendering technique used. It uses the setTimeout
and a rate of 33.333..ms which setTimeout will round down to 33ms this will cause the frames to be dropped every two seconds and may drop many more if the video frame rate is any higher than 30. Using setTimeout
will also introduce video shearing created because setTimeout can not be synced to the display hardware.
There is currently no reliable method that can determine a videos frame rate unless you know the video frame rate in advance you should display it at the maximum display refresh rate possible on browsers. 60fps
The given top answer was for the time (6 years ago) the best solution as requestAnimationFrame
was not widely supported (if at all) but requestAnimationFrame
is now standard across the Major browsers and should be used instead of setTimeout to reduce or remove dropped frames, and to prevent shearing.
Loads a video and set it to loop. The video will not play until the you click on it. Clicking again will pause. There is a mute/sound on button under the video. The video is muted by default.
Note users of IE9+ and Edge. You may not be able to play the video format WebM as it needs additional drivers to play the videos. They can be found at tools.google.com Download IE9+ WebM support
// This code is from the example document on stackoverflow documentation. See HTML for link to the example._x000D_
// This code is almost identical to the example. Mute has been added and a media source. Also added some error handling in case the media load fails and a link to fix IE9+ and Edge support._x000D_
// Code by Blindman67._x000D_
_x000D_
_x000D_
// Original source has returns 404_x000D_
// var mediaSource = "http://video.webmfiles.org/big-buck-bunny_trailer.webm";_x000D_
// New source from wiki commons. Attribution in the leading credits._x000D_
var mediaSource = "http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv"_x000D_
_x000D_
var muted = true;_x000D_
var canvas = document.getElementById("myCanvas"); // get the canvas from the page_x000D_
var ctx = canvas.getContext("2d");_x000D_
var videoContainer; // object to hold video and associated info_x000D_
var video = document.createElement("video"); // create a video element_x000D_
video.src = mediaSource;_x000D_
// the video will now begin to load._x000D_
// As some additional info is needed we will place the video in a_x000D_
// containing object for convenience_x000D_
video.autoPlay = false; // ensure that the video does not auto play_x000D_
video.loop = true; // set the video to loop._x000D_
video.muted = muted;_x000D_
videoContainer = { // we will add properties as needed_x000D_
video : video,_x000D_
ready : false, _x000D_
};_x000D_
// To handle errors. This is not part of the example at the moment. Just fixing for Edge that did not like the ogv format video_x000D_
video.onerror = function(e){_x000D_
document.body.removeChild(canvas);_x000D_
document.body.innerHTML += "<h2>There is a problem loading the video</h2><br>";_x000D_
document.body.innerHTML += "Users of IE9+ , the browser does not support WebM videos used by this demo";_x000D_
document.body.innerHTML += "<br><a href='https://tools.google.com/dlpage/webmmf/'> Download IE9+ WebM support</a> from tools.google.com<br> this includes Edge and Windows 10";_x000D_
_x000D_
}_x000D_
video.oncanplay = readyToPlayVideo; // set the event to the play function that _x000D_
// can be found below_x000D_
function readyToPlayVideo(event){ // this is a referance to the video_x000D_
// the video may not match the canvas size so find a scale to fit_x000D_
videoContainer.scale = Math.min(_x000D_
canvas.width / this.videoWidth, _x000D_
canvas.height / this.videoHeight); _x000D_
videoContainer.ready = true;_x000D_
// the video can be played so hand it off to the display function_x000D_
requestAnimationFrame(updateCanvas);_x000D_
// add instruction_x000D_
document.getElementById("playPause").textContent = "Click video to play/pause.";_x000D_
document.querySelector(".mute").textContent = "Mute";_x000D_
}_x000D_
_x000D_
function updateCanvas(){_x000D_
ctx.clearRect(0,0,canvas.width,canvas.height); _x000D_
// only draw if loaded and ready_x000D_
if(videoContainer !== undefined && videoContainer.ready){ _x000D_
// find the top left of the video on the canvas_x000D_
video.muted = muted;_x000D_
var scale = videoContainer.scale;_x000D_
var vidH = videoContainer.video.videoHeight;_x000D_
var vidW = videoContainer.video.videoWidth;_x000D_
var top = canvas.height / 2 - (vidH /2 ) * scale;_x000D_
var left = canvas.width / 2 - (vidW /2 ) * scale;_x000D_
// now just draw the video the correct size_x000D_
ctx.drawImage(videoContainer.video, left, top, vidW * scale, vidH * scale);_x000D_
if(videoContainer.video.paused){ // if not playing show the paused screen _x000D_
drawPayIcon();_x000D_
}_x000D_
}_x000D_
// all done for display _x000D_
// request the next frame in 1/60th of a second_x000D_
requestAnimationFrame(updateCanvas);_x000D_
}_x000D_
_x000D_
function drawPayIcon(){_x000D_
ctx.fillStyle = "black"; // darken display_x000D_
ctx.globalAlpha = 0.5;_x000D_
ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
ctx.fillStyle = "#DDD"; // colour of play icon_x000D_
ctx.globalAlpha = 0.75; // partly transparent_x000D_
ctx.beginPath(); // create the path for the icon_x000D_
var size = (canvas.height / 2) * 0.5; // the size of the icon_x000D_
ctx.moveTo(canvas.width/2 + size/2, canvas.height / 2); // start at the pointy end_x000D_
ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 + size);_x000D_
ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 - size);_x000D_
ctx.closePath();_x000D_
ctx.fill();_x000D_
ctx.globalAlpha = 1; // restore alpha_x000D_
} _x000D_
_x000D_
function playPauseClick(){_x000D_
if(videoContainer !== undefined && videoContainer.ready){_x000D_
if(videoContainer.video.paused){ _x000D_
videoContainer.video.play();_x000D_
}else{_x000D_
videoContainer.video.pause();_x000D_
}_x000D_
}_x000D_
}_x000D_
function videoMute(){_x000D_
muted = !muted;_x000D_
if(muted){_x000D_
document.querySelector(".mute").textContent = "Mute";_x000D_
}else{_x000D_
document.querySelector(".mute").textContent= "Sound on";_x000D_
}_x000D_
_x000D_
_x000D_
}_x000D_
// register the event_x000D_
canvas.addEventListener("click",playPauseClick);_x000D_
document.querySelector(".mute").addEventListener("click",videoMute)
_x000D_
body {_x000D_
font :14px arial;_x000D_
text-align : center;_x000D_
background : #36A;_x000D_
}_x000D_
h2 {_x000D_
color : white;_x000D_
}_x000D_
canvas {_x000D_
border : 10px white solid;_x000D_
cursor : pointer;_x000D_
}_x000D_
a {_x000D_
color : #F93;_x000D_
}_x000D_
.mute {_x000D_
cursor : pointer;_x000D_
display: initial; _x000D_
}
_x000D_
<h2>Basic Video & canvas example</h2>_x000D_
<p>Code example from Stackoverflow Documentation HTML5-Canvas<br>_x000D_
<a href="https://stackoverflow.com/documentation/html5-canvas/3689/media-types-and-the-canvas/14974/basic-loading-and-playing-a-video-on-the-canvas#t=201607271638099201116">Basic loading and playing a video on the canvas</a></p>_x000D_
<canvas id="myCanvas" width = "532" height ="300" ></canvas><br>_x000D_
<h3><div id = "playPause">Loading content.</div></h3>_x000D_
<div class="mute"></div><br>_x000D_
<div style="font-size:small">Attribution in the leading credits.</div><br>
_x000D_
Using the canvas to render video gives you additional options in regard to displaying and mixing in fx. The following image shows some of the FX you can get using the canvas. Using the 2D API gives a huge range of creative possibilities.
Image relating to answer Fade canvas video from greyscale to color
See video title in above demo for attribution of content in above inmage.
DOM event delegation is a mechanism of responding to ui-events via a single common parent rather than each child, through the magic of event "bubbling" (aka event propagation).
When an event is triggered on an element, the following occurs:
The event is dispatched to its target
EventTarget
and any event listeners found there are triggered. Bubbling events will then trigger any additional event listeners found by following theEventTarget
's parent chain upward, checking for any event listeners registered on each successive EventTarget. This upward propagation will continue up to and including theDocument
.
Event bubbling provides the foundation for event delegation in browsers. Now you can bind an event handler to a single parent element, and that handler will get executed whenever the event occurs on any of its child nodes (and any of their children in turn). This is event delegation. Here's an example of it in practice:
<ul onclick="alert(event.type + '!')">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
With that example if you were to click on any of the child <li>
nodes, you would see an alert of "click!"
, even though there is no click handler bound to the <li>
you clicked on. If we bound onclick="..."
to each <li>
you would get the same effect.
So what's the benefit?
Imagine you now have a need to dynamically add new <li>
items to the above list via DOM manipulation:
var newLi = document.createElement('li');
newLi.innerHTML = 'Four';
myUL.appendChild(newLi);
Without using event delegation you would have to "rebind" the "onclick"
event handler to the new <li>
element, in order for it to act the same way as its siblings. With event delegation you don't need to do anything. Just add the new <li>
to the list and you're done.
This is absolutely fantastic for web apps with event handlers bound to many elements, where new elements are dynamically created and/or removed in the DOM. With event delegation the number of event bindings can be drastically decreased by moving them to a common parent element, and code that dynamically creates new elements on the fly can be decoupled from the logic of binding their event handlers.
Another benefit to event delegation is that the total memory footprint used by event listeners goes down (since the number of event bindings go down). It may not make much of a difference to small pages that unload often (i.e. user's navigate to different pages often). But for long-lived applications it can be significant. There are some really difficult-to-track-down situations when elements removed from the DOM still claim memory (i.e. they leak), and often this leaked memory is tied to an event binding. With event delegation you're free to destroy child elements without risk of forgetting to "unbind" their event listeners (since the listener is on the ancestor). These types of memory leaks can then be contained (if not eliminated, which is freaking hard to do sometimes. IE I'm looking at you).
Here are some better concrete code examples of event delegation:
focus
and blur
events (which do not bubble)According to the bash man page, $RANDOM
is distributed between 0 and 32767; that is, it is an unsigned 15-bit value. Assuming $RANDOM
is uniformly distributed, you can create a uniformly-distributed unsigned 30-bit integer as follows:
$(((RANDOM<<15)|RANDOM))
Since your range is not a power of 2, a simple modulo operation will only almost give you a uniform distribution, but with a 30-bit input range and a less-than-16-bit output range, as you have in your case, this should really be close enough:
PORT=$(( ((RANDOM<<15)|RANDOM) % 63001 + 2000 ))
Here is the same problem.
You need to set table-layout:fixed
and a suitable width on the table element, as well as overflow:hidden
and white-space: nowrap
on the table cells.
The width of the table has to be the same (or smaller) than the fixed width cell(s).
With one fixed width column:
* {
box-sizing: border-box;
}
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
max-width: 100px;
}
td {
background: #F00;
padding: 20px;
overflow: hidden;
white-space: nowrap;
width: 100px;
border: solid 1px #000;
}
_x000D_
<table>
<tbody>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
</tbody>
</table>
_x000D_
With multiple fixed width columns:
* {
box-sizing: border-box;
}
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
max-width: 200px;
}
td {
background: #F00;
padding: 20px;
overflow: hidden;
white-space: nowrap;
width: 100px;
border: solid 1px #000;
}
_x000D_
<table>
<tbody>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
</tbody>
</table>
_x000D_
A width for the table must be set, but any extra width is simply taken by the fluid cell(s).
With multiple columns, fixed width and fluid width:
* {
box-sizing: border-box;
}
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
}
td {
background: #F00;
padding: 20px;
border: solid 1px #000;
}
tr td:first-child {
overflow: hidden;
white-space: nowrap;
width: 100px;
}
_x000D_
<table>
<tbody>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
</tbody>
</table>
_x000D_
It looks like you're writing PHP, in which case you want:
<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>
Notice that the ('us'=>'United', 'ca'=>'canada')
needs to be a parameter to the array function in PHP.
Most programming languages that support associative arrays or dictionaries use arr['key']
to retrieve the item specified by 'key'
For instance:
ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
=> {"us"=>"USA", "ca"=>"Canada"}
ruby-1.9.1-p378 > h['ca']
=> "Canada"
>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'
#
class P
{
static void Main()
{
var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
System.Console.WriteLine(d["ca"]);
}
}
t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables
If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:
# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));
# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);
In this case curl will send your defined cookie along with the cookies from the file.
If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).
The utma utmc, utmz
are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.
Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt
) instead of relative one.
Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.
curl_setopt($ch, CURLOPT_VERBOSE, true);
I think you could solve this with .strip()
in gazpacho:
Input:
html = """\
<p>
<strong class="offender">YOB:</strong> 1987<br />
<strong class="offender">RACE:</strong> WHITE<br />
<strong class="offender">GENDER:</strong> FEMALE<br />
<strong class="offender">HEIGHT:</strong> 5'05''<br />
<strong class="offender">WEIGHT:</strong> 118<br />
<strong class="offender">EYE COLOR:</strong> GREEN<br />
<strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""
Code:
soup = Soup(html)
text = soup.find("p").strip(whitespace=False) # to keep \n characters intact
lines = [
line.strip()
for line in text.split("\n")
if line != ""
]
data = dict([line.split(": ") for line in lines])
Output:
print(data)
# {'YOB': '1987',
# 'RACE': 'WHITE',
# 'GENDER': 'FEMALE',
# 'HEIGHT': "5'05''",
# 'WEIGHT': '118',
# 'EYE COLOR': 'GREEN',
# 'HAIR COLOR': 'BROWN'}
The answer I was searching for was answered here: How to use python argparse with args other than sys.argv?
If main.py
and parse_args()
is written in this way, then the parsing can be done nicely
# main.py
import argparse
def parse_args():
parser = argparse.ArgumentParser(description="")
parser.add_argument('--input', default='my_input.txt')
return parser
def main(args):
print(args.input)
if __name__ == "__main__":
parser = parse_args()
args = parser.parse_args()
main(args)
Then you can call main()
and parse arguments with parser.parse_args(['--input', 'foobar.txt'])
to it in another python script:
# temp.py
from main import main, parse_args
parser = parse_args()
args = parser.parse_args([]) # note the square bracket
# to overwrite default, use parser.parse_args(['--input', 'foobar.txt'])
print(args) # Namespace(input='my_input.txt')
main(args)
Assuming we are talking about web applications and building APIs:
One approach is to categorize files by feature, much like what a micro service architecture would look like. The biggest win in my opinion is that it is super easy to see which files relate to a feature of the application.
The best way to illustrate is through an example:
We are developing a library application. In the first version of the application, a user can:
In a second version, users can also:
In a third version, users can also:
First we have the following structure:
books
+- controllers
¦ +- booksController.js
¦ +- authorsController.js
¦
+- entities
+- book.js
+- author.js
We then add on the user and loan features:
user
+- controllers
¦ +- userController.js
+- entities
¦ +- user.js
+- middleware
+- authentication.js
loan
+- controllers
¦ +- loanController.js
+- entities
+- loan.js
And then the favorites functionality:
favorites
+- controllers
¦ +- favoritesController.js
+- entities
+- favorite.js
For any new developer that gets handed the task to add on that the books search should also return information if any book have been marked as favorite, it's really easy to see where in the code he/she should look.
Then when the product owner sweeps in and exclaims that the favorites feature should be removed completely, it's easy to remove it.
Try:
Use NOPASSWD
line for all commands, I mean:
jenkins ALL=(ALL) NOPASSWD: ALL
Put the line after all other lines in the sudoers
file.
That worked for me (Ubuntu 14.04).
That is not an nginx
configuration file. It is part of an nginx
configuration file.
The nginx
configuration file (usually called nginx.conf
) will look like:
events {
...
}
http {
...
server {
...
}
}
The server
block is enclosed within an http
block.
Often the configuration is distributed across multiple files, by using the include
directives to pull in additional fragments (for example from the sites-enabled
directory).
Use sudo nginx -t
to test the complete configuration file, which starts at nginx.conf
and pulls in additional fragments using the include
directive. See this document for more.
Ideally a multidimensional array is usually an array of arrays so i figured declare an empty array, then create key and value pairs from the db result in a separate array, finally push each array created on iteration into the outer array. you can return the outer array in case this is a separate function call. Hope that helps
$response = array();
foreach ($res as $result) {
$elements = array("firstname" => $result[0], "subject_name" => $result[1]);
array_push($response, $elements);
}
Actually there is a more simple solution (only on Mac version). Just four steps:
Here is an example how to run an Unix bash or Windows bat/cmd script from Java. Arguments can be passed on the script and output received from the script. The method accepts arbitrary number of arguments.
public static void runScript(String path, String... args) {
try {
String[] cmd = new String[args.length + 1];
cmd[0] = path;
int count = 0;
for (String s : args) {
cmd[++count] = args[count - 1];
}
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
try {
process.waitFor();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
while (bufferedReader.ready()) {
System.out.println("Received from script: " + bufferedReader.readLine());
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.exit(1);
}
}
When running on Unix/Linux, the path must be Unix-like (with '/' as separator), when running on Windows - use '\'. Hier is an example of a bash script (test.sh) that receives arbitrary number of arguments and doubles every argument:
#!/bin/bash
counter=0
while [ $# -gt 0 ]
do
echo argument $((counter +=1)): $1
echo doubling argument $((counter)): $(($1+$1))
shift
done
When calling
runScript("path_to_script/test.sh", "1", "2")
on Unix/Linux, the output is:
Received from script: argument 1: 1
Received from script: doubling argument 1: 2
Received from script: argument 2: 2
Received from script: doubling argument 2: 4
Hier is a simple cmd Windows script test.cmd that counts number of input arguments:
@echo off
set a=0
for %%x in (%*) do Set /A a+=1
echo %a% arguments received
When calling the script on Windows
runScript("path_to_script\\test.cmd", "1", "2", "3")
The output is
Received from script: 3 arguments received
Getting a stack trace of an unprepared python program, running in a stock python without debugging symbols can be done with pyrasite. Worked like a charm for me in on Ubuntu Trusty:
$ sudo pip install pyrasite
$ echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
$ sudo pyrasite 16262 dump_stacks.py # dumps stacks to stdout/stderr of the python program
(Hat tip to @Albert, whose answer contained a pointer to this, among other tools.)
A lower-specificity approach that works in most modern browsers (IE11+, and excluding some mobile Opera & IE browsers -- http://caniuse.com/#feat=pointer-events):
.btn {
/* base styles */
}
.btn[disabled]
opacity: 0.4;
cursor: default;
pointer-events: none;
}
.btn:hover {
color: red;
}
The pointer-events: none
rule will disable hover; you won't need to raise specificity with a .btn[disabled]:hover
selector to nullify the hover style.
(FYI, this is the simple HTML pointer-events, not the contentious abstracting-input-devices pointer-events)
For Delete query - Use @Modifying
and @Transactional
before the @Query
like:-
@Repository
public interface CopyRepository extends JpaRepository<Copy, Integer> {
@Modifying
@Transactional
@Query(value = "DELETE FROM tbl_copy where trade_id = ?1 ; ", nativeQuery = true)
void deleteCopyByTradeId(Integer id);
}
It won't give the java.sql.SQLException: Can not issue data manipulation statements with executeQuery()
error.
Edit:
Since this answer is getting many upvotes, I shall refer you to the documentation as well for more understanding.
By default, CRUD methods on repository instances are transactional. For read operations,
the transaction configuration readOnly flag is set to true.
All others are configured with a plain @Transactional so that default transaction
configuration applies.
Indicates a query method should be considered as modifying query as that changes the way
it needs to be executed. This annotation is only considered if used on query methods defined
through a Query annotation). It's not applied on custom implementation methods or queries
derived from the method name as they already have control over the underlying data access
APIs or specify if they are modifying by their name.
Queries that require a @Modifying annotation include INSERT, UPDATE, DELETE, and DDL
statements.
You can get every file, then filter the array:
public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dirInfo, params string[] extensions)
{
var allowedExtensions = new HashSet<string>(extensions, StringComparer.OrdinalIgnoreCase);
return dirInfo.EnumerateFiles()
.Where(f => allowedExtensions.Contains(f.Extension));
}
This will be (marginally) faster than every other answer here.
In .Net 3.5, replace EnumerateFiles
with GetFiles
(which is slower).
And use it like this:
var files = new DirectoryInfo(...).GetFilesByExtensions(".jpg", ".mov", ".gif", ".mp4");
It is because Ajax is asynchronous, the success
or the error
function will be called later, when the server answer the client. So, just move parts depending on the result into your success function like that :
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
successmessage = 'Data was succesfully captured';
$("label#successmessage").text(successmessage);
},
error: function(data) {
successmessage = 'Error';
$("label#successmessage").text(successmessage);
},
});
$(":input").val('');
return false;
this is a late answer, but you could also use the File.Copy method of the System.IO namespace top send a file to the printer:
System.IO.File.Copy(filename, printerName);
This works fine
Easiest:
<a href="page2.php">Link</a>
And if you need to pass a value:
<a href="page2.php?val=1">Link that pass the value 1</a>
To retrive the value put in page2.php this code:
<?php
$val = $_GET["val"];
?>
Now the variable $val
has the value 1
.
PHP will work only on the .php
file extension.
If you are on Apache you can also set, in your httpd.conf
file, the extensions for PHP. You'll have to find the line:
AddType application/x-httpd-php .php .html
^^^^^
and add how many extensions, that should be read with the PHP interpreter, as you want.
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
Regex for minimum 8 char, one alpha, one numeric and one special char:
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$/
Actually, it is very possible for managed code to do 3d games, the problem is the back engines. With .Net, for a brief period, there was a Managed DirectX wrapper to DirectX 9 by Microsoft. This was before the abstraction that is now XNA.
Being given total access to DirectX api's, .Net games work a treat. The best example I know of is www.entombed.co.uk, which is written in VB.Net.
Unfortunately, on the Java side, it is seriously lacking - mainly for the reason that DirectX isn't available for Java, and games programmers know and understand the DirectX api - why learn yet another api when you will be returning to DirectX?
For guys like me, who aren't minimalistic, there is a PECL extension called "intl". I use it for idn conversion since it works way better than the "idn" extension and some other n1 classes like "IntlDateFormatter".
Well, what I want to say is, the "intl" extension has a class called "IntlCalendar" which can handle many international countries (e.g. in Saudi Arabia, sunday is not a weekend day). The IntlCalendar has a method IntlCalendar::isWeekend for that. Maybe you guys give it a shot, I like that "it works for almost every country" fact on these intl-classes.
EDIT: Not quite sure but since PHP 5.5.0, the intl extension is bundled with PHP (--enable-intl).
var res = exitDictionary
.Select(p => p.Value).Cast<Dictionary<string, object>>()
.SelectMany(d => d)
.Where(p => p.Key == "fieldname1")
.Select(p => p.Value).Cast<List<Dictionary<string,string>>>()
.SelectMany(l => l)
.SelectMany(d=> d)
.Where(p => p.Key == "valueTitle")
.Select(p => p.Value)
.ToList();
This also works, and easy to understand.
Same way you'd hide anything: visibility: hidden;
//Response being your httpwebresponse
Dim str_StatusCode as String = CInt(Response.StatusCode)
Console.Writeline(str_StatusCode)
You have a couple of options...
1) You need to call the destroy()
method not remove()
so...
$('#date').datepicker('destroy');
Then call your method to recreate the datepicker
object.
2) You can update the property of the existing object
via
$('#date').datepicker('option', 'minDate', new Date(startDate));
$('#date').datepicker('option', 'maxDate', new Date(endDate));
or...
$('#date').datepicker('option', { minDate: new Date(startDate),
maxDate: new Date(endDate) });
I think it's worth adding information about NamedTuples using type hinting:
# dependencies
from typing import NamedTuple, Optional
# definition
class MyNamedTuple(NamedTuple):
an_attribute: str
my_attribute: Optional[str] = None
next_attribute: int = 1
# instantiation
my_named_tuple = MyNamedTuple("abc", "def")
# or more explicitly:
other_tuple = MyNamedTuple(an_attribute="abc", my_attribute="def")
# access
assert "abc" == my_named_tuple.an_attribute
assert 1 == other_tuple.next_attribute
As I noticed, log4net locks their output files the whole time application is running, so you can't delete them. Otherwise they are similar.
So I prefer NLog.
Use git reset:
git reset --hard "Version 1.0 Revision 1.5"
(assuming that the specified string is the tag).
(Updated for completeness)
You can access session variables from any page or control using Session["loginId"]
and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].
But please read on for my original answer...
I always use a wrapper class around the ASP.NET session to simplify access to session variables:
public class MySession
{
// private constructor
private MySession()
{
Property1 = "default value";
}
// Gets the current session.
public static MySession Current
{
get
{
MySession session =
(MySession)HttpContext.Current.Session["__MySession__"];
if (session == null)
{
session = new MySession();
HttpContext.Current.Session["__MySession__"] = session;
}
return session;
}
}
// **** add your session properties here, e.g like this:
public string Property1 { get; set; }
public DateTime MyDate { get; set; }
public int LoginId { get; set; }
}
This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:
int loginId = MySession.Current.LoginId;
string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;
DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;
This approach has several advantages:
Since C++11 it can be done like this:
std::vector<std::string> splitString(const std::string& str,
const std::regex& regex)
{
return {std::sregex_token_iterator{str.begin(), str.end(), regex, -1},
std::sregex_token_iterator() };
}
// usually we have a predefined set of regular expressions: then
// let's build those only once and re-use them multiple times
static const std::regex regex1(R"some-reg-exp1", std::regex::optimize);
static const std::regex regex2(R"some-reg-exp2", std::regex::optimize);
static const std::regex regex3(R"some-reg-exp3", std::regex::optimize);
string str = "some string to split";
std::vector<std::string> tokens( splitString(str, regex1) );
Notes:
This is because the LEFT OUTER Join is doing more work than an INNER Join BEFORE sending the results back.
The Inner Join looks for all records where the ON statement is true (So when it creates a new table, it only puts in records that match the m.SubID = a.SubID). Then it compares those results to your WHERE statement (Your last modified time).
The Left Outer Join...Takes all of the records in your first table. If the ON statement is not true (m.SubID does not equal a.SubID), it simply NULLS the values in the second table's column for that recordset.
The reason you get the same number of results at the end is probably coincidence due to the WHERE clause that happens AFTER all of the copying of records.
The operating system is also a program, so we can also create our own program by creating from scratch or changing (limiting or adding) features of one of the small operating systems, and then run it during the boot process (using an ISO image).
For example, this page can be used as a starting point:
How to write a simple operating system
Here, the entire Operating System fit entirely in a 512-byte boot sector (MBR)!
Such or similar simple OS can be used to create a simple framework that will allow us:
make the bootloader load subsequent sectors on the disk into RAM, and jump to that point to continue execution. Or you could read up on FAT12, the filesystem used on floppy drives, and implement that.
There are many possibilities, however. For for example to see a bigger x86 assembly language OS we can explore the MykeOS, x86 operating system which is a learning tool to show the simple 16-bit, real-mode OSes work, with well-commented code and extensive documentation.
Other common type of programs that run without the operating system are also Boot Loaders. We can create a program inspired by such a concept for example using this site:
How to develop your own Boot Loader
The above article presents also the basic architecture of such a programs:
- Correct loading to the memory by 0000:7C00 address.
- Calling the BootMain function that is developed in the high-level language.
- Show “”Hello, world…”, from low-level” message on the display.
As we can see, this architecture is very flexible and allows us to implement any program, not necessarily a boot loader.
In particular, it shows how to use the "mixed code" technique thanks to which it is possible to combine high-level constructions (from C or C++) with low-level commands (from Assembler). This is a very useful method, but we have to remember that:
to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.
The article shows also how to see the created program in action and how to perform its testing and debug.
The above examples used the fact of loading the sector MBR on the data medium. However, we can go deeper into the depths by plaing for example with the UEFI applications:
Beyond loading an OS, UEFI can run UEFI applications, which reside as files on the EFI System Partition. They can be executed from the UEFI command shell, by the firmware's boot manager, or by other UEFI applications. UEFI applications can be developed and installed independently of the system manufacturer.
A type of UEFI application is an OS loader such as GRUB, rEFInd, Gummiboot, and Windows Boot Manager; which loads an OS file into memory and executes it. Also, an OS loader can provide a user interface to allow the selection of another UEFI application to run. Utilities like the UEFI shell are also UEFI applications.
If we would like to start creating such programs, we can, for example, start with these websites:
Programming for EFI: Creating a "Hello, World" Program / UEFI Programming - First Steps
It is well known that there is a whole group of malicious software (which are programs) that are running before the operating system starts.
A huge group of them operate on the MBR sector or UEFI applications, just like the all above solutions, but there are also those that use another entry point such as the Volume Boot Record (VBR) or the BIOS:
There are at least four known BIOS attack viruses, two of which were for demonstration purposes.
or perhaps another one too.
Bootkits have evolved from Proof-of-Concept development to mass distribution and have now effectively become open-source software.
I also think that in this context it is also worth mentioning that there are various forms of booting the operating system (or the executable program intended for this). There are many, but I would like to pay attention to loading the code from the network using Network Boot option (PXE), which allows us to run the program on the computer regardless of its operating system and even regardless of any storage medium that is directly connected to the computer:
There must be something wrong with the way you access the array's items. Here's how it's done:
for elem in "${files[@]}"
...
From the bash manpage:
Any element of an array may be referenced using ${name[subscript]}. ... If subscript is @ or *, the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word.
Of course, you should also use double quotes when accessing a single member
cp "${files[0]}" /tmp
@amitchhajer 's post works for GNU tar. If someone finds this post and needs it to work on a NON GNU
system, they can do this:
tar cvf - folderToCompress | gzip > compressFileName
To expand the archive:
zcat compressFileName | tar xvf -
The issue is that the value for backgroundImage
needs to be a string like this:
<div class="circular" v-bind:style="{ backgroundImage: 'url(' + image + ')' }"></div>
Here's a simplified fiddle that's working: https://jsfiddle.net/89af0se9/1/
Re: the comment below about kebab-case, this is how you can do that:
<div class="circular" v-bind:style="{ 'background-image': 'url(' + image + ')' }"></div>
In other words, the value for v-bind:style
is just a plain Javascript object and follows the same rules.
UPDATE: One other note about why you may have trouble getting this to work.
You should make sure your image
value is quoted so that the end resulting string is:
url('some/url/path/to/image.jpeg')
Otherwise, if your image URL has special characters in it (such as whitespace or parentheses) the browser may not apply it properly. In Javascript, the assignment would look like:
this.image = "'some/url/path/to/image.jpeg'"
or
this.image = "'" + myUrl + "'"
Technically, this could be done in the template, but the escaping required to keep it valid HTML isn't worth it.
More info here: Is quoting the value of url() really necessary?
And if you need to calculate the MD5 to see whether it matches the MD5 of an Azure blob, then this SO question and answer might be helpful: MD5 hash of blob uploaded on Azure doesnt match with same file on local machine
Shift+F5 quickly clears the cache.
I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):
SELECT ... FROM ....WHERE
CONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-
','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >= DATEADD(year,-1,GETDATE())
Add this configurations in pom.xml
<project ...>
...
<build>
...
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<fork>true</fork>
<executable>C:\Program Files\Java\jdk1.7.0_79\bin\javac</executable>
</configuration>
</plugin>
</plugins>
</build>
...
</project>
private int pYear;
private int pMonth;
private int pDay;
static final int DATE_DIALOG_ID = 0;
/**inside oncreate */
final Calendar c = Calendar.getInstance();
pYear= c.get(Calendar.YEAR);
pMonth = c.get(Calendar.MONTH);
pDay = c.get(Calendar.DAY_OF_MONTH);
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
pYear, pMonth-1, pDay);
}
return null;
}
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(pYear, pMonth-1, pDay);
break;
}
}
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// write your code here to get the selected Date
}
};
try this it should work. Thanks
Seems that you need classmethod:
class World(object):
allAirports = []
@classmethod
def initialize(cls):
if not cls.allAirports:
f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
file_reader = csv.reader(f)
for col in file_reader:
cls.allAirports.append(Airport(col[0],col[2],col[3]))
return cls.allAirports
The _ is the same thing as x. However it's a python idiom that's used to indicate an identifier that you don't intend to use. In python these identifiers don't takes memor or allocate space like variables do in other languages. It's easy to forget that. They're just names that point to objects, in this case an integer on each iteration.
One reason for this issue could be wrong/empty /etc/resolv.conf
file.
The way I resolved this issue in my centos 7 minimal is as follows:
my /etc/resolv.conf
was empty and I added the following lines:
nameserver 192.168.1.1
nameserver 0.0.0.0
where 192.168.1.1
is my gateway, in your case it can be different.
You need to use the iconv package, specifically its iconv function.
I had the same error and could not figure it out with the other answers. I found that we can "Consolidate" NuGet packages.
if you want to set value than you can do the same in some function on click or on some event fire.
also you can get value using ViewChild
using local variable like this
<input type='text' id='loginInput' #abc/>
and get value like this
this.abc.nativeElement.value
okay got it , you have to use ngAfterViewInit
method of angualr2 for the same like this
ngAfterViewInit(){
document.getElementById('loginInput').value = '123344565';
}
ngAfterViewInit
will not throw any error because it will render after template loading
The alternative for explode in php is split.
The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.
>>> "Rajasekar SP".split()
['Rajasekar', 'SP']
>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']
send_emai()
didn't work for me so I used EmailMessage
here in django docs.
I have included two versions of the anser:
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
# import file with html content
html_version = 'path/to/html_version.html'
html_message = render_to_string(html_version, { 'context': context, })
message = EmailMessage(subject, html_message, from_email, [to_email])
message.content_subtype = 'html' # this is required because there is no plain text email version
message.send()
If you want to include a plain text version of your email, modify the above like this:
from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives # <= EmailMultiAlternatives instead of EmailMessage
plain_version = 'path/to/plain_version.html' # import plain version. No html content
html_version = 'path/to/html_version.html' # import html version. Has html content
plain_message = render_to_string(plain_version, { 'context': context, })
html_message = render_to_string(html_version, { 'context': context, })
message = EmailMultiAlternatives(subject, plain_message, from_email, [to_email])
message.attach_alternative(html_message, "text/html") # attach html version
message.send()
My plain and html versions look like this: plain_version.html:
Plain text {{ context }}
html_version.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
...
</head>
<body>
<table align="center" border="0" cellpadding="0" cellspacing="0" width="320" style="border: none; border-collapse: collapse; font-family: Arial, sans-serif; font-size: 14px; line-height: 1.5;">
...
{{ context }}
...
</table>
</body>
</html>
to pass the event
object:
<p id="p" onclick="doSomething(event)">
to get the clicked child element
(should be used with event
parameter:
function doSomething(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
to pass the element
itself (DOMElement):
<p id="p" onclick="doThing(this)">
see live example on jsFiddle.
You can specify the name of the event
as above, but alternatively your handler can access the event
parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.
You can try it this way!!
var str ="Hello World";
var position = 6;//its 1 based
var newStr = str.substring(0,position - 1) + str.substring(postion, str.length);
alert(newStr);
Here is the live example: http://jsbin.com/ogagaq
Step 1: Add the submodule
git submodule add git://some_repository.git some_repository
Step 2: Fix the submodule to a particular commit
By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.
git checkout -b some_branch origin/some_branch
Now the submodule is fixed on the development branch instead of HEAD of master.
From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .
As an addition to npm version
you can use the --no-git-tag-version
flag if you want a version bump but no tag or a new commit:
npm --no-git-tag-version version patch
<div style="width: 100%; overflow: scroll;"><table class="table table-striped table-bordered" style="font-size:12px">
confirmed roadkill, create a .htaccess file in the web root with a single line which allows you to add php code to a .html file.
AddType application/x-httpd-php .html
The remote
section also specifies fetch rules. You could add something like this into it to fetch all branches from the remote:
fetch = +refs/heads/*:refs/remotes/origin/*
(Or replace origin
with bitbucket
.)
Please read about it here: 10.5 Git Internals - The Refspec
An updated solution using numpy v1.13+ requires specifying the axis in np.unique if using multiple columns, otherwise the array is implicitly flattened.
import numpy as np
np.unique(df[['col1', 'col2']], axis=0)
This change was introduced Nov 2016: https://github.com/numpy/numpy/commit/1f764dbff7c496d6636dc0430f083ada9ff4e4be
You are trying to compare strings inside an arithmetic command (((...))
). Use [[
instead.
if [[ $username == "$username1" && $password == "$password1" ]] ||
[[ $username == "$username2" && $password == "$password2" ]]; then
Note that I've reduced this to two separate tests joined by ||
, with the &&
moved inside the tests. This is because the shell operators &&
and ||
have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d
is equivalent to the intended ( a && b ) || ( c && d )
.
Actually I got this to work. Consider the following snippet:
Method m;
Type[] genericParameterTypes = m.getGenericParameterTypes();
for (int i = 0; i < genericParameterTypes.length; i++) {
if( genericParameterTypes[i] instanceof ParameterizedType ) {
Type[] parameters = ((ParameterizedType)genericParameterTypes[i]).getActualTypeArguments();
//parameters[0] contains java.lang.String for method like "method(List<String> value)"
}
}
I'm using jdk 1.6