As suggested in other answers it's probably easiest to "POST" the form data to the controller. If you need to pass an entire Model/Form you can easily do this with serialize()
e.g.
$('#myform').on('submit', function(e){
e.preventDefault();
var formData = $(this).serialize();
$.post('/student/update', formData, function(response){
//Do something with response
});
});
So your controller could have a view model as the param e.g.
[HttpPost]
public JsonResult Update(StudentViewModel studentViewModel)
{}
Alternatively if you just want to post some specific values you can do:
$('#myform').on('submit', function(e){
e.preventDefault();
var studentId = $(this).find('#Student_StudentId');
var isActive = $(this).find('#Student_IsActive');
$.post('/my/url', {studentId : studentId, isActive : isActive}, function(response){
//Do something with response
});
});
With a controller like:
[HttpPost]
public JsonResult Update(int studentId, bool isActive)
{}
This project should be helpful - maps touch events to click events in a way that allows jQuery UI to work on iPad and iPhone without any changes. Just add the JS to any existing project.
Atomic size is 4096 bytes, max size is 65536 bytes. Sendfile uses 16 pipes each of 4096 bytes size. cmd : ioctl(fd, FIONREAD, &buff_size).
I solved this by removing android:replace
tag
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
I had the same issue. After about two hours of googling, retries, regenerating API Key many times, etc. i discovered that i enabled the wrong service in the Google APis Console. I enabled Google Maps API v2 Service, but for Android Apps you have to use Google Maps Android API v2. After enabling the right service all started working.
If move_uploaded_file() is not working for you and you are not getting any errors (like in my case), make sure that the size of the file/image you are uploading is not greater than upload_max_filesize value in php.ini.
My upload_max_filesize value was 2MB on my localhost and I kept trying to upload a 4MB image for countless times while trying to figure out what the issue with move_uploaded_file() is.
Here is another answer using Spring MVC's standaloneSetup. Using this way you can either autowire the controller class or Mock it.
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.server.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.server.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.server.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.server.MockMvc;
import org.springframework.test.web.server.setup.MockMvcBuilders;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DemoApplicationTests {
final String BASE_URL = "http://localhost:8080/";
@Autowired
private HelloWorld controllerToTest;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(controllerToTest).build();
}
@Test
public void testSayHelloWorld() throws Exception{
//Mocking Controller
controllerToTest = mock(HelloWorld.class);
this.mockMvc.perform(get("/")
.accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().mimeType(MediaType.APPLICATION_JSON));
}
@Test
public void contextLoads() {
}
}
The global scope in React Native is variable global. Such as global.foo = foo
, then you can use global.foo anywhere.
But do not abuse it! In my opinion, global scope may used to store the global config or something like that. Share variables between different views, as your description, you can choose many other solutions(use redux,flux or store them in a higher component), global scope is not a good choice.
A good practice to define global variable is to use a js file. For example global.js
global.foo = foo;
global.bar = bar;
Then, to make sure it is executed when project initialized. For example, import the file in index.js:
import './global.js'
// other code
Now, you can use the global variable anywhere, and don't need to import global.js in each file. Try not to modify them!
$ cat n 2 4 2 7 8 9
$ perl -MList::Util -le 'print List::Util::sum(<>)' < n
32
Or, you can type in the numbers on the command line:
$ perl -MList::Util -le 'print List::Util::sum(<>)'
1
3
5
^D
9
However, this one slurps the file so it is not a good idea to use on large files. See j_random_hacker's answer which avoids slurping.
Handlebars partials take a second parameter which becomes the context for the partial:
{{> person this}}
In versions v2.0.0 alpha and later, you can also pass a hash of named parameters:
{{> person headline='Headline'}}
You can see the tests for these scenarios: https://github.com/wycats/handlebars.js/blob/ce74c36118ffed1779889d97e6a2a1028ae61510/spec/qunit_spec.js#L456-L462 https://github.com/wycats/handlebars.js/blob/e290ec24f131f89ddf2c6aeb707a4884d41c3c6d/spec/partials.js#L26-L32
To complete @thecatontheflat answer I would recommend to also wrap your action inside of a try … catch
block. This will prevent your JSON endpoint from breaking on exceptions. Here's the skeleton I use:
public function someAction()
{
try {
// Your logic here...
return new JsonResponse([
'success' => true,
'data' => [] // Your data here
]);
} catch (\Exception $exception) {
return new JsonResponse([
'success' => false,
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
]);
}
}
This way your endpoint will behave consistently even in case of errors and you will be able to treat them right on a client side.
To get both functions working for a clickable image that will respond to both short and long clicks, I tried the following that seems to work perfectly:
image = (ImageView) findViewById(R.id.imageViewCompass);
image.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
shortclick();
}
});
image.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
longclick();
return true;
}
});
//Then the functions that are called:
public void shortclick()
{
Toast.makeText(this, "Why did you do that? That hurts!!!", Toast.LENGTH_LONG).show();
}
public void longclick()
{
Toast.makeText(this, "Why did you do that? That REALLY hurts!!!", Toast.LENGTH_LONG).show();
}
It seems that the easy way of declaring the item in XML as clickable and then defining a function to call on the click only applies to short clicks - you must have a listener to differentiate between short and long clicks.
Alternatively, you can apply maven-compiler-plugin with appropriate java version by adding this to your pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
Couple of ways. Firstly, if you're adding a row each time a [de]activation occurs, you can set the column default to GETDATE() and not set the value in the insert. Otherwise,
UPDATE TableName SET [ColumnName] = GETDATE() WHERE UserId = @userId
Apparently in some versions of SQL there's a TABLESAMPLE
command, but it's not in all SQL implementations (notably, Redshift).
http://technet.microsoft.com/en-us/library/ms189108(v=sql.105).aspx
This same warning will be emitted on any state changes done in a render()
call.
An example of a tricky to find case:
When rendering a multi-select GUI component based on state data, if state has nothing to display, a call to resetOptions()
is considered state change for that component.
The obvious fix is to do resetOptions()
in componentDidUpdate()
instead of render()
.
While generating the links set the target to the iframes name property and you probably wont have to deal with jquery at all.
<a href="inventory.aspx" target="contentframe" title="Title Inventory">
<iframe id="iframe1" name="contentframe" ></iframe>
A form submission causes the page to navigate away to the action
of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit()
on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:
var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
postData.push(f.elements[i].name + "=" + f.elements[i].value);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));
document.forms.payPal.submit();
Even i had the same problem . And the fault was with the "unsigned" marker in the FK's table PK
select object_name(c.object_id) as table_name
, schema_name(t.schema_id) as schema_name
from sys.columns c
join sys.tables t on c.object_id = t.object_id
where c.name=N'CreatedDate';
It gets a little more complicated if you want alsoother table properties, but you'll refer to the object catalog views like sys.tables, sys.columns etc.
template.txt
Variable 1 value: ${var1}
Variable 2 value: ${var2}
data.sh
#!/usr/bin/env bash
declare var1="value 1"
declare var2="value 2"
parser.sh
#!/usr/bin/env bash
# args
declare file_data=$1
declare file_input=$2
declare file_output=$3
source $file_data
eval "echo \"$(< $file_input)\"" > $file_output
./parser.sh data.sh template.txt parsed_file.txt
parsed_file.txt
Variable 1 value: value 1
Variable 2 value: value 2
.dropZoneOverlay, .FileUpload {_x000D_
width: 283px;_x000D_
height: 71px;_x000D_
}_x000D_
_x000D_
.dropZoneOverlay {_x000D_
border: dotted 1px;_x000D_
font-family: cursive;_x000D_
color: #7066fb;_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.FileUpload {_x000D_
opacity: 0;_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
}
_x000D_
<div class="dropZoneContainer">_x000D_
<input type="file" id="drop_zone" class="FileUpload" accept=".jpg,.png,.gif" onchange="handleFileSelect(this) " />_x000D_
<div class="dropZoneOverlay">Drag and drop your image <br />or<br />Click to add</div>_x000D_
</div>
_x000D_
I find a good way of achieving this at Remove browse button from input=file.
The rationale behind this solution is that it creates a transparent input=file control and creates an layer visible to the user below the file control. The z-index of the input=file will be higher than the layer.
With this, it appears that the layer is the file control itself. But actually when you clicks on it, the input=file is the one clicked and the dialog for choosing file will appear.
I had the same problem on Win 7. The solution was to remove following files:
As for .hg/store/lock - there was no such file.
toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.
var fval = 4;
console.log(fval.toFixed(2)); // prints 4.00
Right click your project in eclipse, build path -> add external jars.
To use arrow functions with function.prototype.call
, I made a helper function on the object prototype:
// Using
// @func = function() {use this here} or This => {use This here}
using(func) {
return func.call(this, this);
}
usage
var obj = {f:3, a:2}
.using(This => This.f + This.a) // 5
Edit
You don't NEED a helper. You could do:
var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5
GMT -03:00 Example
new Date(new Date()-3600*1000*3).toISOString();
CREATE ROLE blog WITH
LOGIN
SUPERUSER
INHERIT
CREATEDB
CREATEROLE
REPLICATION;
COMMENT ON ROLE blog IS 'Test';
You can't do this yourself since Java doesn't permit operator overloading.
With one exception, however. + and += are overloaded for String objects.
.NET has two CLRs 2.0 and 4.0. CLR 2.0 works till .NET framework 3.5. CLR 4.0 works from .NET 4.0 onwards. Its possible that your solution is using a different CLR than your reference assemblies. In your local development environment, you might have both the CLRs and hence you did not faced any problem. However when you moved to deployment environments, they might have a single CLR only and you got this error.
Now Update word-wrap is replace by :
overflow-wrap:break-word;
Compatible old navigator and css 3 it's good alternative !
it's evolution of word-wrap ( since 2012... )
See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap
See compatibility full : http://caniuse.com/#search=overflow-wrap
From the docs
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".
As you say:
error: missing method body, or declare abstract public static void main(String[] args); ^ this is what i got after i added it after the class name
You probably haven't declared main with a body (as ';" would suggest in your error).
You need to have main method with a body, which means you need to add { and }:
public static void main(String[] args) {
}
Add it inside your class definition.
Although sometimes error messages are not very clear, most of the time they contain enough information to point to the issue. Worst case, you can search internet for the error message. Also, documentation can be really helpful.
Sub Datainput()
'Checkbox values are 0 (false), 1 (true), 2 (changed or grey)
If activesheet.CheckBoxes("Check Box 1").value = 1 then
Msgbox ("Yay")
Else: Msgbox("Aww")
End if
End Sub
Use the BigInteger
class that is a part of the Java library.
http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html
Select ID, IsNull(Cast(ParentID as varchar(max)),'') from Patients
This is needed because field ParentID is not varchar/nvarchar type. This will do the trick:
Select ID, IsNull(ParentID,'') from Patients
.done()
terminates the promise chain, making sure nothing else can attach further steps. This means that the jQuery promise implementation can throw any unhandled exception, since no one can possible handle it using .fail()
.
In practical terms, if you do not plan to attach more steps to a promise, you should use .done()
. For more details see why promises need to be done
I used JSON-C for a work project and would recommend it. Lightweight and is released with open licensing.
Documentation is included in the distribution. You basically have *_add
functions to create JSON objects, equivalent *_put
functions to release their memory, and utility functions that convert types and output objects in string representation.
The licensing allows inclusion with your project. We used it in this way, compiling JSON-C as a static library that is linked in with the main build. That way, we don't have to worry about dependencies (other than installing Xcode).
JSON-C also built for us under OS X (x86 Intel) and Linux (x86 Intel) without incident. If your project needs to be portable, this is a good start.
If you don't have any fancy gem action, but do have JSON, this CLI line will work on a hash:
puts JSON.pretty_generate(my_hash).gsub(":", " =>")
#=>
{
:key1 => "value1",
:key2 => "value2",
:key3 => "value3"
}
I converted the code in Anomie's answer here (copy-pasted above by suvish valsan) into Swift:
func fixOrientation() -> UIImage {
if self.imageOrientation == UIImageOrientation.Up {
return self
}
var transform = CGAffineTransformIdentity
switch self.imageOrientation {
case .Down, .DownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI));
case .Left, .LeftMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0);
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2));
case .Right, .RightMirrored:
transform = CGAffineTransformTranslate(transform, 0, self.size.height);
transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2));
case .Up, .UpMirrored:
break
}
switch self.imageOrientation {
case .UpMirrored, .DownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0)
transform = CGAffineTransformScale(transform, -1, 1)
case .LeftMirrored, .RightMirrored:
transform = CGAffineTransformTranslate(transform, self.size.height, 0)
transform = CGAffineTransformScale(transform, -1, 1);
default:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx = CGBitmapContextCreate(
nil,
Int(self.size.width),
Int(self.size.height),
CGImageGetBitsPerComponent(self.CGImage),
0,
CGImageGetColorSpace(self.CGImage),
UInt32(CGImageGetBitmapInfo(self.CGImage).rawValue)
)
CGContextConcatCTM(ctx, transform);
switch self.imageOrientation {
case .Left, .LeftMirrored, .Right, .RightMirrored:
// Grr...
CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.height,self.size.width), self.CGImage);
default:
CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.width,self.size.height), self.CGImage);
break;
}
// And now we just create a new UIImage from the drawing context
let cgimg = CGBitmapContextCreateImage(ctx)
let img = UIImage(CGImage: cgimg!)
return img;
}
(I replaced all occurencies of the parameter image
with self
, because my code is an extension on UIImage
).
EDIT: Swift 3 version.
The method returns an optional, because many of the intermediate calls can fail and I don't like to use !
.
func fixOrientation() -> UIImage? {
guard let cgImage = self.cgImage else {
return nil
}
if self.imageOrientation == UIImageOrientation.up {
return self
}
let width = self.size.width
let height = self.size.height
var transform = CGAffineTransform.identity
switch self.imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: width, y: height)
transform = transform.rotated(by: CGFloat.pi)
case .left, .leftMirrored:
transform = transform.translatedBy(x: width, y: 0)
transform = transform.rotated(by: 0.5*CGFloat.pi)
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: height)
transform = transform.rotated(by: -0.5*CGFloat.pi)
case .up, .upMirrored:
break
}
switch self.imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: height, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
default:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
guard let colorSpace = cgImage.colorSpace else {
return nil
}
guard let context = CGContext(
data: nil,
width: Int(width),
height: Int(height),
bitsPerComponent: cgImage.bitsPerComponent,
bytesPerRow: 0,
space: colorSpace,
bitmapInfo: UInt32(cgImage.bitmapInfo.rawValue)
) else {
return nil
}
context.concatenate(transform);
switch self.imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
// Grr...
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: height, height: width))
default:
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
}
// And now we just create a new UIImage from the drawing context
guard let newCGImg = context.makeImage() else {
return nil
}
let img = UIImage(cgImage: newCGImg)
return img;
}
(Note: Swift 3 version odes compile under Xcode 8.1, but haven't tested it actually works. There might be a typo somewhere, mixed up width/height, etc. Feel free to point/fix any errors).
To expand a bit more on what others are saying, if you wanted to use join to simply concatenate your two strings, you would do this:
strid = repr(595)
print ''.join([array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring(), strid])
I had a very similar problem where for the form action, I had something like:
<form action="http://www.example.com/?q=content/something" method="GET">
<input type="submit" value="Go away..." />
</form>
The button would get the user to the site, but the query info disappeared so the user landed on the home page rather than the desired content page. The solution in my case was to find out how to code the URL without the query that would get the user to the desired page. In this case my target was a Drupal site, so as it turned out /content/something
also worked. I also could have used a node number (i.e. /node/123
).
Verified the following on Virtualbox-5.0.24, Android_x86-4.4-r5. You get a screen similar to an 8" table. You can play around with the xxx in DPI=xxx, to change the resolution. xxx=100 makes it really small to match a real table exactly, but it may be too small when working with android in Virtualbox.
VBoxManage setextradata <VmName> "CustomVideoMode1" "440x680x16"
With the following appended to android kernel cmd:
UVESA_MODE=440x680 DPI=120
Ctrl+Shift+F formats the selected line(s) or the whole source code if you haven't selected any line(s) as per the format specified in your Eclipse, while Ctrl+I gives proper indent to the selected line(s) or the current line if you haven't selected any line(s). try this. or more precisely
The Ant editor that ships with Eclipse can be used to reformat
XML/XHTML/HTML code (with a few configuration options in Window > Preferences > Ant > Editor).
You can right-click a file then
Open With... > Other... > Internal Editors > Ant Editor
Or add a file association between .html (or .xhtml) and that editor with
Window > Preferences > General > Editors > File Associations
Once open in the editor, hit ESC then CTRL-F to reformat.
I wouldn't set the ngmodel via an attribute, you can specify it right in the template:
template: '<div class="some"><label>{{label}}</label><input data-ng-model="ngModel"></div>',
The easiest solution is going to the config.js and setting:
config.allowedContent = true;
(Remember to clear browser's cache). Then CKEditor stops filtering the inputted content at all. However, this will totally disable content filtering which is one of the most important CKEditor features.
You can also configure CKEditor's content filter more precisely to allow only these element, classes, styles and attributes which you need. This solution is much better, because CKEditor will still remove a lot of crappy HTML which browsers produce when copying and pasting content, but it will not strip the content you want.
For example, you can extend the default CKEditor's configuration to accept all div classes:
config.extraAllowedContent = 'div(*)';
Or some Bootstrap stuff:
config.extraAllowedContent = 'div(col-md-*,container-fluid,row)';
Or you can allow description lists with optional dir
attributes for dt
and dd
elements:
config.extraAllowedContent = 'dl; dt dd[dir]';
These were just very basic examples. You can write all kind of rules - requiring attributes, classes or styles, matching only special elements, matching all elements. You can also disallow stuff and totally redefine CKEditor's rules. Read more about:
For a simple way, use system()
:
#include <stdlib.h>
...
int status = system("./foo 1 2 3");
system()
will wait for foo to complete execution, then return a status variable which you can use to check e.g. exitcode (the command's exitcode gets multiplied by 256, so divide system()'s return value by that to get the actual exitcode: int exitcode = status / 256
).
The manpage for wait()
(in section 2, man 2 wait
on your Linux system) lists the various macros you can use to examine the status, the most interesting ones would be WIFEXITED
and WEXITSTATUS
.
Alternatively, if you need to read foo's standard output, use popen(3)
, which returns a file pointer (FILE *
); interacting with the command's standard input/output is then the same as reading from or writing to a file.
You are most likely escaping the SQL string, similar to:
SELECT * FROM `table` WHERE `column` = 'Here's a syntax error!'
You need to escape quotes, like follows:
SELECT * FROM `table` WHERE `column` = 'Here\'s a syntax error!'
mysql_real_escape_string()
handles this for you.
There are very few cases where you want to use except:
. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit
and KeyboardInterupt
, which can make your program annoying to use..
At the very simplest, you would catch urllib2.URLError
:
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
raise MyException("There was an error: %r" % e)
The following should capture the specific error raised when the connection times out:
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
# For Python 2.6
if isinstance(e.reason, socket.timeout):
raise MyException("There was an error: %r" % e)
else:
# reraise the original error
raise
except socket.timeout, e:
# For Python 2.7
raise MyException("There was an error: %r" % e)
To expand on the Wikipedia-based answers:
The Social Security Administration (SSA) explicitly states in this document that the having "000" in the first group of numbers "will NEVER be a valid SSN":
I'd consider that pretty definitive.
However, that the 2nd or 3rd groups of numbers won't be "00" or "0000" can be inferred from a FAQ that the SSA publishes which indicates that allocation of those groups starts at "01" or "0001":
But this is only a FAQ and it's never outright stated that "00" or "0000" will never be used.
In another FAQ they provide (http://www.socialsecurity.gov/employer/randomizationfaqs.html#a0=6) that "00" or "0000" will never be used.
I can't find a reference to the 'advertisement' reserved SSNs on the SSA site, but it appears that no numbers starting with a 3 digit number higher than 772 (according to the document referenced above) have been assigned yet, but there's nothing I could find that states those numbers are reserved. Wikipedia's reference is a book that I don't have access to. The Wikipedia information on the advertisement reserved numbers is mentioned across the web, but many are clearly copied from Wikipedia. I think it would be nice to have a citation from the SSA, though I suspect that now that Wikipedia has made the idea popular that these number would now have to be reserved for advertisements even if they weren't initially.
The SSA has a page with a couple of stories about SSN's they've had to retire because they were used in advertisements/samples (maybe the SSA should post a link to whatever their current policy on this might be):
bash --rcfile <(echo '. ~/.bashrc; some_command')
dispenses the creation of temporary files. Question on other sites:
If you would like to 'add' additional items to a page, you may want to create an array of maps. This is how I created an array of maps and then added results to it:
import { Product } from '../models/product';
products: Array<Product>; // Initialize the array.
[...]
let i = 0;
this.service.products( i , (result) => {
if ( i == 0 ) {
// Create the first element of the array.
this.products = Array(result);
} else {
// Add to the array of maps.
this.products.push(result);
}
});
Where product.ts look like...
export class Product {
id: number;
[...]
}
The directions state:
- Download the appropriate Instant Client packages for your platform. All installations REQUIRE the Basic package.
- Unzip the packages into a single directory such as "instantclient".
- Set the library loading path in your environment to the directory in Step 2 ("instantclient"). On many UNIX platforms, LD_LIBRARY_PATH is the appropriate environment variable. On Windows, PATH should be used.
- Start your application and enjoy.
Suggest extracting/unzipping into a new directory. They've suggested instantclient
, but you can name the directory anything you like. Name it C:\OracleInstantClient\
if you choose.
Then in Step 3, open a Windows Command Prompt. Type:
PATH C:\OracleInstantClient; %PATH%`
That's all there is to it!
I had the same problem and finally resolved it by changing the order of pem blocks in certificate file.
The cert block should be put in the beginning of the file, then intermediate blocks, then root block.
I realized this problem by comparing a problematic certificate file with a working certificate file.
Use Like this:
Uri uri = Uri.parse(URL); //Declare your url here.
VideoView mVideoView = (VideoView)findViewById(R.id.videoview)
mVideoView.setMediaController(new MediaController(this));
mVideoView.setVideoURI(uri);
mVideoView.requestFocus();
mVideoView.start();
Another Method:
String LINK = "type_here_the_link";
VideoView mVideoView = (VideoView) findViewById(R.id.videoview);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
Uri video = Uri.parse(LINK);
mVideoView.setMediaController(mc);
mVideoView.setVideoURI(video);
mVideoView.start();
If you are getting this error Couldn't open file on client side, trying server side Error in Android. and also Refer this. Hope this will give you some solution.
The truth is even in 3.x it still works, surprisingly the projects builds and deploys. But the LATEST/RELEASE keyword causing problems in m2e and eclipse all over the place, ALSO projects depends on the dependency which deployed through the LATEST/RELEASE fail to recognize the version.
It will also causing problem if you are try to define the version as property, and reference it else where.
So the conclusion is use the versions-maven-plugin if you can.
I tested what @Samy Dindane suggested in the comment on the OP.
I believe it works, try
git fetch <remote_name> <remote_branch>:<local_branch>
git checkout <local_branch>
Here's an example for a fictitious remote repository named foo
with a branch named bar
where I create a local branch bar
tracking the remote:
git fetch foo bar:bar
git checkout bar
In Laravel 6 you can get it like this:
try {
window.$ = window.jQuery = require('jquery');
} catch (e) {}
Your reader
variable is an iterable, by looping over it you retrieve the rows.
To make it skip one item before your loop, simply call next(reader, None)
and ignore the return value.
You can also simplify your code a little; use the opened files as context managers to have them closed automatically:
with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
reader = csv.reader(infile)
next(reader, None) # skip the headers
writer = csv.writer(outfile)
for row in reader:
# process each row
writer.writerow(row)
# no need to close, the files are closed automatically when you get to this point.
If you wanted to write the header to the output file unprocessed, that's easy too, pass the output of next()
to writer.writerow()
:
headers = next(reader, None) # returns the headers or `None` if the input is empty
if headers:
writer.writerow(headers)
session.query().with_entities(SomeModel.col1)
is the same as
session.query(SomeModel.col1)
for alias, we can use .label()
session.query(SomeModel.col1.label('some alias name'))
I had the same problem... I had to run it as a user.
00 * * * * root /usr/bin/php /var/virtual/hostname.nz/public_html/cronjob.php
Install VSCode, then add bash debug extension and you are ready to debug in visual mode. see Here in action.
To have text-align:center
work you need to add that style to the #siteInfo
div or wrap the input in a paragraph and add text-align:center
to the paragraph.
On Mac I could not find the pgrep and pkill neither was killall working so wrote a simple one liner script:-
export pid=`ps | grep process_name | awk 'NR==1{print $1}' | cut -d' ' -f1`;kill $pid
If there's an easier way of doing this then please share.
Android Lollipop introduced camera2 API and deprecated the previous camera API. However, using the deprecated API to turn on the flash still works and is much simpler than using the new API.
It seems that the new API is intended for use in dedicated full featured camera apps and that its architects didn't really consider simpler use cases such as turning on the flashlight. To do that now, one has to get a CameraManager, create a CaptureSession with a dummy Surface, and finally create and start a CaptureRequest. Exception handling, resource cleanup and long callbacks included!
To see how to turn the flashlight on Lollipop and newer, take a look at the FlashlightController in the AOSP project (try to find the newest as older use APIs that have been modified). Don't forget to set the needed permissions.
Android Marshmallow finally introduced a simple way to turn on the flash with setTorchMode.
How about tr {outline: thin solid black;}
? Works for me on tr or tbody elements, and appears to be compatible with the most browsers, including IE 8+ but not before.
In Access 2013. Drop a "Text Box" control onto your form. On the Property Sheet for the control under the Format tab find the Format property. Set this to one of the date format options. Job's done.
For a backgrounder, there are 2 ways to use a ComboBox/ListBox
1) Add Country Objects to the Items property and retrieve a Country as Selecteditem. To use this you should override the ToString of Country.
2) Use DataBinding, set the DataSource to a IList (List<>) and use DisplayMember, ValueMember and SelectedValue
For 2) you will need a list of countries first
// not tested, schematic:
List<Country> countries = ...;
...; // fill
comboBox1.DataSource = countries;
comboBox1.DisplayMember="Name";
comboBox1.ValueMember="Cities";
And then in the SelectionChanged,
if (comboBox1.Selecteditem != null)
{
comboBox2.DataSource=comboBox1.SelectedValue;
}
Consider using the Comparator
interface described here which uses generics so you can avoid casting Object
to Student
.
As Eugene Retunsky said, your first part is the correct way to compare String
s. Also if the lastName
s are equal I think you meant to compare firstName
s, in which case just use compareTo
in the same way.
The error that you get does not seem to be related to the RequestHeader.
And you seem to be confusing Spring REST services with JAX-RS, your method signature should be something like:
@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(@RequestHeader(value="User-Agent") String userAgent, @RequestParam(value = "ID", defaultValue = "") String id) {
// your code goes here
}
And your REST class should have annotations like:
@Controller
@RequestMapping("/rest/")
Regarding the actual question, another way to get HTTP headers is to insert the HttpServletRequest into your method and then get the desired header from there.
Example:
@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(HttpServletRequest request, @RequestParam(value = "ID", defaultValue = "") String id) {
String userAgent = request.getHeader("user-agent");
}
Don't worry about the injection of the HttpServletRequest because Spring does that magic for you ;)
Yes, you can access it through GET
and POST
(trying this simple task would have made you aware of that).
Yes, there are other ways, one of the other "preferred" ways is using sessions. When you would want to use hidden over session is kind of touchy, but any GET / POST data is easily manipulated by the end user. A session is a bit more secure given it is saved to a file on the server and it is much harder for the end user to manipulate without access through the program.
This is what I normally use when I need to pad a value.
SET @PaddedValue = REPLICATE('0', @Length - LEN(@OrigValue)) + CAST(@OrigValue as VARCHAR)
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
We could use tidyr::extract()
x <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)
library(tidyr)
extract(tibble(data=x),"data", regex = "^(.*?)\\.(.*?)\\.(.*?)\\.(.*?)$",into = LETTERS[1:4])
#> # A tibble: 13 x 4
#> A B C D
#> <chr> <chr> <chr> <chr>
#> 1 F US CLE V13
#> 2 F US CA6 U13
#> 3 F US CA6 U13
#> 4 F US CA6 U13
#> 5 F US CA6 U13
#> 6 F US CA6 U13
#> 7 F US CA6 U13
#> 8 F US CA6 U13
#> 9 F US DL U13
#> 10 F US DL U13
#> 11 F US DL U13
#> 12 F US DL Z13
#> 13 F US DL Z13
Another option is to use unglue::unglue_data()
# remotes::install_github("moodymudskipper/unglue")
library(unglue)
unglue_data(x,"{A}.{B}.{C}.{D}")
#> A B C D
#> 1 F US CLE V13
#> 2 F US CA6 U13
#> 3 F US CA6 U13
#> 4 F US CA6 U13
#> 5 F US CA6 U13
#> 6 F US CA6 U13
#> 7 F US CA6 U13
#> 8 F US CA6 U13
#> 9 F US DL U13
#> 10 F US DL U13
#> 11 F US DL U13
#> 12 F US DL Z13
#> 13 F US DL Z13
Created on 2019-09-14 by the reprex package (v0.3.0)
<script type="text/javascript">
/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
function disableSelection(target){
if (typeof target.onselectstart!="undefined") //IE route
target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
target.style.MozUserSelect="none"
else //All other route (ie: Opera)
target.onmousedown=function(){return false}
target.style.cursor = "default"
}
//Sample usages
//disableSelection(document.body) //Disable text selection on entire body
//disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"
</script>
EDIT
Code apparently comes from http://www.dynamicdrive.com
The other answers are correct, but if you are trying to make a list of functions, each with a different parameter, that can be executed later, the following code will do that:
import functools
a = [functools.partial(lambda x: x*x, x) for x in range(10)]
b = []
for i in a:
b.append(i())
In [26]: b
Out[26]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
While the example is contrived, I found it useful when I wanted a list of functions that each print something different, i.e.
import functools
a = [functools.partial(lambda x: print(x), x) for x in range(10)]
for i in a:
i()
I recently had to resolve this issue and here's what I did :
First of all, this solution is around tuning Apache server.
Second main think is that there's a bug in the IE9 which means that the meta tag will not work, instead of this solution try this
uncomment/or add the following line
LoadModule headers_module modules/mod_headers.so
add the following lines
<IfModule headers_module>
Header set X-UA-Compatible: IE=EmulateIE8
</IfModule>
save/restart your Apache server,
Consider a solution using the bash builtin read as illustrated within the code snippet from a ufw firewall script that follows. This approach has the advantage of using as many delimited field sets (not just 2) as are desired. We have used the | delimiter because port range specifiers may require a colon, ie 6001:6010.
#!/usr/bin/env bash
readonly connections=(
'192.168.1.4/24|tcp|22'
'192.168.1.4/24|tcp|53'
'192.168.1.4/24|tcp|80'
'192.168.1.4/24|tcp|139'
'192.168.1.4/24|tcp|443'
'192.168.1.4/24|tcp|445'
'192.168.1.4/24|tcp|631'
'192.168.1.4/24|tcp|5901'
'192.168.1.4/24|tcp|6566'
)
function set_connections(){
local range proto port
for fields in ${connections[@]}
do
IFS=$'|' read -r range proto port <<< "$fields"
ufw allow from "$range" proto "$proto" to any port "$port"
done
}
set_connections
Your problem is that at the moment your incoming_Cid
column defined as CHAR(1)
when it should be CHAR(34)
.
To fix this just issue this command to change your columns' length from 1 to 34
ALTER TABLE calls CHANGE incoming_Cid incoming_Cid CHAR(34);
Here is SQLFiddle demo
Use the xattr
command. You can inspect the extended attributes:
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
com.apple.quarantine
and use the -d
option to delete one extended attribute:
$ xattr -d com.apple.quarantine s.7z
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
you can also use the -c
option to remove all extended attributes:
$ xattr -c s.7z
$ xattr s.7z
xattr -h
will show you the command line options, and xattr has a man page.
I encountered the exact problem running on docker container (in build environment). After ssh into the container, I tried running the test manually and still encountered
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /usr/bin/google-chrome-stable is
no longer running, so ChromeDriver is assuming that Chrome has crashed.)
When I tried running chrome locally /usr/bin/google-chrome-stable
, error message
Running as root without --no-sandbox is not supported
I checked my ChromeOptions and it was missing --no-sandbox
, which is why it couldn't spawn chrome.
capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
chromeOptions: { args: %w(headless --no-sandbox disable-gpu window-size=1920,1080) }
)
create resource layout file list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/header_text"
android:layout_height="0dp"
android:layout_width="fill_parent"
android:layout_weight="1"
android:text="Header"
/>
<TextView
android:id="@+id/item_text"
android:layout_height="0dp"
android:layout_width="fill_parent"
android:layout_weight="1"
android:text="dynamic text"
/>
</LinearLayout>
and initialise adaptor like this
adapter = new ArrayAdapter<String>(this, R.layout.list_item,R.id.item_text,data_array);
You can use the "Test Connection" feature after creating the ODBC connection through Control Panel > Administrative Tools > Data Sources.
To test a SQL command itself you could try:
http://www.sqledit.com/odbc/runner.html
http://www.sqledit.com/sqlrun.zip
Or (perhaps easier and more useful in the long run) you can make a test ASP.NET or PHP page in a couple minutes to run SQL statement yourself through IIS.
You can use @PropertySource
to externalize your configuration to a properties file. There is number of way to do get properties:
1.
Assign the property values to fields by using @Value
with PropertySourcesPlaceholderConfigurer
to resolve ${}
in @Value
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Value("${gMapReportUrl}")
private String gMapReportUrl;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
2.
Get the property values by using Environment
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Autowired
private Environment env;
public void foo() {
env.getProperty("gMapReportUrl");
}
}
Hope this can help
string textboxID;
string da;
textboxID = "ctl00$MainContent$grd$ctl" + (grd.Columns.Count + j).ToString() + "$txtDyna" + (k).ToString();
textboxID= ctl00$MainContent$grd$ctl12$ctl00;
da = Request.Form(textboxID);
You definitely want to use the second expression since months in JS are enumerated from 0.
Also you may use Date.parse method, but it uses different date format:
var timestamp = Date.parse("11/30/2011");
var dateObject = new Date(timestamp);
Still relevant in 2018: don't install packages as admin.
The by far more sensible solution is to use virtualenv to create a virtual environment directory (virtualenv dirname
) and then activate that virtual environment with dirname\Script\Activate
in Windows before running any pip commands. Or use pipenv to manage the installs for you.
That way, everything gets written to dirs that you have full write permission for, without needing UAC, and without global installs for local directories.
SELECT emp.LoginID, emp.JobTitle, emp.BirthDate, emp.ModifiedDate ,
CASE WHEN emp.JobTitle NOT LIKE '%Document Control%' THEN emp.JobTitle
ELSE SUBSTRING(emp.JobTitle,CHARINDEX('Document Control',emp.JobTitle),LEN('Document Control'))
END
,emp.gender,emp.MaritalStatus
FROM HumanResources.Employee [emp]
WHERE JobTitle LIKE '[C-F]%'
As explained in the Apache POI Javadocs, you should not use cell.setCellType(Cell.CELL_TYPE_STRING)
to get the string value of a numeric cell, as you'll loose all the formatting
Instead, as the javadocs explain, you should use DataFormatter
What DataFormatter does is take the floating point value representing the cell is stored in the file, along with the formatting rules applied to it, and returns you a string that look like it the cell does in Excel.
So, if you're after a String of the cell, looking much as you had it looking in Excel, just do:
// Create a formatter, do this once
DataFormatter formatter = new DataFormatter(Locale.US);
.....
for (int i=1; i <= sheet.getLastRowNum(); i++) {
Row r = sheet.getRow(i);
if (r == null) {
// empty row, skip
} else {
String j_username = formatter.formatCellValue(row.getCell(0));
String j_password = formatter.formatCellValue(row.getCell(1));
// Use these
}
}
The formatter will return String cells as-is, and for Numeric cells will apply the formatting rules on the style to the number of the cell
I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..
Opening A Seperate File:
ChDir "[Path here]" 'get into the right folder here
Workbooks.Open Filename:= "[Path here]" 'include the filename in this path
'copy data into current workbook or whatever you want here
ActiveWindow.Close 'closes out the file
Opening A File With Specified Date If It Exists:
I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.
Some common error checking statements:
On Error Resume Next 'if error occurs continues on to the next line (ignores it)
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Or (better option):
if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?
you would most likely want to use the GoTo ErrorHandler
shown below to achieve this
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
ErrorHandler:
'Display error message or any code you want to run on error here
Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm
Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/
Hope this helps!
Example on how to ensure error code doesn't run EVERYtime:
if you debug through the code without the Exit Sub
BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.
Sub Macro
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Exit Sub 'Code will exit BEFORE ErrorHandler if everything goes smoothly
'Otherwise, on error, ErrorHandler will be run
ErrorHandler:
'Display error message or any code you want to run on error here
End Sub
Also, look at this other question in you need more reference to how this works: goto block not working VBA
Add a CommandName attribute, and optionally a CommandArgument attribute, to your LinkButton control. Then set the OnCommand attribute to the name of your Command event handler.
<asp:LinkButton ID="ENameLinkBtn" runat="server" CommandName="MyValueGoesHere" CommandArgument="OtherValueHere"
style="font-weight: 700; font-size: 8pt;" OnCommand="ENameLinkBtn_Command" ><%# Eval("EName") %></asp:LinkButton>
<asp:Label id="Label1" runat="server"/>
Then it will be available when in your handler:
protected void ENameLinkBtn_Command (object sender, CommandEventArgs e)
{
Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}
More info on MSDN
List<long> distinctlongs = longs.Distinct().OrderBy(x => x).ToList();
Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.
If the gif is displayed but not animating, see reference links at very bottom of this answer.
Displaying the gif + overlay, however, is easier than you might think.
All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.
So, when the button is pressed, just unhide those two divs. That's it!
$("#button").click(function() {_x000D_
$('#myOverlay').show();_x000D_
$('#loadingGIF').show();_x000D_
setTimeout(function(){_x000D_
$('#myOverlay, #loadingGIF').fadeOut();_x000D_
},2500);_x000D_
});_x000D_
/* Or, remove overlay/image on click background... */_x000D_
$('#myOverlay').click(function(){_x000D_
$('#myOverlay, #loadingGIF').fadeOut();_x000D_
});
_x000D_
body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
#myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}_x000D_
#myOverlay{display:none;backdrop-filter:blur(4px);background:black;opacity:.4;z-index:2;}_x000D_
_x000D_
#loadingGIF{position:absolute;top:10%;left:35%;z-index:3;display:none;}_x000D_
_x000D_
button{margin:5px 30px;padding:10px 20px;}
_x000D_
<div id="myOverlay"></div>_x000D_
<div id="loadingGIF"><img src="http://placekitten.com/150/80" /></div>_x000D_
_x000D_
<div id="abunchoftext">_x000D_
Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="http://www.online-literature.com/poe/335/" target="_blank">Apologies To Poe</a></div>_x000D_
<button id="button">Submit</button>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
_x000D_
You might enjoy playing with the new backdrop-filter:blur(_px)
css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)
References:
http://www.paulirish.com/2007/animated-gif-not-animating/
Animated GIF while loading page does not animate
https://wordpress.org/support/topic/animated-gif-not-working
You can do the following:
String str = "abcd";
char arr[] = new char[len]; // len is the length of the array
arr = str.toCharArray();
I think one of the Advantages of code first is that you can back up all the changes you've made to a version control system like Git. Because all your tables and relationships are stored in what are essentially just classes, you can go back in time and see what the structure of your database was before.
Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:
GRANT CREATE JOB TO scott;
After this statement is executed, scott can create jobs, schedules, or programs in his schema.
copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239
Incase someone is still trying to figure this out. This is how you get the center X and Y of the view
.
int pos[] = new int[2];
view.getLocationOnScreen(pos);
int centerX = pos[0] + view.getMeasuredWidth() / 2;
int centerY = pos[1] + view.getMeasuredHeight() / 2;
# coding: utf-8
from __future__ import unicode_literals
import base64
import os
import six
from Crypto import Random
from Crypto.PublicKey import RSA
class PublicKeyFileExists(Exception): pass
class RSAEncryption(object):
PRIVATE_KEY_FILE_PATH = None
PUBLIC_KEY_FILE_PATH = None
def encrypt(self, message):
public_key = self._get_public_key()
public_key_object = RSA.importKey(public_key)
random_phrase = 'M'
encrypted_message = public_key_object.encrypt(self._to_format_for_encrypt(message), random_phrase)[0]
# use base64 for save encrypted_message in database without problems with encoding
return base64.b64encode(encrypted_message)
def decrypt(self, encoded_encrypted_message):
encrypted_message = base64.b64decode(encoded_encrypted_message)
private_key = self._get_private_key()
private_key_object = RSA.importKey(private_key)
decrypted_message = private_key_object.decrypt(encrypted_message)
return six.text_type(decrypted_message, encoding='utf8')
def generate_keys(self):
"""Be careful rewrite your keys"""
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
private, public = key.exportKey(), key.publickey().exportKey()
if os.path.isfile(self.PUBLIC_KEY_FILE_PATH):
raise PublicKeyFileExists('???? ? ????????? ?????? ??????????. ??????? ????')
self.create_directories()
with open(self.PRIVATE_KEY_FILE_PATH, 'w') as private_file:
private_file.write(private)
with open(self.PUBLIC_KEY_FILE_PATH, 'w') as public_file:
public_file.write(public)
return private, public
def create_directories(self, for_private_key=True):
public_key_path = self.PUBLIC_KEY_FILE_PATH.rsplit('/', 1)
if not os.path.exists(public_key_path):
os.makedirs(public_key_path)
if for_private_key:
private_key_path = self.PRIVATE_KEY_FILE_PATH.rsplit('/', 1)
if not os.path.exists(private_key_path):
os.makedirs(private_key_path)
def _get_public_key(self):
"""run generate_keys() before get keys """
with open(self.PUBLIC_KEY_FILE_PATH, 'r') as _file:
return _file.read()
def _get_private_key(self):
"""run generate_keys() before get keys """
with open(self.PRIVATE_KEY_FILE_PATH, 'r') as _file:
return _file.read()
def _to_format_for_encrypt(value):
if isinstance(value, int):
return six.binary_type(value)
for str_type in six.string_types:
if isinstance(value, str_type):
return value.encode('utf8')
if isinstance(value, six.binary_type):
return value
And use
KEYS_DIRECTORY = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS
class TestingEncryption(RSAEncryption):
PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'
PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'
# django/flask
from django.core.files import File
class ProductionEncryption(RSAEncryption):
PUBLIC_KEY_FILE_PATH = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS + 'public.key'
def _get_private_key(self):
"""run generate_keys() before get keys """
from corportal.utils import global_elements
private_key = global_elements.request.FILES.get('private_key')
if private_key:
private_key_file = File(private_key)
return private_key_file.read()
message = 'Hello ??? friend'
encrypted_mes = ProductionEncryption().encrypt(message)
decrypted_mes = ProductionEncryption().decrypt(message)
I use http://hurl.it/
Ha. Sorry, I mis-read your post. I've used cucumber to test it before. It worked out nicely.
hi firstly there seems to be many 'errors' in your html where you are missing closing tags, you could try wrapping the contents of your <body>
in a fixed width <div style="margin: 0 auto; width: 900px>
to achieve what you have done with the body {margin: 0 10% 0 10%}
If you missed to check the "generate web.xml" option when creating a new project, no worries If it is a Dynamic Web Project in your project right click on "Deployment Descriptor:...." and Click on "Generate Deployment Descriptor Stub" this will create a minimal /webapp/WEB-INF/web.xml.
I am just using the java.net
package.
Here you can do the following:
...
import java.net.URI;
...
String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);
try this:
ffmpeg -i "path to file" -f null /dev/null 2>&1 | grep 'frame=' | cut -f 2 -d ' '
A little late reply, but what I found in Notepad++ v7.8.6 is, on RMB (Right Mouse Button), on selection text, it gives an option called "Style token" where it shows "Using 1st/2nd/3rd/4th/5th style" to highlight the selected text in different pre-defined colors
My Newbie way ;-) Please let me know if that's correct. It seems to be working for all my cases:
#define IPT_SIZE 5
int findNULL(char* arr)
{
for (int i = 0; i < strlen(arr); i++)
{
if (*(arr+i) == '\n')
{
return i;
}
}
return 0;
}
int main()
{
char *input = malloc(IPT_SIZE + 1 * sizeof(char)), buff;
int counter = 0;
//prompt user for the input:
printf("input string no longer than %i characters: ", IPT_SIZE);
do
{
fgets(input, 1000, stdin);
*(input + findNULL(input)) = '\0';
if (strlen(input) > IPT_SIZE)
{
printf("error! the given string is too large. try again...\n");
counter++;
}
//if the counter exceeds 3, exit the program (custom function):
errorMsgExit(counter, 3);
}
while (strlen(input) > IPT_SIZE);
//rest of the program follows
free(input)
return 0;
}
You can accomplish what you want, I think, simply by including the submit button within the paragraph:
<pre>
<p>Read this sentence <input type='submit' value='or push this button'/></p>
</pre>
JDK 1.8 have some more enrich feature which doesn't support to many eclipse .
If you didn't find java compliance level as 1.8 in java compiler ,then go ahead and install the below eclipse 32bit or 64 bit depending on your system supports.
Try running one java program supports to java 8 like lambda expression as below and if no compilation error ,means your eclipse supports to java 1.8, something like this:
interface testI{
void show();
}
/*class A implements testI{
public void show(){
System.out.println("Hello");
}
}*/
public class LambdaDemo1 {
public static void main(String[] args) {
testI test ;
/*test= new A();
test.show();*/
test = () ->System.out.println("Hello,how are you?"); //lambda
test.show();
}
}
int integer = 60;
byte[] bytes = new byte[4];
for (int i = 0; i < 4; i++) {
bytes[i] = (byte)(integer >>> (i * 8));
}
Swift 3.0
Create a ViewController with the UITableViewDelegate and UITableViewDataSource protocols. Then create a tableView inside it, declaring its style to be UITableViewStyle.grouped. This will fix the headers.
lazy var tableView: UITableView = {
let view = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped)
view.delegate = self
view.dataSource = self
view.separatorStyle = .none
return view
}()
There were a few ways I found to do this:
java InstallCert [host]:[port] keytool -exportcert -keystore jssecacerts -storepass changeit -file output.cert keytool -importcert -keystore [DESTINATION_KEYSTORE] -file output.cert
I'm not quite sure what you're attempting to use the div for, but this is an example with some random text.
Mr_Green gave the correct instructions when he said to add overflow-y: auto
as that restricts it to vertical scrolling. This is a JSFiddle example:
Modifying the startup.bat with the CATALINA_OPTS AND JPDA_OPTS didn't work for me but adding them to catalina.bat did
CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"
change call "%EXECUTABLE%" start %CMD_LINE_ARGS% to
call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%
Then configure remote java application in your debug configurations in Eclipse.
<foo name="port">
<value>${my.server.port:8088}</value>
</foo>
should work for you to have 8088 as default port
See also: http://blog.callistaenterprise.se/2011/11/17/configure-your-spring-web-application/
For updating a record:
UPDATE Employees SET [Photo] = (SELECT
MyImage.* from Openrowset(Bulk
'C:\photo.bmp', Single_Blob) MyImage)
where Id = 10
Notes:
You can achieve this by deploying something at a higher layer than namespaced Services, like the service loadbalancer https://github.com/kubernetes/contrib/tree/master/service-loadbalancer. If you want to restrict it to a single namespace, use "--namespace=ns" argument (it defaults to all namespaces: https://github.com/kubernetes/contrib/blob/master/service-loadbalancer/service_loadbalancer.go#L715). This works well for L7, but is a little messy for L4.
I just did this last week. Set the GrowStyle
on the TableLayoutPanel
to AddRows
or AddColumns
, then your code should work:
// Adds "myControl" to the first column of each row
myTableLayoutPanel.Controls.Add(myControl1, 0 /* Column Index */, 0 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl2, 0 /* Column Index */, 1 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl3, 0 /* Column Index */, 2 /* Row index */);
Here is some working code that seems similar to what you are doing:
private Int32 tlpRowCount = 0;
private void BindAddress()
{
Addlabel(Addresses.Street);
if (!String.IsNullOrEmpty(Addresses.Street2))
{
Addlabel(Addresses.Street2);
}
Addlabel(Addresses.CityStateZip);
if (!String.IsNullOrEmpty(Account.Country))
{
Addlabel(Address.Country);
}
Addlabel(String.Empty); // Notice the empty label...
}
private void Addlabel(String text)
{
label = new Label();
label.Dock = DockStyle.Fill;
label.Text = text;
label.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
tlpAddress.Controls.Add(label, 1, tlpRowCount);
tlpRowCount++;
}
The TableLayoutPanel
always gives me fits with size. In my example above, I'm filing an address card that might grow or shrink depending on the account having an address line two, or a country. Because the last row, or column, of the table layout panel will stretch, I throw the empty label in there to force a new empty row, then everything lines up nicely.
Here is the designer code so you can see the table I start with:
//
// tlpAddress
//
this.tlpAddress.AutoSize = true;
this.tlpAddress.BackColor = System.Drawing.Color.Transparent;
this.tlpAddress.ColumnCount = 2;
this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 25F));
this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tlpAddress.Controls.Add(this.pictureBox1, 0, 0);
this.tlpAddress.Dock = System.Windows.Forms.DockStyle.Fill;
this.tlpAddress.Location = new System.Drawing.Point(0, 0);
this.tlpAddress.Name = "tlpAddress";
this.tlpAddress.Padding = new System.Windows.Forms.Padding(3);
this.tlpAddress.RowCount = 2;
this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tlpAddress.Size = new System.Drawing.Size(220, 95);
this.tlpAddress.TabIndex = 0;
If the array is multidimensional, this will work great:
//trims empty spaces in array elements (recursively trim multidimesional arrays)
function trimData($data){
if($data == null)
return null;
if(is_array($data)){
return array_map('trimData', $data);
}else return trim($data);
}
one sample test is like this:
$arr=[" aaa ", " b ", "m ", [" .e ", " 12 3", "9 0 0 0 "]];
print_r(trimData($arr));
//RESULT
//Array ( [0] => aaa [1] => b [2] => m [3] => Array ( [0] => .e [1] => 12 3 [2] => 9 0 0 0 ) )
I have an alternative way without regexp, and it seems to perform pretty good. It is a continuation on Brandon Moretz answer:
public static string RemoveWhitespace(this string input)
{
return new string(input.ToCharArray()
.Where(c => !Char.IsWhiteSpace(c))
.ToArray());
}
I tested it in a simple unit test:
[Test]
[TestCase("123 123 1adc \n 222", "1231231adc222")]
public void RemoveWhiteSpace1(string input, string expected)
{
string s = null;
for (int i = 0; i < 1000000; i++)
{
s = input.RemoveWhitespace();
}
Assert.AreEqual(expected, s);
}
[Test]
[TestCase("123 123 1adc \n 222", "1231231adc222")]
public void RemoveWhiteSpace2(string input, string expected)
{
string s = null;
for (int i = 0; i < 1000000; i++)
{
s = Regex.Replace(input, @"\s+", "");
}
Assert.AreEqual(expected, s);
}
For 1,000,000 attempts the first option (without regexp) runs in less then a second (700 ms on my machine), and the second takes 3.5 seconds.
The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u
means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u
in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.
You can create a Unicode string multiple ways:
>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'
But the real reason is to represent something like this (translation here):
>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????
For the most part, Unicode and non-Unicode strings are interoperable on Python 2.
There are other symbols you will see, such as the "raw" symbol r
for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.
>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'
Unicode and non-Unicode strings can be equal on Python 2:
>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True
but not on Python 3:
>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False
To replace multiples columns convert to numpy array using .values
:
df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2
Some might encounter this error (I got it while implementing PHP-MySQLi-JSON-Google Chart Example):
You called the draw() method with the wrong type of data rather than a DataTable or DataView.
The solution would be: replace jsapi and just use loader.js with:
google.charts.load('current', {packages: ['corechart']}) and
google.charts.setOnLoadCallback
-- according to the release notes --> The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
Make sure to call the release() method to release the camera when it is no longer needed, or you will not be able to use the camera. Perhaps as a sanity check, see if your regular camera works. If it says it fails, then your previous attempts at runni
ActiveRecord is clever enough to know that the parameter referred to by the ?
is a string, and so it encloses it in single quotes. You could as one post suggests use Ruby string interpolation to pad the string with the required %
symbols. However, this might expose you to SQL-injection (which is bad). I would suggest you use the SQL CONCAT()
function to prepare the string like so:
"name LIKE CONCAT('%',?,'%') OR postal_code LIKE CONCAT('%',?,'%')", search, search)
This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout
.
someView.layoutParams = LinearLayout.LayoutParams(100, 200)
This allows to set the width and height (100
and 200
) in a single line.
For anything with requests to URLs you might want to check out requests. For JSON in particular:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
Try adding wmode, it seems to have two parameters.
&wmode=Opaque
&wmode=transparent
I can't find a technical reason why it works, or much more explanation but take at look at this query.
<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/lzQgAR_J1PI?wmode=transparent" frameborder="0" wmode="Opaque">
or this
//Fix z-index youtube video embedding
$(document).ready(function (){
$('iframe').each(function(){
var url = $(this).attr("src");
$(this).attr("src",url+"?wmode=transparent");
});
});
Tested on 4.2.7 release
package com.national.software.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import com.national.software.dto.UserDetails;
public class HibernateTest {
static SessionFactory sessionFactory;
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("user1");
Configuration config = new Configuration();
config.configure();
ServiceRegistry serviceRegistry = (ServiceRegistry) new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
sessionFactory = config.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
This answer is more like an addition and a slight modification to the answers above.
In some versions of Visual Studio (and possibly other compilers) there is a bug that is really annoying and doesn't make sense. So if you declare/define your swap
function like this:
friend void swap(A& first, A& second) {
std::swap(first.size, second.size);
std::swap(first.arr, second.arr);
}
... the compiler will yell at you when you call the swap
function:
This has something to do with a friend
function being called and this
object being passed as a parameter.
A way around this is to not use friend
keyword and redefine the swap
function:
void swap(A& other) {
std::swap(size, other.size);
std::swap(arr, other.arr);
}
This time, you can just call swap
and pass in other
, thus making the compiler happy:
After all, you don't need to use a friend
function to swap 2 objects. It makes just as much sense to make swap
a member function that has one other
object as a parameter.
You already have access to this
object, so passing it in as a parameter is technically redundant.
This answer might be stupid, but I spent quite some time to figure it out.
What happened to me was I didn't set display: flex
to the container. And of course, justify-content
won't work without a container with that property.
Try doing
document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>'
There are two solutions for it.
Solution number one: 1.Recreate the project. While creating a project ensure that precompiled header is checked(Application settings... *** Do not check empty project)
Solution Number two: 1.Create stdafx.h and stdafx.cpp in your project 2 Right click on project -> properties -> C/C++ -> Precompiled Headers 3.select precompiled header to create(/Yc) 4.Rebuild the solution
Drop me a message if you encounter any issue.
If you are using jQuery 1.7:
alert($(this).prop("class"));
or:
alert($(event.target).prop("class"));
$('#dropdownid').val('selectedvalue');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id='dropdownid'>_x000D_
<option value=''>- Please choose -</option>_x000D_
<option value='1'>1</option>_x000D_
<option value='2'>2</option>_x000D_
<option value='selectedvalue'>There we go!</option>_x000D_
<option value='3'>3</option>_x000D_
<option value='4'>4</option>_x000D_
<option value='5'>5</option>_x000D_
</select>
_x000D_
The return statements should place in one line. Or the other option is to remove the curly brackets that bound the HTML statement.
example:
return posts.map((post, index) =>
<div key={index}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
);
I had a similar issue.
The command I used was as follows:
wget -qO https://download.jitsi.org/jitsi-key.gpg.key | apt-key add -
I forgot a hyphen between the flags and the URL, which is why wget threw an error.
This is the command that finally worked for me:
wget -qO - https://download.jitsi.org/jitsi-key.gpg.key | apt-key add -
The posted setdiff
answer is nice. I just thought I'd post this related function I wrote a while back. Its usefulness is up to the reader :-).
lstype<-function(type='closure'){
inlist<-ls(.GlobalEnv)
if (type=='function') type <-'closure'
typelist<-sapply(sapply(inlist,get),typeof)
return(names(typelist[typelist==type]))
}
My solution would probably be considered kind of bogus but I had a similar situation as mayoneez (I wanted to switch views in response to a gesture in an EAGLView), and I got the EAGL's view controller this way:
EAGLViewController *vc = ((EAGLAppDelegate*)[[UIApplication sharedApplication] delegate]).viewController;
I think you are talking about padding strings with spaces.
One way to do this is with string format codes.
For example, if you want to pad a string to a certain length with spaces, use something like this:
String padded = String.format("%-20s", str);
In a formatter, %
introduces a format sequence. The -
means that the string will be left-justified (spaces will be added on the right of the string). The 20
means the resulting string will be 20 characters long. The s
is the character string format code, and ends the format sequence.
This is clearly not the right or best way to do, however it is cleaner to my view:
this.state.hugeNestedObject = hugeNestedObject;
this.state.anotherHugeNestedObject = anotherHugeNestedObject;
this.setState({})
However, React itself should iterate thought nested objects and update state and DOM accordingly which is not there yet.
Update 2020
Products are located mainly in the following tables:
wp_posts
table with post_type
like product
(or product_variation
),
wp_postmeta
table with post_id
as relational index (the product ID).
wp_wc_product_meta_lookup
table with product_id
as relational index (the post ID) | Allow fast queries on specific product data (since WooCommerce 3.7)
wp_wc_order_product_lookup
table with product_id
as relational index (the post ID) | Allow fast queries to retrieve products on orders (since WooCommerce 3.7)
Product types, categories, subcategories, tags, attributes and all other custom taxonomies are located in the following tables:
wp_terms
wp_termmeta
wp_term_taxonomy
wp_term_relationships
- column object_id
as relational index (the product ID)
wp_woocommerce_termmeta
wp_woocommerce_attribute_taxonomies
(for product attributes only)
wp_wc_category_lookup
(for product categories hierarchy only since WooCommerce 3.7)
Product types are handled by custom taxonomy product_type
with the following default terms:
simple
grouped
variable
external
Some other product types for Subscriptions and Bookings plugins:
subscription
variable-subscription
booking
Since Woocommerce 3+ a new custom taxonomy named product_visibility
handle:
exclude-from-search
and exclude-from-catalog
featured
outofstock
rated-1
to rated-5
Particular feature: Each product attribute is a custom taxonomy…
References:
Short version: it's marking that hash as attached to the current package namespace (so that that package provides its class implementation).
DisplayName
sets the DisplayName
in the model metadata. For example:
[DisplayName("foo")]
public string MyProperty { get; set; }
and if you use in your view the following:
@Html.LabelFor(x => x.MyProperty)
it would generate:
<label for="MyProperty">foo</label>
Display
does the same, but also allows you to set other metadata properties such as Name, Description, ...
Brad Wilson has a nice blog post covering those attributes.
Another way is to use System.Threading.ManualResetEvent
dim SecondsToWait as integer = 5
Dim Waiter As New ManualResetEvent(False)
Waiter.WaitOne(SecondsToWait * 1000) 'to get it into milliseconds
This is the solution that I came up with for this problem which works for me.
library used: momentjs with plain javascript Date class.
Step 1.
Convert String date to moment object (PS: moment retains the original date and time as long as toDate()
method is not called):
const dateMoment = moment("2005-07-08T11:22:33+0000");
Step 2.
Extract hours
and minutes
values from the previously created moment object:
const hours = dateMoment.hours();
const mins = dateMoment.minutes();
Step 3. Convert moment to Date(PS: this will change the original date based on the timezone of your browser/machine, but don't worry and read step 4.):
const dateObj = dateMoment.toDate();
Step 4. Manually set the hours and minutes extracted in Step 2.
dateObj.setHours(hours);
dateObj.setMinutes(mins);
Step 5.
dateObj
will now have show the original Date without any timezone difference. Even the Daylight time changes won't have any effect on the date object as we are manually setting the original hours and minutes.
Hope this helps.
Just adding another idea you could use a child selector to get immediate children
document.querySelectorAll(".parent > .child1");
should return all the immediate children with class .child1
As you state in one of your comments that the table in question is in a different database, then ownership chaining applies. I suspect there is a break in the chain somewhere - check that link for full details.
(Added 26 Sept. 2020)
On 24 Oct. 2009, as @pixelbeat first pointed out here, Bruno Haible empirically discovered the following default thread stack sizes for several systems. He said that in a multithreaded program, "the default thread stack size is:"
- glibc i386, x86_64 7.4 MB - Tru64 5.1 5.2 MB - Cygwin 1.8 MB - Solaris 7..10 1 MB - MacOS X 10.5 460 KB - AIX 5 98 KB - OpenBSD 4.0 64 KB - HP-UX 11 16 KB
Note that the above units are all in MB and KB (base 1000 numbers), NOT MiB and KiB (base 1024 numbers). I've proven this to myself by verifying the 7.4 MB case.
He also stated that:
32 KB is more than you can safely allocate on the stack in a multithreaded program
And he said:
And the default stack size for sigaltstack, SIGSTKSZ, is
- only 16 KB on some platforms: IRIX, OSF/1, Haiku.
- only 8 KB on some platforms: glibc, NetBSD, OpenBSD, HP-UX, Solaris.
- only 4 KB on some platforms: AIX.
Bruno
He wrote the following simple Linux C program to empirically determine the above values. You can run it on your system today to quickly see what your maximum thread stack size is, or you can run it online on GDBOnline here: https://onlinegdb.com/rkO9JnaHD.
Explanation: It simply creates a single new thread, so as to check the thread stack size and NOT the program stack size, in case they differ, then it has that thread repeatedly allocate 128 bytes of memory on the stack (NOT the heap), using the Linux alloca()
call, after which it writes a 0 to the first byte of this new memory block, and then it prints out how many total bytes it has allocated. It repeats this process, allocating 128 more bytes on the stack each time, until the program crashes with a Segmentation fault (core dumped)
error. The last value printed is the estimated maximum thread stack size allowed for your system.
Important note: alloca()
allocates on the stack: even though this looks like dynamic memory allocation onto the heap, similar to a malloc()
call, alloca()
does NOT dynamically allocate onto the heap. Rather, alloca()
is a specialized Linux function to "pseudo-dynamically" (I'm not sure what I'd call this, so that's the term I chose) allocate directly onto the stack as though it was statically-allocated memory. Stack memory used and returned by alloca()
is scoped at the function-level, and is therefore "automatically freed when the function that called alloca()
returns to its caller." That's why its static scope isn't exited and memory allocated by alloca()
is NOT freed each time a for
loop iteration is completed and the end of the for
loop scope is reached. See man 3 alloca
for details. Here's the pertinent quote (emphasis added):
DESCRIPTION
Thealloca()
function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that calledalloca()
returns to its caller.RETURN VALUE
Thealloca()
function returns a pointer to the beginning of the allocated space. If the allocation causes stack overflow, program behavior is undefined.
Here is Bruno Haible's program from 24 Oct. 2009, copied directly from the GNU mailing list here:
Again, you can run it live online here.
// By Bruno Haible
// 24 Oct. 2009
// Source: https://lists.gnu.org/archive/html/bug-coreutils/2009-10/msg00262.html
// =============== Program for determining the default thread stack size =========
#include <alloca.h>
#include <pthread.h>
#include <stdio.h>
void* threadfunc (void*p) {
int n = 0;
for (;;) {
printf("Allocated %d bytes\n", n);
fflush(stdout);
n += 128;
*((volatile char *) alloca(128)) = 0;
}
}
int main()
{
pthread_t thread;
pthread_create(&thread, NULL, threadfunc, NULL);
for (;;) {}
}
When I run it on GDBOnline using the link above, I get the exact same results each time I run it, as both a C and a C++17 program. It takes about 10 seconds or so to run. Here are the last several lines of the output:
Allocated 7449856 bytes Allocated 7449984 bytes Allocated 7450112 bytes Allocated 7450240 bytes Allocated 7450368 bytes Allocated 7450496 bytes Allocated 7450624 bytes Allocated 7450752 bytes Allocated 7450880 bytes Segmentation fault (core dumped)
So, the thread stack size is ~7.45 MB for this system, as Bruno mentioned above (7.4 MB).
I've made a few changes to the program, mostly just for clarity, but also for efficiency, and a bit for learning.
Summary of my changes:
[learning] I passed in BYTES_TO_ALLOCATE_EACH_LOOP
as an argument to the threadfunc()
just for practice passing in and using generic void*
arguments in C.
[efficiency] I made the main thread sleep instead of wastefully spinning.
[clarity] I added more-verbose variable names, such as BYTES_TO_ALLOCATE_EACH_LOOP
and bytes_allocated
.
[clarity] I changed this:
*((volatile char *) alloca(128)) = 0;
to this:
volatile uint8_t * byte_buff =
(volatile uint8_t *)alloca(BYTES_TO_ALLOCATE_EACH_LOOP);
byte_buff[0] = 0;
Here is my modified test program, which does exactly the same thing as Bruno's, and even has the same results:
You can run it online here, or download it from my repo here. If you choose to run it locally from my repo, here's the build and run commands I used for testing:
Build and run it as a C program:
mkdir -p bin && \
gcc -Wall -Werror -g3 -O3 -std=c11 -pthread -o bin/tmp \
onlinegdb--empirically_determine_max_thread_stack_size_GS_version.c && \
time bin/tmp
Build and run it as a C++ program:
mkdir -p bin && \
g++ -Wall -Werror -g3 -O3 -std=c++17 -pthread -o bin/tmp \
onlinegdb--empirically_determine_max_thread_stack_size_GS_version.c && \
time bin/tmp
It takes < 0.5 seconds to run locally on a fast computer with a thread stack size of ~7.4 MB.
Here's the program:
// =============== Program for determining the default thread stack size =========
// Modified by Gabriel Staples, 26 Sept. 2020
// Originally by Bruno Haible
// 24 Oct. 2009
// Source: https://lists.gnu.org/archive/html/bug-coreutils/2009-10/msg00262.html
#include <alloca.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h> // sleep
/// Thread function to repeatedly allocate memory within a thread, printing
/// the total memory allocated each time, until the program crashes. The last
/// value printed before the crash indicates how big a thread's stack size is.
void* threadfunc(void* bytes_to_allocate_each_loop)
{
const uint32_t BYTES_TO_ALLOCATE_EACH_LOOP =
*(uint32_t*)bytes_to_allocate_each_loop;
uint32_t bytes_allocated = 0;
while (true)
{
printf("bytes_allocated = %u\n", bytes_allocated);
fflush(stdout);
// NB: it appears that you don't necessarily need `volatile` here,
// but you DO definitely need to actually use (ex: write to) the
// memory allocated by `alloca()`, as we do below, or else the
// `alloca()` call does seem to get optimized out on some systems,
// making this whole program just run infinitely forever without
// ever hitting the expected segmentation fault.
volatile uint8_t * byte_buff =
(volatile uint8_t *)alloca(BYTES_TO_ALLOCATE_EACH_LOOP);
byte_buff[0] = 0;
bytes_allocated += BYTES_TO_ALLOCATE_EACH_LOOP;
}
}
int main()
{
const uint32_t BYTES_TO_ALLOCATE_EACH_LOOP = 128;
pthread_t thread;
pthread_create(&thread, NULL, threadfunc,
(void*)(&BYTES_TO_ALLOCATE_EACH_LOOP));
while (true)
{
const unsigned int SLEEP_SEC = 10000;
sleep(SLEEP_SEC);
}
return 0;
}
Sample output (same results as Bruno Haible's original program):
bytes_allocated = 7450240 bytes_allocated = 7450368 bytes_allocated = 7450496 bytes_allocated = 7450624 bytes_allocated = 7450752 bytes_allocated = 7450880 Segmentation fault (core dumped)
The GuidToBinary routine posted by KCD should be tweaked to account for the bit layout of the timestamp in the GUID string. If the string represents a version 1 UUID, like those returned by the uuid() mysql routine, then the time components are embedded in letters 1-G, excluding the D.
12345678-9ABC-DEFG-HIJK-LMNOPQRSTUVW
12345678 = least significant 4 bytes of the timestamp in big endian order
9ABC = middle 2 timestamp bytes in big endian
D = 1 to signify a version 1 UUID
EFG = most significant 12 bits of the timestamp in big endian
When you convert to binary, the best order for indexing would be: EFG9ABC12345678D + the rest.
You don't want to swap 12345678 to 78563412 because big endian already yields the best binary index byte order. However, you do want the most significant bytes moved in front of the lower bytes. Hence, EFG go first, followed by the middle bits and lower bits. Generate a dozen or so UUIDs with uuid() over the course of a minute and you should see how this order yields the correct rank.
select uuid(), 0
union
select uuid(), sleep(.001)
union
select uuid(), sleep(.010)
union
select uuid(), sleep(.100)
union
select uuid(), sleep(1)
union
select uuid(), sleep(10)
union
select uuid(), 0;
/* output */
6eec5eb6-9755-11e4-b981-feb7b39d48d6
6eec5f10-9755-11e4-b981-feb7b39d48d6
6eec8ddc-9755-11e4-b981-feb7b39d48d6
6eee30d0-9755-11e4-b981-feb7b39d48d6
6efda038-9755-11e4-b981-feb7b39d48d6
6f9641bf-9755-11e4-b981-feb7b39d48d6
758c3e3e-9755-11e4-b981-feb7b39d48d6
The first two UUIDs were generated closest in time. They only vary in the last 3 nibbles of the first block. These are the least significant bits of the timestamp, which means we want to push them to the right when we convert this to an indexable byte array. As a counter example, the last ID is the most current, but the KCD's swapping algorithm would put it before the 3rd ID (3e before dc, last bytes from the first block).
The correct order for indexing would be:
1e497556eec5eb6...
1e497556eec5f10...
1e497556eec8ddc...
1e497556eee30d0...
1e497556efda038...
1e497556f9641bf...
1e49755758c3e3e...
See this article for supporting information: http://mysql.rjweb.org/doc.php/uuid
*** note that I don't split the version nibble from the high 12 bits of the timestamp. This is the D nibble from your example. I just throw it in front. So my binary sequence ends up being DEFG9ABC and so on. This implies that all my indexed UUIDs start with the same nibble. The article does the same thing.
I figured out this problem by:
./gradlew
cleanString::repeat
Use String::repeat
in Java 11 and later.
"A".repeat( 3 )
AAA
And the example from the Question.
int i = 3; //frequency to repeat
String someNum = "123"; // initial string
String ch = "0"; // character to append
someNum = someNum + ch.repeat(i); // formulation of the string
System.out.println(someNum); // would result in output -- "123000"
Open the file again using vi. and then press " i " or press insert key ,
For save and quit
Enter Esc
and write the following command
:wq
without save and quit
:q!
Indeed you are on the right track. You should use another thread, and you have identified the best ways to do that. The rest is just updating the progress bar. In case you don't want to use BackgroundWorker like others have suggested, there is one trick to keep in mind. The trick is that you cannot update the progress bar from the worker thread because UI can be only manipulated from the UI thread. So you use the Invoke method. It goes something like this (fix the syntax errors yourself, I'm just writing a quick example):
class MyForm: Form
{
private void delegate UpdateDelegate(int Progress);
private void UpdateProgress(int Progress)
{
if ( this.InvokeRequired )
this.Invoke((UpdateDelegate)UpdateProgress, Progress);
else
this.MyProgressBar.Progress = Progress;
}
}
The InvokeRequired
property will return true
on every thread except the one that owns the form. The Invoke
method will call the method on the UI thread, and will block until it completes. If you don't want to block, you can call BeginInvoke
instead.
Fixed-length arrays are not yet supported. What does that actually mean? Not that you can't create an array of n
many things — obviously you can just do let a = [ 1, 2, 3 ]
to get an array of three Int
s. It means simply that array size is not something that you can declare as type information.
If you want an array of nil
s, you'll first need an array of an optional type — [SKSpriteNode?]
, not [SKSpriteNode]
— if you declare a variable of non-optional type, whether it's an array or a single value, it cannot be nil
. (Also note that [SKSpriteNode?]
is different from [SKSpriteNode]?
... you want an array of optionals, not an optional array.)
Swift is very explicit by design about requiring that variables be initialized, because assumptions about the content of uninitialized references are one of the ways that programs in C (and some other languages) can become buggy. So, you need to explicitly ask for an [SKSpriteNode?]
array that contains 64 nil
s:
var sprites = [SKSpriteNode?](repeating: nil, count: 64)
This actually returns a [SKSpriteNode?]?
, though: an optional array of optional sprites. (A bit odd, since init(count:,repeatedValue:)
shouldn't be able to return nil.) To work with the array, you'll need to unwrap it. There's a few ways to do that, but in this case I'd favor optional binding syntax:
if var sprites = [SKSpriteNode?](repeating: nil, count: 64){
sprites[0] = pawnSprite
}
Yes. You can use reg.exe which comes with the OS to add, delete or query registry values. Reg.exe does not have an explicit modify command, but you can do it by doing delete and then add.
Very good answer using inheritance, just remember to override the initializer
public class Utf8StringWriter : StringWriter
{
public Utf8StringWriter(StringBuilder sb) : base (sb)
{
}
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
Within the same folder, just use the file name:
<a href="thefile.html">my link</a>
Within the parent folder's directory:
<a href="../thefile.html">my link</a>
Within a sub-directory:
<a href="subdir/thefile.html">my link</a>
Try something like this: Create the final object table, tmpFerdeen with the structure of the union.
Then
INSERT INTO tmpFerdeen (
SELECT top(100)*
FROM Customers
UNION All
SELECT top(100)*
FROM CustomerEurope
UNION All
SELECT top(100)*
FROM CustomerAsia
UNION All
SELECT top(100)*
FROM CustomerAmericas
)
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isArray(a) {
return Object.prototype.toString.call(a) === '[object Array]'
}
function isObject(a) {
return Object.prototype.toString.call(a) === '[object Object]'
}
function isEmpty(a) {
if (null == a || "" == a)return!0;
if ("number" == typeof a || "string" == typeof a)return!1;
var b = !0;
if (isArray(a)) {
if (!a.length)return!0;
for (var c = 0; c < a.length; c++)isEmpty(a[c]) || (b = !1);
return b
}
if (isObject(a)) {
for (var d in a)hasOwnProperty.call(a, d) && (isEmpty(a[d]) || (b = !1));
return b
}
return!0
}
I found another issue, for some reason if the extensions are cached in the local AppData folder, the XNA extensions never get loaded.
You need to remove the files extensionSdks.en-US.cache
and extensions.en-US.cache
from the %LocalAppData%\Microsoft\VisualStudio\11.0\Extensions
folder. These files are rebuilt the next time you launch
If you need access to the Visual Studio startup log to debug what's happening, run devenv.exe /log
command from the C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE
directory (assuming you are on a 64 bit machine). The log file generated is located here:
%AppData%\Microsoft\VisualStudio\11.0\ActivityLog.xml
An expression of non-boolean type specified in a context where a condition is expected
I also got this error when I forgot to add ON condition when specifying my join clause.
Here is a pure JavaScript solution (without jQuery)
var _Utils = function ()
{
this.findChildById = function (element, childID, isSearchInnerDescendant) // isSearchInnerDescendant <= true for search in inner childern
{
var retElement = null;
var lstChildren = isSearchInnerDescendant ? Utils.getAllDescendant(element) : element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].id == childID)
{
retElement = lstChildren[i];
break;
}
}
return retElement;
}
this.getAllDescendant = function (element, lstChildrenNodes)
{
lstChildrenNodes = lstChildrenNodes ? lstChildrenNodes : [];
var lstChildren = element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].nodeType == 1) // 1 is 'ELEMENT_NODE'
{
lstChildrenNodes.push(lstChildren[i]);
lstChildrenNodes = Utils.getAllDescendant(lstChildren[i], lstChildrenNodes);
}
}
return lstChildrenNodes;
}
}
var Utils = new _Utils;
Example of use:
var myDiv = document.createElement("div");
myDiv.innerHTML = "<table id='tableToolbar'>" +
"<tr>" +
"<td>" +
"<div id='divIdToSearch'>" +
"</div>" +
"</td>" +
"</tr>" +
"</table>";
var divToSearch = Utils.findChildById(myDiv, "divIdToSearch", true);
Just create a new MFC C++ app. It's built in, pretty easy, and thousands of examples exist in the world...
Plus, you can design your dialog box right in Visual Studio, give them variable names, and 90% of the code is generated for you.
Try this :
width:auto;
margin-right:50px;
By design, getRequestURL()
gives you the full URL, missing only the query string.
In HttpServletRequest
, you can get individual parts of the URI using the methods below:
// Example: http://myhost:8080/people?lastname=Fox&age=30
String uri = request.getScheme() + "://" + // "http" + "://
request.getServerName() + // "myhost"
":" + // ":"
request.getServerPort() + // "8080"
request.getRequestURI() + // "/people"
"?" + // "?"
request.getQueryString(); // "lastname=Fox&age=30"
.getScheme()
will give you "https"
if it was a https://domain
request..getServerName()
gives domain
on http(s)://domain
..getServerPort()
will give you the port.String uri = request.getScheme() + "://" +
request.getServerName() +
("http".equals(request.getScheme()) && request.getServerPort() == 80 || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? "" : ":" + request.getServerPort() ) +
request.getRequestURI() +
(request.getQueryString() != null ? "?" + request.getQueryString() : "");
This snippet above will get the full URI, hiding the port if the default one was used, and not adding the "?"
and the query string if the latter was not provided.
Note, that if your request passes through a proxy, you need to look at the X-Forwarded-Proto
header since the scheme might be altered:
request.getHeader("X-Forwarded-Proto")
Also, a common header is X-Forwarded-For
, which show the original request IP instead of the proxys IP.
request.getHeader("X-Forwarded-For")
If you are responsible for the configuration of the proxy/load balancer yourself, you need to ensure that these headers are set upon forwarding.
Well, you want to have an answer that is up-to-date and modern.
Here is my answer:
When I need to mail in Python, I use the mailgun API wich get's a lot of the headaches with sending mails sorted out. They have a wonderfull app/api that allows you to send 5,000 free emails per month.
Sending an email would be like this:
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
auth=("api", "YOUR_API_KEY"),
data={"from": "Excited User <mailgun@YOUR_DOMAIN_NAME>",
"to": ["[email protected]", "YOU@YOUR_DOMAIN_NAME"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
You can also track events and lots more, see the quickstart guide.
I hope you find this useful!
iostream doesn't know it's at the end of the file until it tries to read that first character past the end of the file.
The sample code at cplusplus.com says to do it like this: (But you shouldn't actually do it this way)
while (is.good()) // loop while extraction from file is possible
{
c = is.get(); // get character from file
if (is.good())
cout << c;
}
A better idiom is to move the read into the loop condition, like so:
(You can do this with all istream
read operations that return *this
, including the >>
operator)
char c;
while(is.get(c))
cout << c;
What worked for me is to first run:
gradle wrapper
After successful build I was able to run
./gradlew assembleRelease
Note: To be able run
gradle wrapper
first runbrew install gradle
. If installation successful rungradle wrapper
from project root.
Source and thanks: http://gradle.org/docs/current/userguide/gradle_wrapper.html and https://stackoverflow.com/users/745574/rage
What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties
inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx
Add the event listeners etc..
Hope this helps
Use Collections.list(iterator).stream()...
Have you tried creating a windows shortcut for sql plus and set the working directory?
select Project tab and click Build automatically so Build all option will be activated and then click on build all.and always start xml file name with lowercase.
Updated below for ES6
This MDN document describes extending classes well:
https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript
In particular, here is now they handle it:
// define the Person Class
function Person() {}
Person.prototype.walk = function(){
alert ('I am walking!');
};
Person.prototype.sayHello = function(){
alert ('hello');
};
// define the Student class
function Student() {
// Call the parent constructor
Person.call(this);
}
// inherit Person
Student.prototype = Object.create(Person.prototype);
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
// replace the sayHello method
Student.prototype.sayHello = function(){
alert('hi, I am a student');
}
// add sayGoodBye method
Student.prototype.sayGoodBye = function(){
alert('goodBye');
}
var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();
// check inheritance
alert(student1 instanceof Person); // true
alert(student1 instanceof Student); // true
Note that Object.create()
is unsupported in some older browsers, including IE8:
If you are in the position of needing to support these, the linked MDN document suggests using a polyfill, or the following approximation:
function createObject(proto) {
function ctor() { }
ctor.prototype = proto;
return new ctor();
}
Using this like Student.prototype = createObject(Person.prototype)
is preferable to using new Person()
in that it avoids calling the parent's constructor function when inheriting the prototype, and only calls the parent constructor when the inheritor's constructor is being called.
Thankfully, the JavaScript designers have heard our pleas for help and have adopted a more suitable way of approaching this issue.
MDN has another great example on ES6 class inheritance, but I'll show the exact same set of classes as above reproduced in ES6:
class Person {
sayHello() {
alert('hello');
}
walk() {
alert('I am walking!');
}
}
class Student extends Person {
sayGoodBye() {
alert('goodBye');
}
sayHello() {
alert('hi, I am a student');
}
}
var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();
// check inheritance
alert(student1 instanceof Person); // true
alert(student1 instanceof Student); // true
Clean and understandable, just like we all want. Keep in mind, that while ES6 is pretty common, it's not supported everywhere:
Firstly, add path of visual studio common tools (c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools
) into the system path. To learn how to add a path into system path, please check this website:
http://www.computerhope.com/issues/ch000549.htm. You just need to this once.
After that, whenever you need, open a command line and execute vsvars32.bat
to add all required visual studio tools' paths into the system path.
Then, you can call nmake -f makefile.mak
PS: Path of visual studio common tools might be different in your system. Please change it accordingly.
If you don't have a problem integrating a small batch application, there is this program called Cmdow.exe that will allow you to hide console windows based on console title.
Console.Title = "MyConsole";
System.Diagnostics.Process HideConsole = new System.Diagnostics.Process();
HideConsole.StartInfo.UseShellExecute = false;
HideConsole.StartInfo.Arguments = "MyConsole /hid";
HideConsole.StartInfo.FileName = "cmdow.exe";
HideConsole.Start();
Add the exe to the solution, set the build action to "Content", set Copy to Output Directory to what suits you, and cmdow will hide the console window when it is ran.
To make the console visible again, you just change the Arguments
HideConsole.StartInfo.Arguments = "MyConsole /Vis";
make the image float: left;
and the text float: right;
Take a look at this fiddle I used a picture online but you can just swap it out for your picture.
$test = "{'employees':[{'firstName':'John', 'lastName':'Doe'},{'firstName':'John', 'lastName':'Doe'}]}" ;
$test = str_replace("'", '"', $test);
echo $test;
$jtest = json_decode($test,true);
var_dump($jtest);
For arrays you can use:
Array.FindIndex<T>
:
int keyIndex = Array.FindIndex(words, w => w.IsKey);
For lists you can use List<T>.FindIndex
:
int keyIndex = words.FindIndex(w => w.IsKey);
You can also write a generic extension method that works for any Enumerable<T>
:
///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
if (items == null) throw new ArgumentNullException("items");
if (predicate == null) throw new ArgumentNullException("predicate");
int retVal = 0;
foreach (var item in items) {
if (predicate(item)) return retVal;
retVal++;
}
return -1;
}
And you can use LINQ as well:
int keyIndex = words
.Select((v, i) => new {Word = v, Index = i})
.FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;
To decode json, you have to pass the json string. Currently you're trying to pass an object:
>>> response = urlopen(url)
>>> response
<addinfourl at 2146100812 whose fp = <socket._fileobject object at 0x7fe8cc2c>>
You can fetch the data with response.read()
.
Strings, though they are not set
types, have a valuable in
property during validation in scripts:
yn = input("Are you sure you want to do this? ")
if yn in "yes":
#accepts 'y' OR 'e' OR 's' OR 'ye' OR 'es' OR 'yes'
return True
return False
I hope this helps you better understand the use of in
with this example.
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
Use to_datetime
, there is no need for a format string the parser is man/woman enough to handle it:
In [51]:
pd.to_datetime(df['I_DATE'])
Out[51]:
0 2012-03-28 14:15:00
1 2012-03-28 14:17:28
2 2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]
To access the date/day/time component use the dt
accessor:
In [54]:
df['I_DATE'].dt.date
Out[54]:
0 2012-03-28
1 2012-03-28
2 2012-03-28
dtype: object
In [56]:
df['I_DATE'].dt.time
Out[56]:
0 14:15:00
1 14:17:28
2 14:50:50
dtype: object
You can use strings to filter as an example:
In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]
Out[59]:
date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09
var x = document.getElementById("myTable").rows.length;
Well, to start with List<T>
does have the FindAll
and ConvertAll
methods - but the more idiomatic, modern approach is to use LINQ:
// Find all the people older than 30
var query1 = list.Where(person => person.Age > 30);
// Find each person's name
var query2 = list.Select(person => person.Name);
You'll need a using directive in your file to make this work:
using System.Linq;
Note that these don't use strings to express predicates and projects - they use delegates, usually created from lambda expressions as above.
If lambda expressions and LINQ are new to you, I would suggest you get a book covering LINQ first, such as LINQ in Action, Pro LINQ, C# 4 in a Nutshell or my own C# in Depth. You certainly can learn LINQ just from web tutorials, but I think it's such an important technology, it's worth taking the time to learn it thoroughly.
Make sure you XML looks like this:
<?xml version="1.0" encoding="utf-8"?>
<rootElement>
...
</rootElement>
Also, a blank XML file will return the same Root elements is missing exception. Each XML file must have a root element / node which encloses all the other elements.
xcopy "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i
Probably the problem is the space.Try with quotes.
Before you implement any of the other suggestions, ask yourself these questions...
The answers to these questions are easier in certain types of applications (Web apps, for example) than they are in others, but are worth asking anyway.
Accessing the ApplicationContext does kind of violate the whole dependency injection principle, but sometimes you've not got much choice.
It's not a big issue but beginner level developers as like me, we things what kind of error is this and finally we weast huge time for solve it.
Actually if you delete the db and create the db once again and after try to create the collection then it's will be work properly.
? mongo
use dbName;
db.dropDatabase();
exit
Windows default install location for Webstorm:
C:\Program Files\JetBrains\WebStorm 2019.1.3\bin\idea.properties
I went x4 default for intellisense
and x5 for file size
(my business workstation is a beast though: 8th gen i7, 32Gb RAM, NVMe PCIE3.0x4 SDD, gloat, etc, gloat, etc)
#---------------------------------------------------------------------
# Maximum file size (kilobytes) IDE should provide code assistance for.
# The larger file is the slower its editor works and higher overall system memory requirements are
# if code assistance is enabled. Remove this property or set to very large number if you need
# code assistance for any files available regardless their size.
#---------------------------------------------------------------------
idea.max.intellisense.filesize=10000
#---------------------------------------------------------------------
# Maximum file size (kilobytes) IDE is able to open.
#---------------------------------------------------------------------
idea.max.content.load.filesize=100000
Yet another SQLite wrapper for Swift 2 and Swift 3: http://github.com/groue/GRDB.swift
Features:
An API that will look familiar to users of ccgus/fmdb
A low-level SQLite API that leverages the Swift standard library
A pretty Swift query interface for SQL-allergic developers
Support for the SQLite WAL mode, and concurrent database access for extra performance
A Record class that wraps result sets, eats your custom SQL queries for breakfast, and provides basic CRUD operations
Swift type freedom: pick the right Swift type that fits your data. Use Int64 when needed, or stick with the convenient Int. Store and read NSDate or NSDateComponents. Declare Swift enums for discrete data types. Define your own database-convertible types.
Database Migrations
(UPDATED with examples for Bootstrap v4, v3 and v3)
Examples of forms with validation classes for the past few major versions of Bootstrap.
Bootstrap v4
See the live version on codepen
<div class="container">
<form>
<div class="form-group row">
<label for="inputEmail" class="col-sm-2 col-form-label text-success">Email</label>
<div class="col-sm-7">
<input type="email" class="form-control is-valid" id="inputEmail" placeholder="Email">
</div>
</div>
<div class="form-group row">
<label for="inputPassword" class="col-sm-2 col-form-label text-danger">Password</label>
<div class="col-sm-7">
<input type="password" class="form-control is-invalid" id="inputPassword" placeholder="Password">
</div>
<div class="col-sm-3">
<small id="passwordHelp" class="text-danger">
Must be 8-20 characters long.
</small>
</div>
</div>
</form>
</div>
Bootstrap v3
See the live version on codepen
<form role="form">
<div class="form-group has-warning">
<label class="control-label" for="inputWarning">Input with warning</label>
<input type="text" class="form-control" id="inputWarning">
<span class="help-block">Something may have gone wrong</span>
</div>
<div class="form-group has-error">
<label class="control-label" for="inputError">Input with error</label>
<input type="text" class="form-control" id="inputError">
<span class="help-block">Please correct the error</span>
</div>
<div class="form-group has-info">
<label class="control-label" for="inputError">Input with info</label>
<input type="text" class="form-control" id="inputError">
<span class="help-block">Username is taken</span>
</div>
<div class="form-group has-success">
<label class="control-label" for="inputSuccess">Input with success</label>
<input type="text" class="form-control" id="inputSuccess" />
<span class="help-block">Woohoo!</span>
</div>
</form>
Bootstrap v2
See the live version on jsfiddle
The .error
, .success
, .warning
and .info
classes are appended to the .control-group
. This is standard Bootstrap markup and styling in v2. Just follow that and you're in good shape. Of course you can go beyond with your own styles to add a popup or "inline flash" if you prefer, but if you follow Bootstrap convention and hang those validation classes on the .control-group
it will stay consistent and easy to manage (at least since you'll continue to have the benefit of Bootstrap docs and examples)
<form class="form-horizontal">
<div class="control-group warning">
<label class="control-label" for="inputWarning">Input with warning</label>
<div class="controls">
<input type="text" id="inputWarning">
<span class="help-inline">Something may have gone wrong</span>
</div>
</div>
<div class="control-group error">
<label class="control-label" for="inputError">Input with error</label>
<div class="controls">
<input type="text" id="inputError">
<span class="help-inline">Please correct the error</span>
</div>
</div>
<div class="control-group info">
<label class="control-label" for="inputInfo">Input with info</label>
<div class="controls">
<input type="text" id="inputInfo">
<span class="help-inline">Username is taken</span>
</div>
</div>
<div class="control-group success">
<label class="control-label" for="inputSuccess">Input with success</label>
<div class="controls">
<input type="text" id="inputSuccess">
<span class="help-inline">Woohoo!</span>
</div>
</div>
</form>
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
The following class definition gives a simple method to convert an input XML string into formatted output XML with the xml declaration as UTF-8. It supports all the configuration options that the XmlWriterSettings class offers.
using System;
using System.Text;
using System.Xml;
using System.IO;
namespace CJBS.Demo
{
/// <summary>
/// Supports formatting for XML in a format that is easily human-readable.
/// </summary>
public static class PrettyXmlFormatter
{
/// <summary>
/// Generates formatted UTF-8 XML for the content in the <paramref name="doc"/>
/// </summary>
/// <param name="doc">XmlDocument for which content will be returned as a formatted string</param>
/// <returns>Formatted (indented) XML string</returns>
public static string GetPrettyXml(XmlDocument doc)
{
// Configure how XML is to be formatted
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true
, IndentChars = " "
, NewLineChars = System.Environment.NewLine
, NewLineHandling = NewLineHandling.Replace
//,NewLineOnAttributes = true
//,OmitXmlDeclaration = false
};
// Use wrapper class that supports UTF-8 encoding
StringWriterWithEncoding sw = new StringWriterWithEncoding(Encoding.UTF8);
// Output formatted XML to StringWriter
using (XmlWriter writer = XmlWriter.Create(sw, settings))
{
doc.Save(writer);
}
// Get formatted text from writer
return sw.ToString();
}
/// <summary>
/// Wrapper class around <see cref="StringWriter"/> that supports encoding.
/// Attribution: http://stackoverflow.com/a/427737/3063884
/// </summary>
private sealed class StringWriterWithEncoding : StringWriter
{
private readonly Encoding encoding;
/// <summary>
/// Creates a new <see cref="PrettyXmlFormatter"/> with the specified encoding
/// </summary>
/// <param name="encoding"></param>
public StringWriterWithEncoding(Encoding encoding)
{
this.encoding = encoding;
}
/// <summary>
/// Encoding to use when dealing with text
/// </summary>
public override Encoding Encoding
{
get { return encoding; }
}
}
}
}
Possibilities for further improvement:-
GetPrettyXml(XmlDocument doc, XmlWriterSettings settings)
could be created that allows the caller to customize the output.GetPrettyXml(String rawXml)
could be added that supports parsing raw text, rather than have the client use the XmlDocument. In my case, I needed to manipulate the XML using the XmlDocument, hence I didn't add this.Usage:
String myFormattedXml = null;
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(myRawXmlString);
myFormattedXml = PrettyXmlFormatter.GetPrettyXml(doc);
}
catch(XmlException ex)
{
// Failed to parse XML -- use original XML as formatted XML
myFormattedXml = myRawXmlString;
}
try
{
string AppPath = "\\\\spri11U1118\\SampleBatch\\Bin\\";
string strFilePath = AppPath + "ABCED120D_XXX.bat";
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = strFilePath;
string pwd = "s44erver";
proc.StartInfo.Domain = "abcd";
proc.StartInfo.UserName = "sysfaomyulm";
System.Security.SecureString secret = new System.Security.SecureString();
foreach (char c in pwd)
secret.AppendChar(c);
proc.StartInfo.Password = secret;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WorkingDirectory = "psexec \\\\spri11U1118\\SampleBatch\\Bin ";
proc.Start();
while (!proc.HasExited)
{
proc.Refresh();
// Thread.Sleep(1000);
}
proc.Close();
}
catch (Exception ex)
{
throw ex;
}
If you're using WordPress, there is now a filter hook to resolve this:
remove_filter('template_redirect', 'redirect_canonical');
(Put this in your theme's functions.php
)
This tells WordPress to not redirect index.php
back to the root page, but to sit where it is. That way, index.html
can be assigned to be the default page in .htaccess
and can work alongside index.php
.
I don't know if this is still actual for you, but I still leave my comment so maybe it will help somebody else. I had same issue, and the solution proposed by @dighan on bountysource.com/issues/ solved it for me.
So here is the code that solved my problem:
var media = document.getElementById("YourVideo");
const playPromise = media.play();
if (playPromise !== null){
playPromise.catch(() => { media.play(); })
}
It still throws an error into console, but at least the video is playing :)
after that all html we want to write these lines of code
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css" type="text/css" media="all">
<script>
$('#date').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
yearRange: "-100:+0",
dateFormat: 'dd/mm/yy'
});
</script>
You say you "really just want B", but this is false. You want B, but you also want an updated A if there have been any changes to it ("active development").
So, sometimes you want to work with A, B, and C. For this case you have aggregator project P. For the case where you want to work with A and B (but do not want C), you should create aggregator project Q.
Edit 2016: The above information was perhaps relevant in 2009. As of 2016, I highly recommend ignoring this in most cases, and simply using the -am
or -pl
command-line flags as described in the accepted answer. If you're using a version of maven from before v2.1, change that first :)
Here is a DB2 Stored Procidure that receive a parameter
CREATE PROCEDURE getStateByName (IN StateName VARCHAR(128))
DYNAMIC RESULT SETS 1
P1: BEGIN
-- Declare cursor
DECLARE State_Cursor CURSOR WITH RETURN for
-- #######################################################################
-- # Replace the SQL statement with your statement.
-- # Note: Be sure to end statements with the terminator character (usually ';')
-- #
-- # The example SQL statement SELECT NAME FROM SYSIBM.SYSTABLES
-- # returns all names from SYSIBM.SYSTABLES.
-- ######################################################################
SELECT * FROM COUNTRY.STATE
WHERE PROVINCE_NAME LIKE UPPER(stateName);
-- Cursor left open for client application
OPEN Province_Cursor;
END P1
//Country is a db2 scheme
//Now here is a java Entity bean Method
public List<Province> getStateByName(String stateName) throws Exception {
EntityManager em = this.em;
List<State> states= null;
try {
Query query = em.createNativeQuery("call NGB.getStateByName(?1)", Province.class);
query.setParameter(1, provinceName);
states= (List<Province>) query.getResultList();
} catch (Exception ex) {
throw ex;
}
return states;
}
Java also does not use line numbers, which is a necessity for a GOTO function. Unlike C/C++, Java does not have goto statement, but java supports label. The only place where a label is useful in Java is right before nested loop statements. We can specify label name with break to break out a specific outer loop.
You can use toFixed() to do that
var twoPlacedFloat = parseFloat(yourString).toFixed(2)