Had similar issue but with .swiftdoc files.
I have extensions and unit test targets in project. And they had same "Product Module Name" (PRODUCT_MODULE_NAME in Build Settings) as application. After making names unique issue gone.
Basing on this answer if you need history object only in order to navigate to other component:
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
C++ programs are translated to assembly programs during the generation of machine code from the source code. It would be virtually wrong to say assembly is slower than C++. Moreover, the binary code generated differs from compiler to compiler. So a smart C++ compiler may produce binary code more optimal and efficient than a dumb assembler's code.
However I believe your profiling methodology has certain flaws. The following are general guidelines for profiling:
I had similar problem.
Function that return all element which include text from arg.
This works for me:
function getElementsByText(document, str, tag = '*') {
return [...document.querySelectorAll(tag)]
.filter(
el => (el.text && el.text.includes(str))
|| (el.children.length === 0 && el.outerText && el.outerText.includes(str)))
}
It's a terrible practice to give away access to the entire s3 (all actions, all buckets), just to unblock yourself.
The 403 error above is usually due to the lack of "Read" permission of files. The Read action for reading a file in S3 is s3:GetObject
.
{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": [
"arn:aws:s3:::mybucketname/path/*",
"arn:aws:s3:::mybucketname"
]
}
You can create a Policy (e.g. MY_S3_READER
) with the following, and attach it to the user or role that's doing the job. (e.g. EC2 Instance's IAM role)
Here is the exact JSON for your Policy: (just replace mybucketname
and path
)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": [
"arn:aws:s3:::mybucketname/path/*",
"arn:aws:s3:::mybucketname"
]
}
]
}
Create this Policy. Then, go to IAM > Roles > Attach Policy and attach it.
Go to your bucket in S3, then add the following example: (replace mybucketname
and myip
)
{
"Version": "2012-10-17",
"Id": "SourceIP",
"Statement": [
{
"Sid": "ValidIpAllowRead",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": [
"arn:aws:s3:::mybucketname",
"arn:aws:s3:::mybucketname/*"
],
"Condition": {
"IpAddress": {
"aws:SourceIp": "myip/32"
}
}
}
]
}
If you want to change this read permission to by User or Role (instead of IP Address), remove the Condition
part, and change "Principal" to "Principal": { "AWS": "<IAM User/Role's ARN>" },
".
Check the permissions via aws s3 cp
or aws s3 ls
manually for faster debugging.
It sometimes takes up to 30 seconds for the permission change to be effective. Be patient.
Note that for doing "ls
" (e.g. aws s3 ls s3://mybucket/mypath
) you need s3:ListBucket
access.
IMPORTANT Accessing files by their HTTP(S) URL via cURL
or similar tools (e.g. axios
on AJAX calls) requires you to grant either IP access, or supply proper headers, manually, or get a signedUrl from the SDK first.
Yes just add the setters/getters with public modifier ;)
If you don't have access to php.ini, adding this code (after your $ch = curl_init();
line) works for me:
$certificate_location = "C:\Program Files (x86)\EasyPHP-Devserver-16.1\ca-bundle.crt"; // modify this line accordingly (may need to be absolute)
curl_setopt($ch, CURLOPT_CAINFO, $certificate_location);
curl_setopt($ch, CURLOPT_CAPATH, $certificate_location);
Then, you will just need to download ca-bundle.crt and save it to location you specified in $certificate_location
.
Follow bolnad answer up to Step 4.
Then make it simpler by replacing all the other steps with:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// Configure your cell
sizingNibNew.configureCell(data as! CustomCellData, delegate: self)
// We use the full width minus insets
let width = collectionView.frame.size.width - collectionView.sectionInset.left - collectionView.sectionInset.right
// Constrain our cell to this width
let height = sizingNibNew.systemLayoutSizeFitting(CGSize(width: width, height: .infinity), withHorizontalFittingPriority: UILayoutPriorityRequired, verticalFittingPriority: UILayoutPriorityFittingSizeLevel).height
return CGSize(width: width, height: height)
}
I read the comments about contacts app and how it use a theme for each contact.
Probably, contacts app has some predefine themes (for each material primary color from here: http://www.google.com/design/spec/style/color.html).
You can apply a theme before a the setContentView method inside onCreate method.
Then the contacts app can apply a theme randomly to each user.
This method is:
setTheme(R.style.MyRandomTheme);
But this method has a problem, for example it can change the toolbar color, the scroll effect color, the ripple color, etc, but it cant change the status bar color and the navigation bar color (if you want to change it too).
Then for solve this problem, you can use the method before and:
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setNavigationBarColor(getResources().getColor(R.color.md_red_500));
getWindow().setStatusBarColor(getResources().getColor(R.color.md_red_700));
}
This two method change the navigation and status bar color. Remember, if you set your navigation bar translucent, you can't change its color.
This should be the final code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.MyRandomTheme);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setNavigationBarColor(getResources().getColor(R.color.myrandomcolor1));
getWindow().setStatusBarColor(getResources().getColor(R.color.myrandomcolor2));
}
setContentView(R.layout.activity_main);
}
You can use a switch and generate random number to use random themes, or, like in contacts app, each contact probably has a predefine number associated.
A sample of theme:
<style name="MyRandomTheme" parent="Theme.AppCompat.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/myrandomcolor1</item>
<item name="colorPrimaryDark">@color/myrandomcolor2</item>
<item name="android:navigationBarColor">@color/myrandomcolor1</item>
</style>
Sorry for my english.
I would use:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
let touch : UITouch = touches.anyObject() as UITouch
if let touchView = touch.view as? UIPickerView
{
}
}
If you want to find how many processors (or CPUs) a machine has the same way %NUMBER_OF_PROCESSORS%
shows you the number of cores, save the following script in a batch file, for example, GetNumberOfCores.cmd
:
@echo off
for /f "tokens=*" %%f in ('wmic cpu get NumberOfCores /value ^| find "="') do set %%f
And then execute like this:
GetNumberOfCores.cmd
echo %NumberOfCores%
The script will set a environment variable named %NumberOfCores%
and it will contain the number of processors.
Use <div id="rectangle" style="width:number px; height:number px; background-color:blue"></div>
This will create a blue rectangle.
Replace
dateTime.setText(app.getTotalDl());
With
dateTime.setText(""+app.getTotalDl());
You are trying to call DeckOfCards::shuffle
with a deckOfCards
parameter:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck
But the method takes a vector<Card>&
:
void deckOfCards::shuffle(vector<Card>& deck)
The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.
Error:
[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'
Paraphrased:
Hey, pal. You're trying to call a function called
shuffle
which apparently takes a single parameter of type reference-to-deckOfCards
, but there is no such function.
Error:
[Note] candidate is:
In file included from main.cpp
[Note] void deckOfCards::shuffle(std::vector&)
Paraphrased:
I mean, maybe you meant this other function called
shuffle
, but that one takes a reference-tovector<something>
.
Error:
[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'
Which I'd be happy to call if I knew how to convert from a
deckOfCards
to avector
; but I don't. So I won't.
Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.
function myFunction() {_x000D_
var selchbox = [];_x000D_
var inputfields = document.getElementsByName("myCheck");_x000D_
var ar_inputflds = inputfields.length;_x000D_
_x000D_
for (var i = 0; i < ar_inputflds; i++) {_x000D_
if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
selchbox.push(inputfields[i].value);_x000D_
}_x000D_
return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
var selchb = myFunction();_x000D_
console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
You can also encode bytes to Base64. How to get this from a stream see here: How to convert an Stream into a byte[] in C#?
Or I think it should be also possible to use the .ToString() method and encode this.
You may use two options:
Create Element is the fastest way (check here.):
$(document.createElement('table'));
InnerHTML is another popular approach:
$("#foo").append("<div>hello world</div>"); // Check similar for table too.
Check a real example on How to create a new table with rows using jQuery and wrap it inside div.
There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.
Check Dynamic creation of table with DOM
IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:
function createProviderFormFields(id, labelText, tooltip, regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}
/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
int result = 0;
Iterator<Row> rowIterator = xssfSheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<Cell> cells = new ArrayList<>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cells.add(cellIterator.next());
}
for (int i = cells.size(); i >= 0; i--) {
Cell cell = cells.get(i-1);
if (cell.toString().trim().isEmpty()) {
cells.remove(i-1);
} else {
result = cells.size() > result ? cells.size() : result;
break;
}
}
}
return result;
}
This two classes are borrowed from the HTML Boilerplate main.css. Although the invisible checkbox will be focused and not the label.
/*
* Hide only visually, but have it available for screenreaders: h5bp.com/v
*/
.visuallyhidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
/*
* Extends the .visuallyhidden class to allow the element to be focusable
* when navigated to via the keyboard: h5bp.com/p
*/
.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
clip: auto;
height: auto;
margin: 0;
overflow: visible;
position: static;
width: auto;
}
Android Studio now comes bundled with OpenJDK 8 . Legacy projects can still use JDK7 or JDK8
Reference: https://developer.android.com/studio/releases/index.html
You will have to use the fluent API to do this.
Try adding the following to your DbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(a => a.UserDetail)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
try this
single function for all radio have class "radio-button"
work in chrome and FF
$('.radio-button').on("click", function(event){_x000D_
$('.radio-button').prop('checked', false);_x000D_
$(this).prop('checked', true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
qImageView.setImageResource(R.drawable.img2);
I think this will help you
All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :
protected void bLoanButton_Click(object sender, EventArgs e)
{
//your same code
........
GridView1.DataBind();
}
regards
There is something wrong with your design. Try to make your classes represent real world things. For example:
Please change only the name of the function; no other change is required
<script>
function totalbandwidthresult() {
alert("fdf");
var fps = Number(document.calculator.fps.value);
var bitrate = Number(document.calculator.bitrate.value);
var numberofcameras = Number(document.calculator.numberofcameras.value);
var encoding = document.calculator.encoding.value;
if (encoding = "mjpeg") {
storage = bitrate * fps;
} else {
storage = bitrate;
}
totalbandwidth = (numberofcameras * storage) / 1000;
alert(totalbandwidth);
document.calculator.totalbandwidthresult.value = totalbandwidth;
}
</script>
<form name="calculator" class="formtable">
<div class="formrow">
<label for="rcname">RC Name</label>
<input type="text" name="rcname">
</div>
<div class="formrow">
<label for="fps">FPS</label>
<input type="text" name="fps">
</div>
<div class="formrow">
<label for="bitrate">Bitrate</label>
<input type="text" name="bitrate">
</div>
<div class="formrow">
<label for="numberofcameras">Number of Cameras</label>
<input type="text" name="numberofcameras">
</div>
<div class="formrow">
<label for="encoding">Encoding</label>
<select name="encoding" id="encodingoptions">
<option value="h264">H.264</option>
<option value="mjpeg">MJPEG</option>
<option value="mpeg4">MPEG4</option>
</select>
</div>Total Storage:
<input type="text" name="totalstorage">Total Bandwidth:
<input type="text" name="totalbandwidth">
<input type="button" value="totalbandwidthresult" onclick="totalbandwidthresult();">
</form>
Create a UNIQUE
constraint on your subs_email
column, if one does not already exist:
ALTER TABLE subs ADD UNIQUE (subs_email)
Use INSERT ... ON DUPLICATE KEY UPDATE
:
INSERT INTO subs
(subs_name, subs_email, subs_birthday)
VALUES
(?, ?, ?)
ON DUPLICATE KEY UPDATE
subs_name = VALUES(subs_name),
subs_birthday = VALUES(subs_birthday)
You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com
Add in pom.xml:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>4.0.0.RC2</version>
</dependency>
and use org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors
for authorization request.
See the sample usage at https://github.com/rwinch/spring-security-test-blog
(https://jira.spring.io/browse/SEC-2592).
Update:
4.0.0.RC2 works for spring-security 3.x. For spring-security 4 spring-security-test become part of spring-security (http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test, version is the same).
Setting Up is changed: http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test-mockmvc
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
Sample for basic-authentication: http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#testing-http-basic-authentication.
I believe, this arrow exists because of your IDE. IntelliJ IDEA does such thing with some code. This is called code folding. You can click at the arrow to expand it.
$endOfCycle = date("Y-m", mktime(0, 0, 0, date("m", time())+1 , 15, date("m", time())));
UPDATE
In Android Studio AVD:
I prefer using Hamcrest because it gives much better output in case of a failure
Assert.assertThat(listUnderTest,
IsIterableContainingInOrder.contains(expectedList.toArray()));
Instead of reporting
expected true, got false
it will report
expected List containing "1, 2, 3, ..." got list containing "4, 6, 2, ..."
IsIterableContainingInOrder.contain
According to the Javadoc:
Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items
So the listUnderTest
must have the same number of elements and each element must match the expected values in order.
ColumnNames
is a property of type List<String>
so when you are setting up you need to pass a List<String>
in the Returns
call as an argument (or a func which return a List<String>
)
But with this line you are trying to return just a string
input.SetupGet(x => x.ColumnNames).Returns(temp[0]);
which is causing the exception.
Change it to return whole list:
input.SetupGet(x => x.ColumnNames).Returns(temp);
Use positive lookahead assertions:
var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;
Without it, your current regex only matches that you have 6 to 16 valid characters, it doesn't validate that it has at least a number, and at least a special character. That's what the lookahead above is for.
(?=.*[0-9])
- Assert a string has at least one number;(?=.*[!@#$%^&*])
- Assert a string has at least one special character.TL:DR version:
//Objective-C
[self.picker selectRow:2 inComponent:0 animated:YES];
//Swift
picker.selectRow(2, inComponent:0, animated:true)
Either you didn't set your picker to select the row (which you say you seem to have done but anyhow):
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated
OR you didn't use the the following method to get the selected item from your picker
- (NSInteger)selectedRowInComponent:(NSInteger)component
This will get the selected row as Integer from your picker and do as you please with it. This should do the trick for yah. Good luck.
Anyhow read the ref: https://developer.apple.com/documentation/uikit/uipickerview
EDIT:
An example of manually setting and getting of a selected row in a UIPickerView:
the .h file:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
{
UIPickerView *picker;
NSMutableArray *source;
}
@property (nonatomic,retain) UIPickerView *picker;
@property (nonatomic,retain) NSMutableArray *source;
-(void)pressed;
@end
the .m file:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize picker;
@synthesize source;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.view.backgroundColor = [UIColor yellowColor];
self.source = [[NSMutableArray alloc] initWithObjects:@"EU", @"USA", @"ASIA", nil];
UIButton *pressme = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 280, 80)];
[pressme setTitle:@"Press me!!!" forState:UIControlStateNormal];
pressme.backgroundColor = [UIColor lightGrayColor];
[pressme addTarget:self action:@selector(pressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:pressme];
self.picker = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 110, 280, 300)];
self.picker.delegate = self;
self.picker.dataSource = self;
[self.view addSubview:self.picker];
//This is how you manually SET(!!) a selection!
[self.picker selectRow:2 inComponent:0 animated:YES];
}
//logs the current selection of the picker manually
-(void)pressed
{
//This is how you manually GET(!!) a selection
int row = [self.picker selectedRowInComponent:0];
NSLog(@"%@", [source objectAtIndex:row]);
}
- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
return [source count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
return [source objectAtIndex:row];
}
#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
// NSLog(@"%@", [source objectAtIndex:row]);
}
@end
EDIT for Swift solution (Source: Dan Beaulieu's answer)
Define an Outlet:
@IBOutlet weak var pickerView: UIPickerView! // for example
Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:
pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)
If you inspect the Swift 2.0 framework you'll see .selectRow defined as:
func selectRow(row: Int, inComponent component: Int, animated: Bool)
option clicking .selectRow in Xcode displays the following:
This is my approach:
String[] columnNames = {"id", "Nome", "Sobrenome","Email"};
List<Student> students = _repo.getAll();
Object[][] data = new Object[students.size()][4];
int index = 0;
for(Student s : students) {
data[index][0] = s.getId();
data[index][1] = s.getFirstName();
data[index][2] = s.getLastName();
data[index][3] = s.getEmail();
index++;
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
My problem has gone after I added this:
<system.webServer>
<security>
<requestFiltering>
<requestLimits
maxAllowedContentLength="104857600"
/>
</requestFiltering>
</security>
</system.webServer>
I found the answer here:
https://web.archive.org/web/20160421163524/http://vijayt.com/Post/Set-RadioButton-value-using-jQuery
Basically, if you want to check one radio button, you MUST pass the value as an array:
$('input:radio[name=cols]').val(['Site']);
$('input:radio[name=rows]').val(['Site']);
Did you import the packages for the file reading stuff.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
also here
cfiltering(numberOfUsers, numberOfMovies);
Are you trying to create an object or calling a method?
also another thing:
user_movie_matrix[userNo][movieNo]=rating;
you are assigning a value to a member of an instance as if it was a static variable
also remove the Th
in
private int user_movie_matrix[][];Th
Hope this helps.
You can have the return type to be a superclass of the three classes (either defined by you or just use object
). Then you can return any one of those objects, but you will need to cast it back to the correct type when getting the result. Like:
public object GetAnything()
{
Hello hello = new Hello();
Computer computer = new Computer();
Radio radio = new Radio();
return radio; or return computer; or return hello //should be possible?!
}
Then:
Hello hello = (Hello)getAnything();
For your iphone You could use in your head balise :
"width=device-width"
Whatever changes you would make in function will persist.So there is no need to return anything.You can pass 2d array and change it whenever you will like.
void MakeGridOfCounts(int Grid[][6])
{
cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
}
or
void MakeGridOfCounts(int Grid[][6],int answerArray[][6])
{
....//do the changes in the array as you like they will reflect in main...
}
Few things:
Why are your use-permissions and use-features tags in your activity tag. Generally, permissions are included as direct children of your <manifest>
tag. This could be part of the problem.
According to the android camera open documentation, a runtime exception is thrown:
if connection to the camera service fails (for example, if the camera is in use by another process or device policy manager has disabled the camera)
Have you tried checking if the camera is being used by something else or if your policy manager has some setting where the camera is turned off?
Don't forget the <uses-feature android:name="android.hardware.camera.autofocus" />
for autofocus.
While I'm not sure if any of these will directly help you, I think they're worth investigating if for no other reason than to simply rule out. Due diligence if you will.
EDIT
As mentioned in the comments below, the solution was to move the uses-permissions
up to above the application tag.
This is an old question, but I think will worth it to share how to create an arrow using this triangle technique.
Lets create 2 triangles, for the second one we will use the :after
pseudo class and position it just below the other:
.arrow{
width: 0;
height: 0;
border-radius: 50px;
display: inline-block;
position: relative;
}
.arrow:after{
content: "";
width: 0;
height: 0;
position: absolute;
}
.arrow-up{
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid #333;
}
.arrow-up:after{
top: 5px;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid #ccc;
right: -50px;
}
_x000D_
<div class="arrow arrow-up"> </div>
_x000D_
Now we just have to set the predominant border color of the second triangle to the same color of the background:
.arrow{
width: 0;
height: 0;
border-radius: 50px;
display: inline-block;
position: relative;
}
.arrow:after{
content: "";
width: 0;
height: 0;
position: absolute;
}
.arrow-up{
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid #333;
}
.arrow-up:after{
top: 5px;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid #fff;
right: -50px;
}
_x000D_
<div class="arrow arrow-up"> </div>
_x000D_
Fiddle with all the arrows:
http://jsfiddle.net/tomsarduy/r0zksgeu/
With jquery you could do to sth. like this, which will simply switch classes.
$('.showhide').click(function() {
$(this).removeClass('myclass');
$(this).addClass('showhidenew');
});
If you want to switch classes back and forth on each click, you can use toggleClass, like so:
$('.showhide').click(function() {
$(this).toggleClass('myclass');
$(this).toggleClass('showhidenew');
});
// Create a Employee table
create table employee(
id number(10),
name varchar2(100),
salary number(10)
);
======================================================================= //Employee.java
public class Employee {
private int id;
private String name;
private float salary;
//no-arg and parameterized constructors
public Employee(){};
public Employee(int id, String name, float salary){
this.id=id;
this.name=name;
this.salary=salary;
}
//getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String toString(){
return id+" "+name+" "+salary;
}
}
========================================================================= //EmployeeDao.java
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
private NamedParameterJdbcTemplate nameTemplate;
public void setnameTemplate(NamedParameterJdbcTemplate template) {
this.nameTemplate = template;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// BY using JdbcTemplate
public int saveEmployee(Employee e){
int id = e.getId();
String name = e.getName();
float salary = e.getSalary();
Object p[] = {id, name, salary};
String query="insert into employee values(?,?,?)";
return jdbcTemplate.update(query, p);
/*String query="insert into employee values('"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";
return jdbcTemplate.update(query);
*/
}
//By using NameParameterTemplate
public void insertEmploye(Employee e) {
String query="insert into employee values (:id,:name,:salary)";
Map<String,Object> map=new HashMap<String,Object>();
map.put("id",e.getId());
map.put("name",e.getName());
map.put("salary",e.getSalary());
nameTemplate.execute(query,map,new MyPreparedStatement());
}
// Updating Employee
public int updateEmployee(Employee e){
String query="update employee set name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";
return jdbcTemplate.update(query);
}
// Deleting a Employee row
public int deleteEmployee(Employee e){
String query="delete from employee where id='"+e.getId()+"' ";
return jdbcTemplate.update(query);
}
//Selecting Single row with condition and also all rows
public int selectEmployee(Employee e){
//String query="select * from employee where id='"+e.getId()+"' ";
String query="select * from employee";
List<Map<String, Object>> rows = jdbcTemplate.queryForList(query);
for(Map<String, Object> row : rows){
String id = row.get("id").toString();
String name = (String)row.get("name");
String salary = row.get("salary").toString();
System.out.println(id + " " + name + " " + salary );
}
return 1;
}
// Can use MyrowMapper class an implementation class for RowMapper interface
public void getAllEmployee()
{
String query="select * from employee";
List<Employee> l = jdbcTemplate.query(query, new MyrowMapper());
Iterator it=l.iterator();
while(it.hasNext())
{
Employee e=(Employee)it.next();
System.out.println(e.getId()+" "+e.getName()+" "+e.getSalary());
}
}
//Can use directly a RowMapper implementation class without an object creation
public List<Employee> getAllEmployee1(){
return jdbcTemplate.query("select * from employee",new RowMapper<Employee>(){
@Override
public Employee mapRow(ResultSet rs, int rownumber) throws SQLException {
Employee e=new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
return e;
}
});
}
// End of all the function
}
================================================================ //MyrowMapper.java
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class MyrowMapper implements RowMapper<Employee> {
@Override
public Employee mapRow(ResultSet rs, int rownumber) throws SQLException
{
System.out.println("mapRow()====:"+rownumber);
Employee e=new Employee();
e.setId(rs.getInt("id"));
e.setName(rs.getString("name"));
e.setSalary(rs.getFloat("salary"));
return e;
}
}
========================================================== //MyPreparedStatement.java
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;
public class MyPreparedStatement implements PreparedStatementCallback<Object> {
@Override
public Object doInPreparedStatement(PreparedStatement ps)
throws SQLException, DataAccessException {
return ps.executeUpdate();
}
}
===================================================================== //Test.java
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
// By calling constructor for insert
/*
int status=dao.saveEmployee(new Employee(103,"Ajay",35000));
System.out.println(status);
*/
// By calling PreparedStatement
dao.insertEmploye(new Employee(103,"Roh",25000));
// By calling setter-getter for update
/*
Employee e=new Employee();
e.setId(102);
e.setName("Rohit");
e.setSalary(8000000);
int status=dao.updateEmployee(e);
*/
// By calling constructor for update
/*
int status=dao.updateEmployee(new Employee(102,"Sadhan",15000));
System.out.println(status);
*/
// Deleting a record
/*
Employee e=new Employee();
e.setId(102);
int status=dao.deleteEmployee(e);
System.out.println(status);
*/
// Selecting single or all rows
/*
Employee e=new Employee();
e.setId(102);
int status=dao.selectEmployee(e);
System.out.println(status);
*/
// Can use MyrowMapper class an implementation class for RowMapper interface
dao.getAllEmployee();
// Can use directly a RowMapper implementation class without an object creation
/*
List<Employee> list=dao.getAllEmployee1();
for(Employee e1:list)
System.out.println(e1);
*/
}
}
================================================================== //applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="hr" />
<property name="password" value="hr" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="nameTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="ds"></constructor-arg>
</bean>
<bean id="edao" class="EmployeeDao">
<!-- Can use both -->
<property name="nameTemplate" ref="nameTemplate"></property>
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
===================================================================
If the excel file is password protected, then this error comes up.
Let's begin with D of SOLID and look at DI and IoC from Scott Millett's book "Professional ASP.NET Design Patterns":
Dependency Inversion Principle (DIP)
The DIP is all about isolating your classes from concrete implementations and having them depend on abstract classes or interfaces. It promotes the mantra of coding to an interface rather than an implementation, which increases flexibility within a system by ensuring you are not tightly coupled to one implementation.
Dependency Injection (DI) and Inversion of Control (IoC)
Closely linked to the DIP are the DI principle and the IoC principle. DI is the act of supplying a low level or dependent class via a constructor, method, or property. Used in conjunction with DI, these dependent classes can be inverted to interfaces or abstract classes that will lead to loosely coupled systems that are highly testable and easy to change.
In IoC, a system’s flow of control is inverted compared to procedural programming. An example of this is an IoC container, whose purpose is to inject services into client code without having the client code specifying the concrete implementation. The control in this instance that is being inverted is the act of the client obtaining the service.
Millett,C (2010). Professional ASP.NET Design Patterns. Wiley Publishing. 7-8.
One function can do the job,
void free_list(node *pHead)
{
node *pNode = pHead, *pNext;
while (NULL != pNode)
{
pNext = pNode->next;
free(pNode);
pNode = pNext;
}
}
The following worked for me.
var temp = ctx.Set<DbTable>()
.GroupBy(g => new { g.id })
.ToDictionary(d => d.Key.id);
This didn't work
=IIf((CountRows("ScannerStatisticsData") = 0),False,True)
but this did and I can't really explain why
=IIf((CountRows("ScannerStatisticsData") < 1),False,True)
guess SSRS doesn't like equal comparisons as much as less than.
It can be done this way as well
foreach (Company company in listofCompany.Where(d => d.Id = 1)).ToList())
{
//do your stuff here
company.Id= 2;
company.Name= "Sample"
}
Remember this if all your Strings in the column do not have an underscore (...or else if null value will be the output):
SELECT COALESCE
(SUBSTR("STRING_COLUMN" , 0, INSTR("STRING_COLUMN", '_')-1),
"STRING_COLUMN")
AS OUTPUT FROM DUAL
This looks like one case where it is better to use setAttribute:
Dev.Opera — Efficient JavaScript
var posElem = document.getElementById('animation');
var newStyle = 'background: ' + newBack + ';' +
'color: ' + newColor + ';' +
'border: ' + newBorder + ';';
if(typeof(posElem.style.cssText) != 'undefined') {
posElem.style.cssText = newStyle;
} else {
posElem.setAttribute('style', newStyle);
}
Use toLocaleString()
In your case do:
return "Total Pounds Entered : " + tot.toLocaleString();
If I understand your question correctly:
for elem in doc.findall('timeSeries/values/value'):
print elem.get('dateTime'), elem.text
or if you prefer (and if there is only one occurrence of timeSeries/values
:
values = doc.find('timeSeries/values')
for value in values:
print value.get('dateTime'), elem.text
The findall()
method returns a list of all matching elements, whereas find()
returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values
element, in this case leading to the same result.
I don't see where the problem with not finding timeSeries
comes from however. Maybe you just forgot the getroot()
call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values
or //timeSeries/values
)
If that kind of thing does not already exist, you can make an NSString category:
@interface NSString (TrucBiduleChoseAdditions)
- (BOOL)isEmpty;
@end
@implementation NSString (TrucBiduleChoseAdditions)
- (BOOL)isEmpty {
return self == nil || [@"" isEqualToString:self];
}
@end
from state in _objedatasource.StateList()
where listofcountrycodes.Contains(state.CountryCode)
select state
Here's a flow chart that illustrates a for loop:
The equivalent C code would be
for(i = 2; i <= 6; i = i + 2) {
printf("%d\t", i + 1);
}
I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.
You are making it complicated. string
is already nullable. You don't need to make it more nullable. Take out the ?
on the property type.
public void Enable_Usercontrol1()
{
UserControl1 usercontrol1 = new UserControl1();
usercontrol1.Enabled = true;
}
/*
Put this Anywhere in your Form and Call it by Enable_Usercontrol1();
Also, Make sure the Usercontrol1 Modifiers is Set to Protected Internal
*/
I've created a bash command. Configure it with 3 simple steps. then in the terminal just type cleandd
https://github.com/Salarsoleimani/Usefulscripts
you can use the identity
log[a]x
log[b]x = ---------
log[a]b
so this would be applicable for log2.
log[10]x
log[2]x = ----------
log[10]2
just plug this into the java Math log10 method....
Apache commons collections 4 has a CircularFifoQueue<> which is what you are looking for. Quoting the javadoc:
CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.
import java.util.Queue;
import org.apache.commons.collections4.queue.CircularFifoQueue;
Queue<Integer> fifo = new CircularFifoQueue<Integer>(2);
fifo.add(1);
fifo.add(2);
fifo.add(3);
System.out.println(fifo);
// Observe the result:
// [2, 3]
If you are using an older version of the Apache commons collections (3.x), you can use the CircularFifoBuffer which is basically the same thing without generics.
Update: updated answer following release of commons collections version 4 that supports generics.
The element that triggered the event can be different than the one you bound the handler to because events bubble up the DOM tree.
So if you want to get the ID of the element the event handler is bound to, you can do this easily with this.id
(this
refers to the element).
But if you want to get the element where the event originated, then you have to access it with event.target
in W3C compatible browsers and event.srcElement
in IE 8 and below.
I would avoid writing a lot of JavaScript in the onXXXX
HTML attributes. I would only pass the event
object and put the code to extract the element in the handler (or in an extra function):
<div onlick="doWithThisElement(event)">
Then the handler would look like this:
function doWithThisElement(event) {
event = event || window.event; // IE
var target = event.target || event.srcElement; // IE
var id = target.id;
//...
}
I suggest to read the excellent articles about event handling at quirksmode.org.
Btw
<link onclick="doWithThisElement(id_of_this_element)" />
does hardly make sense (<link>
is an element that can only appear in the <head>
, binding an event handler (if even possible) will have no effect).
This worked for me.
git reset --hard ORIG_HEAD
Undo a merge or pull:
$ git pull (1)
Auto-merging nitfol
CONFLICT (content): Merge conflict in nitfol
Automatic merge failed; fix conflicts and then commit the result.
$ git reset --hard (2)
$ git pull . topic/branch (3)
Updating from 41223... to 13134...
Fast-forward
$ git reset --hard ORIG_HEAD (4)
Checkout this: HEAD and ORIG_HEAD in Git for more.
The accepted answer nor the other answer work for me. I found this post which suggested
string.encode!('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
This fixed the problem for me.
You cannot manually expire a token after it has been created. Thus, you cannot log out with JWT on the server-side as you do with sessions.
JWT is stateless, meaning that you should store everything you need in the payload and skip performing a DB query on every request. But if you plan to have a strict log out functionality, that cannot wait for the token auto-expiration, even though you have cleaned the token from the client-side, then you might need to neglect the stateless logic and do some queries. so what's a solution?
Set a reasonable expiration time on tokens
Delete the stored token from client-side upon log out
Query provided token against The Blacklist on every authorized request
“Blacklist” of all the tokens that are valid no more and have not expired yet. You can use a DB that has a TTL option on documents which would be set to the amount of time left until the token is expired.
Redis is a good option for blacklist, which will allow fast in-memory access to the list. Then, in the middleware of some kind that runs on every authorized request, you should check if the provided token is in The Blacklist. If it is you should throw an unauthorized error. And if it is not, let it go and the JWT verification will handle it and identify if it is expired or still active.
For more information, see How to log out when using JWT. by Arpy Vanyan
In order to serve up a static CSS file in express app (i.e. use a css style file to style ejs "templates" files in express app). Here are the simple 3 steps that need to happen:
Place your css file called "styles.css" in a folder called "assets" and the assets folder in a folder called "public". Thus the relative path to the css file should be "/public/assets/styles.css"
In the head of each of your ejs files you would simply call the css file (like you do in a regular html file) with a <link href=… />
as shown in the code below. Make sure you copy and paste the code below directly into your ejs file <head>
section
<link href= "/public/assets/styles.css" rel="stylesheet" type="text/css" />
In your server.js file, you need to use the app.use()
middleware. Note that a middleware is nothing but a term that refers to those operations or code that is run between the request and the response operations. By putting a method in middleware, that method will automatically be called everytime between the request and response methods. To serve up static files (such as a css file) in the app.use()
middleware there is already a function/method provided by express called express.static()
. Lastly, you also need to specify a request route that the program will respond to and serve up the files from the static folder everytime the middleware is called. Since you will be placing the css files in your public folder. In the server.js file, make sure you have the following code:
// using app.use to serve up static CSS files in public/assets/ folder when /public link is called in ejs files
// app.use("/route", express.static("foldername"));
app.use('/public', express.static('public'));
After following these simple 3 steps, every time you res.render('ejsfile')
in your app.get()
methods you will automatically see the css styling being called. You can test by accessing your routes in the browser.
try this
<c:forEach items="${list}" var="map">
<tr>
<c:forEach items="${map}" var="entry">
<td>${entry.value}</td>
</c:forEach>
</tr>
</c:forEach>
Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution? So, if the value includes any parts of time, it should return true too. I could NOT be able to define a array of format.
When I was in a similar situation, here is what I did:
This http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simple was really helpful both for understanding as well as validation the syntax for each format.
My 2 cents if it helps....
Try this solution if the Reset Password option (of SQL Developer) did not work:
Step 1: Open Run SQL Command Line (from the start menu, which comes with SQL Developer installation package)
Step 2: Run the following commands:
Note: If password has already expired, Changing password for <user>
option will automatically come.
Here's a variation on ashirazi's answer which doesn't rely on $IFS
. It does have its own issues which I ouline below.
sentence="one;two;three"
sentence=${sentence//;/$'\n'} # change the semicolons to white space
for word in $sentence
do
echo "$word"
done
Here I've used a newline, but you could use a tab "\t
" or a space. However, if any of those characters are in the text it will be split there, too. That's the advantage of $IFS
- it can not only enable a separator, but disable the default ones. Just make sure you save its value before you change it - as others have suggested.
In this question, the answer from @PbxMan should get you started:
Run a Java Application as a Service on Linux
Edit:
There is another, less nice way to start a process on reboot, using cron:
@reboot user-to-run-under /usr/bin/java -jar /path/to/application.jar
This works, but gives you no nice start/stop interface for your application. You can still simply kill
it anyway...
Not exactly the case of this question but can be helpful. I got this exception when i call mkdirs() on new file instead of its parent
File file = new java.io.File(path);
//file.mkdirs(); // wrong!
file.getParentFile().mkdirs(); // correct!
if (!file.exists()) {
file.createNewFile();
}
=IIF(Fields!Column.Value = "Approved", "Green", "No Color")
<<
is a binary shift, shifting 1 to the left 8 places.
4'b0001 << 1 => 4'b0010
>>
is a binary right shift adding 0's to the MSB.
>>>
is a signed shift which maintains the value of the MSB if the left input is signed.
4'sb1011 >> 1 => 0101
4'sb1011 >>> 1 => 1101
Three ways to indicate left operand is signed:
module shift;
logic [3:0] test1 = 4'b1000;
logic signed [3:0] test2 = 4'b1000;
initial begin
$display("%b", $signed(test1) >>> 1 ); //Explicitly set as signed
$display("%b", test2 >>> 1 ); //Declared as signed type
$display("%b", 4'sb1000 >>> 1 ); //Signed constant
$finish;
end
endmodule
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
In my case, all other solutions didn't work, but this one did:
obj = {...arr}
my arr is in a form: [name: "the name", email: "[email protected]"]
I had same kind of problem in Netbeans.
I updated the image location in the project and when I executed the jsp file, the image was not loaded in the page.
Then I clean and Built the project in Netbeans. Then it worked fine.
Though you need to check the image actually exists or not using the image URL in the browser.
You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
You should put the print function in your view-details.php file and call it once the file is loaded, by either using
<body onload="window.print()">
or
$(document).ready(function () {
window.print();
});
The connection string is a string of the form:
postgres://[user[:password]@][host][:port][/dbname]
(where the parts in [...]
can optionally be included or excluded)
Some examples of valid connection strings include:
postgres://localhost
postgres://localhost:5432
postgres://localhost/mydb
postgres://user@localhost
postgres://user:secret_password@localhost
If you've just started a database on your local machine, the connection string postgres://localhost
will typically work, as that uses the default port number, username, and no password. If the database was started with a specific account, you might find you need to use postgres://pg@localhost
or postgres://postgres@localhost
If none of these work, and you have installed docker, another option is to run npx @databases/pg-test start
. This will start a postgres server in a docker container and then print out the connection string for you. The pg-test
databases are only intended for testing though, so you will loose all your data if your computer restarts.
You can connect to the database and issue queries using @databases/pg
:
const createPool = require('@databases/pg');
const {sql} = require('@databases/pg');
// If you're using TypeScript or Babel, you can swap
// the two `require` calls for this import statement:
// import createPool, {sql} from '@databases/pg';
// create a "pool" of connections, you can think of this as a single
// connection, the pool is just used behind the scenes to improve
// performance
const db = createPool('postgres://localhost');
// wrap code in an `async` function so we can use `await`
async function run() {
// we can run sql by tagging it as "sql" and then passing it to db.query
await db.query(sql`
CREATE TABLE IF NOT EXISTS beatles (
name TEXT NOT NULL,
height INT NOT NULL,
birthday DATE NOT NULL
);
`);
const beatle = {
name: 'George',
height: 70,
birthday: new Date(1946, 02, 14),
};
// If we need to pass values, we can use ${...} and they will
// be safely & securely escaped for us
await db.query(sql`
INSERT INTO beatles (name, height, birthday)
VALUES (${beatle.name}, ${beatle.height}, ${beatle.birthday});
`);
console.log(
await db.query(sql`SELECT * FROM beatles;`)
);
}
run().catch(ex => {
// It's a good idea to always report errors using
// `console.error` and set the process.exitCode if
// you're calling an async function at the top level
console.error(ex);
process.exitCode = 1;
}).then(() => {
// For this little demonstration, we'll dispose of the
// connection pool when we're done, so that the process
// exists. If you're building a web server/backend API
// you probably never need to call this.
return db.dispose();
});
You can find a more complete guide to querying Postgres using node.js at https://www.atdatabases.org/docs/pg
I was looking for this answer:
import os,glob
folder_path = '/some/path/to/file'
for filename in glob.glob(os.path.join(folder_path, '*.htm')):
with open(filename, 'r') as f:
text = f.read()
print (filename)
print (len(text))
you can choose as well '*.txt' or other ends of your filename
...
public static final String NOTIFICATION_CHANNEL_ID = MyLocationService.class.getSimpleName();
...
...
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_ID+"_name",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.notification_text))
.setOngoing(true)
.setContentIntent(broadcastIntent)
.setSmallIcon(R.drawable.ic_tracker)
.setPriority(PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_SERVICE);
startForeground(1, builder.build());
...
This is because Cascade Deletes are enabled by default. The problem is that when you call a delete on the entity, it will delete each of the f-key referenced entities as well. You should not make 'required' values nullable to fix this problem. A better option would be to remove EF Code First's Cascade delete convention:
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
It's probably safer to explicitly indicate when to do a cascade delete for each of the children when mapping/config. the entity.
In most contexts where double
values are used, calculations will have a certain amount of uncertainty. The difference between 1.33333333333333300 and 1.33333333333333399 may be less than the amount of uncertainty that exists in the calculations. Displaying the value of "2/3 + 2/3" as "1.33333333333333" is apt to be more meaningful than displaying it as "1.33333333333333319", since the latter display implies a level of precision that doesn't really exist.
In the debugger, however, it is important to uniquely indicate the value held by a variable, including essentially-meaningless bits of precision. It would be very confusing if a debugger displayed two variables as holding the value "1.333333333333333" when one of them actually held 1.33333333333333319 and the other held 1.33333333333333294 (meaning that, while they looked the same, they weren't equal). The extra precision shown by the debugger isn't apt to represent a numerically-correct calculation result, but indicates how the code will interpret the values held by the variables.
When you open catalina.sh / catalina.bat, you can see :
Environment Variable Prequisites
JAVA_HOME Must point at your Java Development Kit installation.
So, set your environment variable JAVA_HOME
to point to Java 6. Also make sure JRE_HOME
is pointing to the same target, if it is set.
Update: since you are on Windows, see here for how to manage your environment variables
I added this to Espuz and JCC's answer. It uses the y position of the subviews and doesn't include the scroll bars. Edit Uses the bottom of the lowest sub view that is visible.
+ (CGFloat) bottomOfLowestContent:(UIView*) view
{
CGFloat lowestPoint = 0.0;
BOOL restoreHorizontal = NO;
BOOL restoreVertical = NO;
if ([view respondsToSelector:@selector(setShowsHorizontalScrollIndicator:)] && [view respondsToSelector:@selector(setShowsVerticalScrollIndicator:)])
{
if ([(UIScrollView*)view showsHorizontalScrollIndicator])
{
restoreHorizontal = YES;
[(UIScrollView*)view setShowsHorizontalScrollIndicator:NO];
}
if ([(UIScrollView*)view showsVerticalScrollIndicator])
{
restoreVertical = YES;
[(UIScrollView*)view setShowsVerticalScrollIndicator:NO];
}
}
for (UIView *subView in view.subviews)
{
if (!subView.hidden)
{
CGFloat maxY = CGRectGetMaxY(subView.frame);
if (maxY > lowestPoint)
{
lowestPoint = maxY;
}
}
}
if ([view respondsToSelector:@selector(setShowsHorizontalScrollIndicator:)] && [view respondsToSelector:@selector(setShowsVerticalScrollIndicator:)])
{
if (restoreHorizontal)
{
[(UIScrollView*)view setShowsHorizontalScrollIndicator:YES];
}
if (restoreVertical)
{
[(UIScrollView*)view setShowsVerticalScrollIndicator:YES];
}
}
return lowestPoint;
}
If you use the vim plugin https://github.com/tpope/vim-surround (or use VSCode Vim plugin, which comes with vim-surround pre-installed), its pretty convinient!
add
ysiw' // surround in word `'`
drop
ds' // drop surround `'`
change
cs'" // change surround from `'` to `"`
It even works for html tags!
cst<em> // change surround from current tag to `<em>`
check out the readme on github for better examples
You could create two handlers for file and stdout and then create one logger with handlers
argument to basicConfig
. It could be useful if you have the same log_level and format output for both handlers:
import logging
import sys
file_handler = logging.FileHandler(filename='tmp.log')
stdout_handler = logging.StreamHandler(sys.stdout)
handlers = [file_handler, stdout_handler]
logging.basicConfig(
level=logging.DEBUG,
format='[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s',
handlers=handlers
)
logger = logging.getLogger('LOGGER_NAME')
Something like this might help:
SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=
The important part is the first line. It takes the output of the internal DATE
value and parses it into an environmental variable named Today
, in the format CCYYMMDD
, as in '20110407`.
The %Date:~10,4%
says to extract a *substring of the Date
environmental variable 'Thu 04/07/2011' (built in - type echo %Date%
at a command prompt) starting at position 10 for 4 characters (2011
). It then concatenates another substring of Date:
starting at position 4 for 2 chars (04
), and then concats two additional characters starting at position 7 (07
).
*The substring value starting points are 0-based.
You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.
var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top;
if (!isNaN(top)) {
$("#app_scroler").click(function () {
$('html, body').animate({
scrollTop: top
}, 100);
});
}
if you want to scroll a little above or below from specific div that add value to the top like this.....like I add 800
var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top + 800;
Like @user293153 I only just discovered this question and it didn't seem to be answered correctly.
His answer was best. But you can also animate to the element as well.
$('html, body').animate({ scrollTop: $("#some_element").offset().top }, 500);
The XmlTextWriter is usually used for generating (not updating) XML content. When you load the xml file into an XmlDocument, you don't need a separate writer.
Just update the node you have selected and .Save() that XmlDocument.
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
Today NodeJS supports new async/await
syntax. This is an easy syntax and makes the life much easier
async function process(promises) { // must be an async function
let x = await Promise.all(promises); // now x will be an array
x = x.map( tmp => tmp * 10); // proccessing the data.
}
const promises = [
new Promise(resolve => setTimeout(resolve, 0, 1)),
new Promise(resolve => setTimeout(resolve, 0, 2))
];
process(promises)
Learn more:
df_1.join(df_2)
df_1.merge(df_2)
on
parameter has different meaning in both casesdf_1.merge(df_2, on='column_1')
df_1.join(df_2, on='column_1') // It will throw error
df_1.join(df_2.set_index('column_1'), on='column_1')
I've added
public void ExportToFile(string path, DataTable tabela)
{
DataColumnCollection colunas = tabela.Columns;
foreach (DataRow linha in tabela.Rows)
{
this.AddRow();
foreach (DataColumn coluna in colunas)
{
this[coluna.ColumnName] = linha[coluna];
}
}
this.ExportToFile(path);
}
Previous code does not work with old .NET versions. For 3.5 version of framework use this other version:
public void ExportToFile(string path)
{
bool abort = false;
bool exists = false;
do
{
exists = File.Exists(path);
if (!exists)
{
if( !Convert.ToBoolean( File.CreateText(path) ) )
abort = true;
}
} while (!exists || abort);
if (!abort)
{
//File.OpenWrite(path);
using (StreamWriter w = File.AppendText(path))
{
w.WriteLine("hello");
}
}
//File.WriteAllText(path, Export());
}
I'm playing the Sims 3, and I did some poking around. The graphics engine is C++, while the scripting and behavior engine is C#/Mono. So while C++ is there for time critical bits, other stuff like .interaction, game logic, AI is in an object oriented managed language.
Provide a module whose responsibility is to execute requests sequentially, while tracking the current index of each operation in an ordinal manner. Define the operation in a Command Pattern for flexibility.
execute
method to chain & track each operation. SequentialPromise returns a Promise-Chain from all operations performed.execute
method while passing in an ordinal list of options for each operation.Use SequentialPromise when ordinal behavior of Promise resolution is needed. SequentialPromise will track the index for which a Promise was rejected.
clear();
var http = {
get(url) {
var delay = Math.floor( Math.random() * 10 ), even = !(delay % 2);
var xhr = new Promise(exe);
console.log(`REQUEST`, url, delay);
xhr.then( (data) => console.log(`SUCCESS: `, data) ).catch( (data) => console.log(`FAILURE: `, data) );
function exe(resolve, reject) {
var action = { 'true': reject, 'false': resolve }[ even ];
setTimeout( () => action({ url, delay }), (1000 * delay) );
}
return xhr;
}
};
var SequentialPromise = new (function SequentialPromise() {
var PRIVATE = this;
return class SequentialPromise {
constructor(context, action) {
this.index = 0;
this.requests = [ ];
this.context = context;
this.action = action;
return this;
}
log() {}
execute(url, ...more) {
var { context, action, requests } = this;
var chain = context[action](url);
requests.push(chain);
chain.then( (data) => this.index += 1 );
if (more.length) return chain.then( () => this.execute(...more) );
return chain;
}
};
})();
var sequence = new SequentialPromise(http, 'get');
var urls = [
'url/name/space/0',
'url/name/space/1',
'url/name/space/2',
'url/name/space/3',
'url/name/space/4',
'url/name/space/5',
'url/name/space/6',
'url/name/space/7',
'url/name/space/8',
'url/name/space/9'
];
var chain = sequence.execute(...urls);
var promises = sequence.requests;
chain.catch( () => console.warn(`EXECUTION STOPPED at ${sequence.index} for ${urls[sequence.index]}`) );
// console.log('>', chain, promises);
Unfortunately there is no such thing.
Windows console applications only have a single output handle. (Well, there are two STDOUT
, STDERR
but it doesn't matter here) The >
redirects the output normally written to the console handle to a file handle.
If you want to have some kind of multiplexing you have to use an external application which you can divert the output to. This application then can write to a file and to the console again.
The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column [First Name]
(with a space)--but then you'd need to use brackets every time you referred to that column.
The newer tools add them everywhere just in case or for consistency.
For doing this you can use this
title.setPaintFlags(title.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
and for remove you can use this
title.setPaintFlags(title.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using
fileIsLocked = !file.renameTo(file)
most useful, as it avoids false positives when processing write protected (or readonly) files.
Or you just put the variable in parenthesis
DECLARE @top INT = 10;
SELECT TOP (@Top) *
FROM <table_name>;
split :: Eq a => a -> [a] -> [[a]]
split d [] = []
split d s = x : split d (drop 1 y) where (x,y) = span (/= d) s
E.g.
split ';' "a;bb;ccc;;d"
> ["a","bb","ccc","","d"]
A single trailing delimiter will be dropped:
split ';' "a;bb;ccc;;d;"
> ["a","bb","ccc","","d"]
Using Angular?
This is a very important caveat to remember.
The base tag needs to not only be in the head but in the right location.
I had my base tag in the wrong place in the head, it should come before any tags with url requests. Basically placing it as the second tag underneath the title solved it for me.
<base href="/">
I wrote a little post on it here
I had the same issue earlier, but my situation was a bit different in the front-end. I'll share my scenario anyway, maybe someone might find it useful.
I had an api call to /api/user/register
in the frontend with email, password and username as request body. On submitting the form(register form), a handler function is called which initiates the fetch call to /api/user/register
. I used the event.preventDefault()
in the beginning line of this handler function, all other lines,like forming the request body as well the fetch call was written after the event.preventDefault()
. This returned a pending promise
.
But when I put the request body formation code above the event.preventDefault()
, it returned the real promise. Like this:
event.preventDefault();
const data = {
'email': email,
'password': password
}
fetch(...)
...
instead of :
const data = {
'email': email,
'password': password
}
event.preventDefault();
fetch(...)
...
There is no runtime performance cost to using var. Though, I would suspect there to be a compiling performance cost as the compiler needs to infer the type, though this will most likely be negligable.
Ive modifiet Lukas Knuth's solution a little:
1) There's no need to subclass the webview,
2) the code will crash during bytecode verification on some Android 1.6 devices if you don't put nonexistant methods in seperate classes
3) Zoom controls will still appear if the user scrolls up/down a page. I simply set the zoom controller container to visibility GONE
wv.getSettings().setSupportZoom(true);
wv.getSettings().setBuiltInZoomControls(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
// Use the API 11+ calls to disable the controls
// Use a seperate class to obtain 1.6 compatibility
new Runnable() {
public void run() {
wv.getSettings().setDisplayZoomControls(false);
}
}.run();
} else {
final ZoomButtonsController zoom_controll =
(ZoomButtonsController) wv.getClass().getMethod("getZoomButtonsController").invoke(wv, null);
zoom_controll.getContainer().setVisibility(View.GONE);
}
While Phairoh's solution seems theoretically sound, I have also found another solution to this problem. By passing the UpdatePanels id as a paramater (event target) for the doPostBack function the update panel will post back but not the entire page.
__doPostBack('myUpdatePanelId','')
*note: second parameter is for addition event args
hope this helps someone!
EDIT: so it seems this same piece of advice was given above as i was typing :)
You Can Use MYSQL Administrator Tool its free http://dev.mysql.com/downloads/gui-tools/5.0.html
you'll find many options to export ur MYSQL DataBase
Also, it is very likely, that problem with proxy settings.
Any who didn't overcome Tomact starting problrem, - try in NetBeans choose No Proxy in the Tools -> Options -> General tab.
It helped me.
If you don't want to re-encode your video AND your player can handle rotation metadata you can just change the rotation in the metadata using ffmpeg:
ffmpeg -i input.m4v -map_metadata 0 -metadata:s:v rotate="90" -codec copy output.m4v
In my case i have to create a custom cell with a image which is coming from server and can be of any width and height. And two UILabels with dynamic size(both width & height)
i have achieved the same here in my answer with autolayout and programmatically:
Basically above @smileyBorg answer helped but systemLayoutSizeFittingSize never worked for me, In my approach :
1. No use of automatic row height calculation property. 2.No use of estimated height 3.No need of unnecessary updateConstraints. 4.No use of Automatic Preferred Max Layout Width. 5. No use of systemLayoutSizeFittingSize (should have use but not working for me, i dont know what it is doing internally), but instead my method -(float)getViewHeight working and i know what it's doing internally.
<Window x:Class="HTA.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
mc:Ignorable="d"
ResizeMode="NoResize"
WindowStartupLocation="CenterScreen"
Width="1024" Height="768"
WindowState="Maximized" WindowStyle="None">
Window state to Maximized and window style to None
Loki's answer points to the Hibernate 3 docs and provides good information, but I was still not getting the results I expected.
Much thrashing, waving of arms and general dead mouse runs finally landed me my cheese.
Because Hibernate 3 is using Simple Logging Facade for Java (SLF4J) (per the docs), if you are relying on Log4j 1.2 you will also need the slf4j-log4j12-1.5.10.jar if you are wanting to fully configure Hibernate logging with a log4j configuration file. Hope this helps the next guy.
Check this below code, it works
#define MAX_BYTE_RANGE 255
template <typename T>
class string
{
public:
typedef char *pointer;
typedef const char *const_pointer;
typedef __gnu_cxx::__normal_iterator<pointer, string> iterator;
typedef __gnu_cxx::__normal_iterator<const_pointer, string> const_iterator;
string() : length(0)
{
}
size_t size() const
{
return length;
}
void operator=(const_pointer value)
{
if (value == nullptr)
throw std::invalid_argument("value cannot be null");
auto count = strlen(value);
if (count > 0)
_M_copy(value, count);
}
void operator=(const string &value)
{
if (value.length != 0)
_M_copy(value.buf, value.length);
}
iterator begin()
{
return iterator(buf);
}
iterator end()
{
return iterator(buf + length);
}
const_iterator begin() const
{
return const_iterator(buf);
}
const_iterator end() const
{
return const_iterator(buf + length);
}
const_pointer c_str() const
{
return buf;
}
~string()
{
}
private:
unsigned char length;
T buf[MAX_BYTE_RANGE];
void _M_copy(const_pointer value, size_t count)
{
memcpy(buf, value, count);
length = count;
}
};
I tore my app and all its dependencies to bits over this issue (details here: AngularJS app initiating twice (tried the usual solutions..))
And in the end, it was all Batarang Chrome plugin's fault.
Resolution in this answer:
I'd strongly recommend the first thing on anyone's list is to disable it per the post before altering code.
It is indeed a key conflict. When concatenating arrays, duplicate keys are not overwritten.
Instead you must use array_merge()
$array = array_merge(array('Item 1'), array('Item 2'));
Wasn't sure if you meant which Oracle users can read\write with the directory or the correlation of the permissions between Oracle Directory Object and the underlying Operating System Directory.
As DCookie has covered the Oracle side of the fence, the following is taken from the Oracle documentation found here.
Privileges granted for the directory are created independently of the permissions defined for the operating system directory, and the two may or may not correspond exactly. For example, an error occurs if sample user hr is granted READ privilege on the directory object but the corresponding operating system directory does not have READ permission defined for Oracle Database processes.
This works for me:
$('#element').click(function (e) {
if (e.offsetX > e.target.offsetLeft) {
// click on element
}
else{
// click on ::before element
}
});
So as to have another possibility1 to find the files that are executable by the current user:
find . -type f -exec test -x {} \; -print
(the test command here is the one found in PATH, very likely /usr/bin/test
, not the builtin).
1 Only use this if the -executable
flag of find
is not available! this is subtly different from the -perm +111
solution.
By keys()
and values()
methods of dictionary and zip
.
zip
will return a list of tuples which acts like an ordered dictionary.
Demo:
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]
I've assumed a named JSONArray is a JSONObject and accessed the data from the server to populate an Android GridView. For what it is worth my method is:
private String[] fillTable( JSONObject jsonObject ) {
String[] dummyData = new String[] {"1", "2", "3", "4", "5", "6", "7","1", "2", "3", "4", "5", "6", "7","1", "2", "3", "4", "5", "6", "7", };
if( jsonObject != null ) {
ArrayList<String> data = new ArrayList<String>();
try {
// jsonArray looks like { "everything" : [{}, {},] }
JSONArray jsonArray = jsonObject.getJSONArray( "everything" );
int number = jsonArray.length(); //How many rows have got from the database?
Log.i( Constants.INFORMATION, "Number of ows returned: " + Integer.toString( number ) );
// Array elements look like this
//{"success":1,"error":0,"name":"English One","owner":"Tutor","description":"Initial Alert","posted":"2013-08-09 15:35:40"}
for( int element = 0; element < number; element++ ) { //visit each element
JSONObject jsonObject_local = jsonArray.getJSONObject( element );
// Overkill on the error/success checking
Log.e("JSON SUCCESS", Integer.toString( jsonObject_local.getInt(Constants.KEY_SUCCESS) ) );
Log.e("JSON ERROR", Integer.toString( jsonObject_local.getInt(Constants.KEY_ERROR) ) );
if ( jsonObject_local.getInt( Constants.KEY_SUCCESS) == Constants.JSON_SUCCESS ) {
String name = jsonObject_local.getString( Constants.KEY_NAME );
data.add( name );
String owner = jsonObject_local.getString( Constants.KEY_OWNER );
data.add( owner );
String description = jsonObject_local.getString( Constants.KEY_DESCRIPTION );
Log.i( "DESCRIPTION", description );
data.add( description );
String date = jsonObject_local.getString( Constants.KEY_DATE );
data.add( date );
}
else {
for( int i = 0; i < 4; i++ ) {
data.add( "ERROR" );
}
}
}
} //JSON object is null
catch ( JSONException jsone) {
Log.e( "JSON EXCEPTION", jsone.getMessage() );
}
dummyData = data.toArray( dummyData );
}
return dummyData;
}
With the latest version of Lollipop, go into app. drawer and look for Google Settings. Scroll down to Security, tap iit to open, slide to the left the slider next to 'Improve harmful app. detection' to the left, then same for 'Scan device for security threats'. Exit out of that, and the annoying pop up will never appear again!
This is what matplotlib.pyplot.scatter
is for.
As a quick example:
import matplotlib.pyplot as plt
import numpy as np
# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)
plt.scatter(t,x,c=y)
plt.show()
I hope this answers the intent of the question. Although there are no Booleans in SQL Server, if you have a database that had Boolean types that was translated from Access, the phrase which works in Access was "...WHERE Foo" (Foo is the Boolean column name). It can be replaced by "...WHERE Foo<>0" ... and this works. Good luck!
document.getElementById('TextBoxID').readOnly = true; //to enable readonly
document.getElementById('TextBoxID').readOnly = false; //to disable readonly
For float
have a look at sys.float_info
:
>>> import sys
>>> sys.float_info
sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2
250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsil
on=2.2204460492503131e-16, radix=2, rounds=1)
Specifically, sys.float_info.max
:
>>> sys.float_info.max
1.7976931348623157e+308
If that's not big enough, there's always positive infinity:
>>> infinity = float("inf")
>>> infinity
inf
>>> infinity / 10000
inf
The long
type has unlimited precision, so I think you're only limited by available memory.
Please confirm that your firewall is allowing outbound traffic and that you are not being blocked by antivirus software.
I received the same issue and the culprit was antivirus software.
In my case i just needed to pass the whole url and encode only the value of each parameters. I didn't find a common code to do that so (!!) so i created this small method to do the job :
public static String encodeUrl(String url) throws Exception {
if (url == null || !url.contains("?")) {
return url;
}
List<String> list = new ArrayList<>();
String rootUrl = url.split("\\?")[0] + "?";
String paramsUrl = url.replace(rootUrl, "");
List<String> paramsUrlList = Arrays.asList(paramsUrl.split("&"));
for (String param : paramsUrlList) {
if (param.contains("=")) {
String key = param.split("=")[0];
String value = param.replace(key + "=", "");
list.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
else {
list.add(param);
}
}
return rootUrl + StringUtils.join(list, "&");
}
public static String decodeUrl(String url) throws Exception {
return URLDecoder.decode(url, "UTF-8");
}
It uses org.apache.commons.lang3.StringUtils
Open a new worksheet on the related instance (Alt-F10)
and run the following query
SELECT view_name, owner
FROM sys.all_views
ORDER BY owner, view_name
This worked for me - ( from mongo shell )
var file = cat('./new.json'); # file name
use testdb # db name
var o = JSON.parse(file); # convert string to JSON
db.forms.insert(o) # collection name
String[] name = {"amit", "rahul", "surya"};
public static String arrayToString(String array[])
{
if (array.length == 0) return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; ++i)
{
sb.append(",'").append(array[i]).append("'");
}
return sb.substring(1);
}
To get a scrollbar for an ItemsControl
, you can host it in a ScrollViewer
like this:
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl>
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
</ItemsControl>
</ScrollViewer>
This worked for me: first, make sure the npm directories have the right user
sudo chown -R myuser ~/.npm
sudo chown -R myuser /usr/local/lib/node_modules
Then your in your package.json link the directory
"scripts": {
"preinstall": "npm ln mylib ../../path/to/mylib"
},
"dependencies": {
"mylib" : "*"
}
If you have an instance of the class, or can get one, you have a pure java solution:
try{
Class clazz = Class.forName(" try{
Class clazz = Class.forName("class-name");
String name = "/"+clazz.getName().replace('.', '/')+".class";
URL url = clazz.getResource(name);
String jar = url.toString().substring(10).replaceAll("!.*", "");
System.out.println( jar );
}catch(Exception err){
err.printStackTrace();
}
Of course, the first two line have to adapted according to where you have an instance of the class or the class name.
In my case I have a database class that handle all the direct database interaction such as querying, fetching, and such. So if I had to change my database from MySQL to PostgreSQL there won't be any problem. So adding that extra layer can be useful.
Each table can have its own class and have its specific methods, but to actually get the data, it lets the database class handle it:
Database.php
class Database {
private static $connection;
private static $current_query;
...
public static function query($sql) {
if (!self::$connection){
self::open_connection();
}
self::$current_query = $sql;
$result = mysql_query($sql,self::$connection);
if (!$result){
self::close_connection();
// throw custom error
// The query failed for some reason. here is query :: self::$current_query
$error = new Error(2,"There is an Error in the query.\n<b>Query:</b>\n{$sql}\n");
$error->handleError();
}
return $result;
}
....
public static function find_by_sql($sql){
if (!is_string($sql))
return false;
$result_set = self::query($sql);
$obj_arr = array();
while ($row = self::fetch_array($result_set))
{
$obj_arr[] = self::instantiate($row);
}
return $obj_arr;
}
}
Table object classL
class DomainPeer extends Database {
public static function getDomainInfoList() {
$sql = 'SELECT ';
$sql .='d.`id`,';
$sql .='d.`name`,';
$sql .='d.`shortName`,';
$sql .='d.`created_at`,';
$sql .='d.`updated_at`,';
$sql .='count(q.id) as queries ';
$sql .='FROM `domains` d ';
$sql .='LEFT JOIN queries q on q.domainId = d.id ';
$sql .='GROUP BY d.id';
return self::find_by_sql($sql);
}
....
}
I hope this example helps you create a good structure.
You could do it in either of this ways , triggering an onclick
on a form button like this,
<form id="myform" name="myform" method="post" action="demo2.jsp">
<input type="text" name="usnername" />
<input type="text" name="password"/>
<input type="button" value="go" onclick="submitForm" />
</form>
And using javascript
,
function submitForm() {
document.forms[0].submit();
return true;
}
or you could also try Ajax
to post your page
here is the link jQueryAjax
And also nice startup examples using Ajax and here
Hope this helps !!
Try this one. It will sort numbers from other variables.
const obj = {
a: 1,
b: 2,
c: 3
};
const result = Object.keys(obj)
.reduce((acc, rec) => typeof obj[rec] === "number" ? acc.concat([obj[rec]]) : acc, [])
.reduce((acc, rec) => acc + rec)
This worked for me.
<table>
<tr>
<td *ngFor="#group of groups">
<h1>{{group.name}}</h1>
</td>
</tr>
</table>
Here's what worked for me:
$a = Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-7)}
if ($a = (Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}
#Im using the -gt switch instead of -ge
{}
Else
{
'STORE XXX HAS NOT RECEIVED ANY ORDERS IN THE PAST 7 DAYS'
}
$b = Get-ChildItem \\COMP NAME\Folder\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-1)}
if ($b = (Get-ChildItem \\COMP NAME\TFolder\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-1)))}
{}
Else
{
'STORE XXX DID NOT RUN ITS BACKUP LAST NIGHT'
}
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
Try this:
$("#textbox").bind('paste',function() {alert("Change detected!");});
See demo on JSFiddle.
You could use JavaScript and XMLHTTPRequest (AJAX) to perform a POST without using a form. Check this link out. Keep in mind that you will need JavaScript enabled in your browser though.
If you are using Git Gui on windows,
You can't do what I think you're asking to do.
The only privileges you can grant on procedures are EXECUTE and DEBUG.
If you want to allow user B to create a procedure in user A schema, then user B must have the CREATE ANY PROCEDURE privilege. ALTER ANY PROCEDURE and DROP ANY PROCEDURE are the other applicable privileges required to alter or drop user A procedures for user B. All are wide ranging privileges, as it doesn't restrict user B to any particular schema. User B should be highly trusted if granted these privileges.
EDIT:
As Justin mentioned, the way to give execution rights to A for a procedure owned by B:
GRANT EXECUTE ON b.procedure_name TO a;
Figure and Figcaption tags:
<figure>
<img src='image.jpg' alt='missing' />
<figcaption>Caption goes here</figcaption>
</figure>
Gotta love HTML5.
See sample
#container {_x000D_
text-align: center;_x000D_
}_x000D_
a, figure {_x000D_
display: inline-block;_x000D_
}_x000D_
figcaption {_x000D_
margin: 10px 0 0 0;_x000D_
font-variant: small-caps;_x000D_
font-family: Arial;_x000D_
font-weight: bold;_x000D_
color: #bb3333;_x000D_
}_x000D_
figure {_x000D_
padding: 5px;_x000D_
}_x000D_
img:hover {_x000D_
transform: scale(1.1);_x000D_
-ms-transform: scale(1.1);_x000D_
-webkit-transform: scale(1.1);_x000D_
-moz-transform: scale(1.1);_x000D_
-o-transform: scale(1.1);_x000D_
}_x000D_
img {_x000D_
transition: transform 0.2s;_x000D_
-webkit-transition: -webkit-transform 0.2s;_x000D_
-moz-transition: -moz-transform 0.2s;_x000D_
-o-transition: -o-transform 0.2s;_x000D_
}
_x000D_
<div id="container">_x000D_
<a href="#">_x000D_
<figure>_x000D_
<img src="http://lorempixel.com/100/100/nature/1/" width="100px" height="100px" />_x000D_
<figcaption>First image</figcaption>_x000D_
</figure>_x000D_
</a>_x000D_
<a href="#">_x000D_
<figure>_x000D_
<img src="http://lorempixel.com/100/100/nature/2/" width="100px" height="100px" />_x000D_
<figcaption>Second image</figcaption>_x000D_
</figure>_x000D_
</a>_x000D_
</div>
_x000D_
JToken
is the base class for JObject
, JArray
, JProperty
, JValue
, etc. You can use the Children<T>()
method to get a filtered list of a JToken's children that are of a certain type, for example JObject
. Each JObject
has a collection of JProperty
objects, which can be accessed via the Properties()
method. For each JProperty
, you can get its Name
. (Of course you can also get the Value
if desired, which is another JToken
.)
Putting it all together we have:
JArray array = JArray.Parse(json);
foreach (JObject content in array.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
Console.WriteLine(prop.Name);
}
}
Output:
MobileSiteContent
PageContent
If table does not have relation, just copy all in new table with row number and remove old and rename new one with old one.
Select RowNum = ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) , * INTO cdm.dbo.SALES2018 from
(
select * from SALE2018) as SalesSource
For Each row As DataGridViewRow In yourDGV.SelectedRows
yourDGV.Rows.Remove(row)
Next
This will delete all rows that had been selected.
You can just use the Paths
class:
Path path = Paths.get(textPath);
... assuming you want to use the default file system, of course.
You can get the nodeValue of the first childNode using
$('.title')[0].childNodes[0].nodeValue
Bad practice definitely. One reason is that it is not very 'user-friendly' for the fact that every JFrame
shows a new taskbar icon. Controlling multiple JFrame
s will have you ripping your hair out.
Personally, I would use ONE JFrame
for your kind of application. Methods of displaying multiple things is up to you, there are many. Canvas
es, JInternalFrame
, CardLayout
, even JPanel
s possibly.
Multiple JFrame objects = Pain, trouble, and problems.
I found this question as I had a similar problem. While data-backdrop
does "solve" the issue; I found another problem in my markup.
I had the button which launched this modal and the modal dialog itself was in the footer. The problem is that the footer was defined as navbar_fixed_bottom
, and that contained position:fixed
.
After I moved the dialog outside of the fixed section, everything worked as expected.
Try this:
function funcName() {
alert("test");
}
var run = setInterval(funcName, 10000)
You might want to do something like this (if you're in java 5 & up)
Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
The steps for schedule jobs in Jenkins:
@midnight
Note: under the schedule field, can see the last and the next date-time run.
Jenkins also supports predefined aliases to schedule build:
@hourly
, @daily
, @weekly
, @monthly
, @midnight
@hourly
--> Build every hour at the beginning of the hour --> 0 * * * *
@daily, @midnight
--> Build every day at midnight --> 0 0 * * *
@weekly
--> Build every week at midnight on Sunday morning --> 0 0 * * 0
@monthly
--> Build every month at midnight of the first day of the month --> 0 0 1 * *
Here is your solution for the problem,
$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
if(ord($i) % 2 != 0)
$letter[] .= $i;
}
print_r($letter);
You need to get the ASCII value for that character which will solve your problem.
Here is ord doc and working code.
For your requirement, you can do like this,
for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
$letter[] .= $i;
}
print_r($letter);
Here set $x as per your requirement.
lencioni's answer is what I'd recommend. You can change the selector for the option ('#mySelect option:last')
to select the option with a specific value using "#mySelect option[value='yourDefaultValue']
". More on selectors.
If you're working extensively with select lists on the client check out this plugin: http://www.texotela.co.uk/code/jquery/select/. Take a look the source if you want to see some more examples of working with select lists.
I have met this issue several times and every time I landed on this page, tried every thing and failed!
It's because I have 2FA enabled!!!
According to https://help.github.com/articles/which-remote-url-should-i-use/#when-2fa-is-enabled
If you have enabled two-factor authentication, or if you are accessing an organization that uses SAML single sign-on, you must provide a personal access token instead of entering your password for HTTPS Git.
git clone https://github.com/username/repo_name.git
(The default git repo link is good enough!)Update:
git config credential.helper store
(don't do this on machine you don't trust)In F#, the distance from the point c
to the line segment between a
and b
is given by:
let pointToLineSegmentDistance (a: Vector, b: Vector) (c: Vector) =
let d = b - a
let s = d.Length
let lambda = (c - a) * d / s
let p = (lambda |> max 0.0 |> min s) * d / s
(a + p - c).Length
The vector d
points from a
to b
along the line segment. The dot product of d/s
with c-a
gives the parameter of the point of closest approach between the infinite line and the point c
. The min
and max
function are used to clamp this parameter to the range 0..s
so that the point lies between a
and b
. Finally, the length of a+p-c
is the distance from c
to the closest point on the line segment.
Example use:
pointToLineSegmentDistance (Vector(0.0, 0.0), Vector(1.0, 0.0)) (Vector(-1.0, 1.0))
It works for me:
File imgFile = new File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//Drawable d = new BitmapDrawable(getResources(), myBitmap);
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
Edit:
If above hard-coded sdcard directory is not working in your case, you can fetch the sdcard path:
String sdcardPath = Environment.getExternalStorageDirectory().toString();
File imgFile = new File(sdcardPath);
So,
You have plenty of options to check whether your variable is string or not:
a = "my string"
type(a) == str # first
a.__class__ == str # second
isinstance(a, str) # third
str(a) == a # forth
type(a) == type('') # fifth
This order is for purpose.
Transform the data structure to a map if you frequently use this search
mapPersons: Map<number, Person>;
// prepare the map - call once or when person array change
populateMap() : void {
this.mapPersons = new Map();
for (let o of this.personService.getPersons()) this.mapPersons.set(o.id, o);
}
getPerson(id: number) : Person {
return this.mapPersons.get(id);
}
The simple answer... One who knows assembly well (aka has the reference beside him, and is taking advantage of every little processor cache and pipeline feature etc) is guaranteed to be capable of producing much faster code than any compiler.
However the difference these days just doesn't matter in the typical application.
private static void test()
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
string [] dirs = System.IO.Directory.GetDirectories("C:\\Test\\");
string[] files = System.IO.Directory.GetFiles("C:\\Test\\");
if (dirs.Length == 0 && files.Length == 0)
Console.WriteLine("Empty");
else
Console.WriteLine("Not Empty");
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
This quick test came back in 2 milliseconds for the folder when empty and when containing subfolders & files (5 folders with 5 files in each)
You can't.
One workaround is to create clone environment, and then remove original one:
(remember about deactivating current environment with deactivate
on Windows and source deactivate
on macOS/Linux)
conda create --name new_name --clone old_name
conda remove --name old_name --all # or its alias: `conda env remove --name old_name`
There are several drawbacks of this method:
--offline
flag to disable it,There is an open issue requesting this feature.
Really have to do this with JS. Here's a solution. I didn't use your class names, but I called the div within the td class name of "full-height" :-) Used jQuery, obviously. Note this was called from jQuery(document).ready(function(){ setFullHeights();}); Also note if you have images, you are going to have to iterate through them first with something like:
function loadedFullHeights(){
var imgCount = jQuery(".full-height").find("img").length;
if(imgCount===0){
return setFullHeights();
}
var loaded = 0;
jQuery(".full-height").find("img").load(function(){
loaded++;
if(loaded ===imgCount){
setFullHeights()
}
});
}
And you would want to call the loadedFullHeights() from docReady instead. This is actually what I ended up using just in case. Got to think ahead you know!
function setFullHeights(){
var par;
var height;
var $ = jQuery;
var heights=[];
var i = 0;
$(".full-height").each(function(){
par =$(this).parent();
height = $(par).height();
var tPad = Number($(par).css('padding-top').replace('px',''));
var bPad = Number($(par).css('padding-bottom').replace('px',''));
height -= tPad+bPad;
heights[i]=height;
i++;
});
for(ii in heights){
$(".full-height").eq(ii).css('height', heights[ii]+'px');
}
}
I found this query which helped me find my locked table and query causing the issue.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
I encountered a similar problem when I was using the below to obtain connection factory
ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");
Its resolved when I changed it to the below
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");
The below then showed that my Q size was increasing..
http://:8161/admin/queues.jsp
It could be a security access on your machine, are you running Pageant (which is a putty agent)?
These are present by default as rownames
when you create a data.frame
.
R> df = data.frame('a' = rnorm(10), 'b' = runif(10), 'c' = letters[1:10])
R> df
a b c
1 0.3336944 0.39746731 a
2 -0.2334404 0.12242856 b
3 1.4886706 0.07984085 c
4 -1.4853724 0.83163342 d
5 0.7291344 0.10981827 e
6 0.1786753 0.47401690 f
7 -0.9173701 0.73992239 g
8 0.7805941 0.91925413 h
9 0.2469860 0.87979229 i
10 1.2810961 0.53289335 j
and you can access them via the rownames
command.
R> rownames(df)
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10"
if you need them as numbers, simply coerce to numeric by adding as.numeric
, as in as.numeric(rownames(df))
.
You don't need to add them, as if you know what you are looking for (say item df$c == 'i'
, you can use the which command:
R> which(df$c =='i')
[1] 9
or if you don't know the column
R> which(df == 'i', arr.ind=T)
row col
[1,] 9 3
you may access the element using df[9, 'c']
, or df$c[9]
.
If you wanted to add them you could use df$rownumber <- as.numeric(rownames(df))
, though this may be less robust than df$rownumber <- 1:nrow(df)
as there are cases when you might have assigned to rownames
so they will no longer be the default index numbers (the which command will continue to return index numbers even if you do assign to rownames
).
I had this issue with sites running on XAMPP with private hostnames. Not so private, it turns out! They were all domain.dev
, which Google has now registered as a private gTLD, and is forcing HSTS at the domain level. Changed every virtual host to .devel
(eugh), restarted Apache and all is now well.
There might a case where some other argline setup or plugin in pom may be overriding jacoco execution order setup.
argLine set to -javaagent:/Users/davea/.m2/repository/org/jacoco/org.jacoco.agent/0.6.2.201302030002/org.jacoco.agent-0.6.2.201302030002-runtime.jar=destfile=/Users/davea/Dropbox/workspace/myproject/target/jacoco.exec
One of the example
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<forkCount>5</forkCount>
<reuseForks>true</reuseForks>
<argLine>-Dnet.sf.ehcache.disabled=true</argLine>
</configuration>
</plugin>
After getting rid of argLine from these plugins, jacoco started to work normally.
(Neither IN
nor ANY
is an "operator". A "construct" or "syntax element".)
Logically, quoting the manual:
IN
is equivalent to= ANY
.
But there are two syntax variants of IN
and two variants of ANY
. Details:
IN
taking a set is equivalent to = ANY
taking a set, as demonstrated here:
But the second variant of each is not equivalent to the other. The second variant of the ANY
construct takes an array (must be an actual array type), while the second variant of IN
takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:
ANY
is more versatileThe ANY
construct is far more versatile, as it can be combined with various operators, not just =
. Example:
SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');
For a big number of values, providing a set scales better for each:
Related:
"Find rows where id
is in the given array":
SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);
Inversion: "Find rows where id
is not in the array":
SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}'); -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));
All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[]
.
Rows with id IS NULL
do not pass either of these expressions. To include NULL
values additionally:
SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;
Note: This is not a duplicate, because the OP is aware that the image from cv2.imread
is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)
To illustrate, I've opened up this same color JPEG image:
once using the conversion
img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
and another by loading it in gray scale mode
img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom
I've summed up the diff too to see
import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image
I tried all cv2.imread()
modes
Among all the IMREAD_
modes for cv2.imread()
, only IMREAD_COLOR
and IMREAD_ANYCOLOR
can be converted using COLOR_BGR2GRAY
, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE
The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)
Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.
In brief, let's not mix the versions and types in the processing pipeline.
So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)
On linux you can do the following:
$cmd = 'nohup nice -n 10 php -f php/file.php > log/file.log & printf "%u" $!';
$pid = shell_exec($cmd);
This will execute the command at the command prompty and then just return the PID, which you can check for > 0 to ensure it worked.
This question is similar: Does PHP have threading?
I guess you can use @CollectionOfElements
(for hibernate/jpa 1) / @ElementCollection
(jpa 2) to map a collection of "entity properties" to a List
in entity
.
You can create the EntityProperty
type and annotate it with @Embeddable
hg commit --amend
:This also works from TortoiseHG's GUI (I'm using v2.5):
Swich to the 'Commit' view or, in the workbench view, select the 'working directory' entry. The 'Commit' button has an option named 'Amend current revision' (click the button's drop-down arrow to find it).
||
||
\/
Caveat emptor:
This extra option will only be enabled if the mercurial version is at least 2.2.0, and if the current revision is not public, is not a patch and has no children. [...]
Clicking the button will call 'commit --amend' to 'amend' the revision.
More info about this on the THG dev channel
You are using a wrong format in your cookie file. As curl documentation states, it uses an old Netscape cookie file format, which is different from the format used by web browsers. If you need to create a curl cookie file manually, this post should help you. In your example the file should contain following line
127.0.0.1 FALSE / FALSE 0 USER_TOKEN in
having 7 TAB-separated fields meaning domain, tailmatch, path, secure, expires, name, value.
For folks that have programmed in nodeJs before, particularly using expressJS. I think of .ashx
as a middleware that calls the next
function. While .aspx
will be the controller that actually responds to the request either around res.redirect
, res.send
or whatever.
This is extension of answer provided by Ranjith
I would suggest, you to choose a choice-parameter build, and specify the branches that you would like to build. Active Choice Parameter
And after that, you can specify branches to build. Branch to Build
Now, when you would build your project, you would be provided with "Build with Parameters, where you can choose the branch to build"
You can also write a groovy script to fetch all your branches to in active choice parameter.
In our case the solution to this problem did not involve the "ISAPI and CGI Restrictions" settings. The error started occuring after operations staff had upgraded the server to .NET 4.5 by accident, then downgraded to .NET 4.0 again. This caused some of the IIS websites to forget their respective correct application pools, and it caused some of the application pools to switch from .NET Framework 4.0 to 2.0. Changing these settings back fixed the problem.
As of Aug 29, 2013, Github's documentation claim that:
Warning: Project pages subpaths like http://username.github.io/projectname will not be redirected to a project's custom domain.
I tried almost all of this. but still couldn't work. Finally I found it was because of 24bitmap problems. If you tried some bitmap which less than 24bit. Most of those above methods should work.
You can use spawns to format phone numbers in Android. This solution is better than the others because it does not change input text. Formatting remains purely visual.
implementation 'com.googlecode.libphonenumber:libphonenumber:7.0.4'
Formatter class:
open class PhoneNumberFormatter : TransformationMethod {
private val mFormatter: AsYouTypeFormatter = PhoneNumberUtil.getInstance().getAsYouTypeFormatter(Locale.getDefault().country)
override fun getTransformation(source: CharSequence, view: View): CharSequence {
val formatted = format(source)
if (source is Spannable) {
setSpans(source, formatted)
return source
}
return formatted
}
override fun onFocusChanged(view: View?, sourceText: CharSequence?, focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) = Unit
private fun setSpans(spannable: Spannable, formatted: CharSequence): CharSequence {
spannable.clearSpawns()
var charterIndex = 0
var formattedIndex = 0
var spawn = ""
val spawns: List<String> = spannable
.map {
spawn = ""
charterIndex = formatted.indexOf(it, formattedIndex)
if (charterIndex != -1){
spawn = formatted.substring(formattedIndex, charterIndex-1)
formattedIndex = charterIndex+1
}
spawn
}
spawns.forEachIndexed { index, sequence ->
spannable.setSpan(CharterSpan(sequence), index, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
return formatted
}
private fun Spannable.clearSpawns() =
this
.getSpans(0, this.length, CharterSpan::class.java)
.forEach { this.removeSpan(it) }
private fun format(spannable: CharSequence): String {
mFormatter.clear()
var formated = ""
for (i in 0 until spannable.length) {
formated = mFormatter.inputDigit(spannable[i])
}
return formated
}
private inner class CharterSpan(private val charters: String) : ReplacementSpan() {
var space = 0
override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
space = Math.round(paint.measureText(charters, 0, charters.length))
return Math.round(paint.measureText(text, start, end)) + space
}
override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
space = Math.round(paint.measureText(charters, 0, charters.length))
canvas.drawText(text, start, end, x + space, y.toFloat(), paint)
canvas.drawText(charters, x, y.toFloat(), paint)
}
}
}
Uasge:
editText.transformationMethod = formatter
You need to use the document.getElementsByClassName('class_name');
and dont forget that the returned value is an array of elements so if you want the first one use:
document.getElementsByClassName('class_name')[0]
UPDATE
Now you can use:
document.querySelector(".class_name")
to get the first element with the class_name
CSS class (null
will be returned if non of the elements on the page has this class name)
or document.querySelectorAll(".class_name")
to get a NodeList of elements with the class_name
css class (empty NodeList will be returned if non of. the elements on the the page has this class name).
I don't have R on this computer, but here is a crack at it. You can use par
to display multiple plots in a window, or like this to prompt for a click before displaying the next page.
plotfun <- function(col)
plot(data[ , col], ylab = names(data[col]), type = "l")
par(ask = TRUE)
sapply(seq(1, length(data), 1), plotfun)
For me above solutions didn't work when setting a specific color or property.
This did work:
let attributes = [
NSFontAttributeName : UIFont(name: "Helvetica Neue", size: 12.0)!,
NSUnderlineStyleAttributeName : 1,
NSForegroundColorAttributeName : UIColor.darkGrayColor(),
NSTextEffectAttributeName : NSTextEffectLetterpressStyle,
NSStrokeWidthAttributeName : 3.0]
var atriString = NSAttributedString(string: "My Attributed String", attributes: attributes)
Input one number at a time, and check whether the following character is ,
. If so, discard it.
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string str = "1,2,3,4,5,6";
std::vector<int> vect;
std::stringstream ss(str);
for (int i; ss >> i;) {
vect.push_back(i);
if (ss.peek() == ',')
ss.ignore();
}
for (std::size_t i = 0; i < vect.size(); i++)
std::cout << vect[i] << std::endl;
}
No, it needs three operands. That's why they're called ternary operators.
However, for what you have as your example, you can do this:
if(condition) x = true;
Although it's safer to have braces if you need to add more than one statement in the future:
if(condition) { x = true; }
Edit: Now that you mention the actual code in which your question applies to:
if(!defaults.slideshowWidth)
{ defaults.slideshowWidth = obj.find('img').width()+'px'; }
Not a lot of "slick" going on so far:
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
When you initialize an array with a number, it creates an array with the length
set to that value so that the array appears to contain that many undefined
elements. Though some Array instance methods skip array elements without values, .join()
doesn't, or at least not completely; it treats them as if their value is the empty string. Thus you get a copy of the zero character (or whatever "z" is) between each of the array elements; that's why there's a + 1
in there.
Example usage:
pad(10, 4); // 0010
pad(9, 4); // 0009
pad(123, 4); // 0123
pad(10, 4, '-'); // --10
$emit
It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope
listeners. The event life cycle starts at the scope on which $emit
was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.
$broadcast
It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope
listeners. The event life cycle starts at the scope on which $broadcast
was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.
$on
It listen on events of a given type. It can catch the event dispatched by $broadcast
and $emit
.
Visual demo:
Demo working code, visually showing scope tree (parent/child relationship):
http://plnkr.co/edit/am6IDw?p=preview
Demonstrates the method calls:
$scope.$on('eventEmitedName', function(event, data) ...
$scope.broadcastEvent
$scope.emitEvent
You just use an ImageButton and make the background whatever you want and set the icon as the src.
<ImageButton
android:id="@+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/album_icon"
android:background="@drawable/round_button" />
Issue because connection establishment or communication with a client failed to complete within the allotted time interval. This may be a result of network or system delays.
git tag -d your_tag_name
git push origin :refs/tags/your_tag_name
The first line deletes your_tag_name
from local repo and second line deletes your_tag_name
from remote repo.
For those who use GitHub, one more step is needed: discarding draft.
You would normally do a Response.Flush followed by a Response.Close, but for some reason the iTextSharp library doesn't seem to like this. The data doesn't make it through and Adobe thinks the PDF is corrupt. Leave out the Response.Close function and see if your results are better:
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-disposition", "attachment; filename=file.pdf"); // open in a new window
Response.OutputStream.Write(outStream.GetBuffer(), 0, outStream.GetBuffer().Length);
Response.Flush();
// For some reason, if we close the Response stream, the PDF doesn't make it through
//Response.Close();
Look in TomcatDirectory/logs/catalina.out for the logs. If the logs are too long, delete the catalina.out file and rerun the app.
In my case, I only updated the custom view.
// DO NOT LIKE THIS
customView.layoutIfNeeded() // Change to view.layoutIfNeeded()
UIView.animate(withDuration: 0.5) {
customViewConstraint.constant = 100.0
customView.layoutIfNeeded() // Change to view.layoutIfNeeded()
}
Thank you OP for your question, and Roman for your answer. I had to search a bit to find this; I hope the following helps others.
Python 2.7
See: https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html
import numpy as np
from StringIO import StringIO
data = "1, abc , 2\n 3, xxx, 4"
print type(data)
"""
<type 'str'>
"""
print '\n', np.genfromtxt(StringIO(data), delimiter=",", dtype="|S3", autostrip=True)
"""
[['1' 'abc' '2']
['3' 'xxx' '4']]
"""
print '\n', type(data)
"""
<type 'str'>
"""
print '\n', np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
"""
[[ 1. nan 2.]
[ 3. nan 4.]]
"""
Python 3.5:
import numpy as np
from io import StringIO
import io
data = "1, abc , 2\n 3, xxx, 4"
#print(data)
"""
1, abc , 2
3, xxx, 4
"""
#print(type(data))
"""
<class 'str'>
"""
#np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
# TypeError: Can't convert 'bytes' object to str implicitly
print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", dtype="|S3", autostrip=True))
"""
[[b'1' b'abc' b'2']
[b'3' b'xxx' b'4']]
"""
print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", autostrip=True))
"""
[[ 1. nan 2.]
[ 3. nan 4.]]
"""
Aside:
dtype="|Sx", where x = any of { 1, 2, 3, ...}:
dtypes. Difference between S1 and S2 in Python
"The |S1 and |S2 strings are data type descriptors; the first means the array holds strings of length 1, the second of length 2. ..."
GLib is a portability/utility library for C which forms the basis of the GTK+ graphical toolkit. It can be used as a standalone library.
It contains portable wrappers for managing directories. See Glib File Utilities documentation for details.
Personally, I wouldn't even consider writing large amounts of C-code without something like GLib behind me. Portability is one thing, but it's also nice to get data structures, thread helpers, events, mainloops etc. for free
Jikes, I'm almost starting to sound like a sales guy :) (don't worry, glib is open source (LGPL) and I'm not affiliated with it in any way)
There is an option in search => file and shortcut is Ctrl+H. Go for further refer follow link. This is work fine with Eclipse Neon
Is there a way to find/replace across an entire project in Eclipse?
Here are the primary differences between using System.out
/.err
/.in
and System.console()
:
System.console()
returns null if your application is not run in a terminal (though you can handle this in your application)System.console()
provides methods for reading password without echoing charactersSystem.out
and System.err
use the default platform encoding, while the Console
class output methods use the console encodingThis latter behaviour may not be immediately obvious, but code like this can demonstrate the difference:
public class ConsoleDemo {
public static void main(String[] args) {
String[] data = { "\u250C\u2500\u2500\u2500\u2500\u2500\u2510",
"\u2502Hello\u2502",
"\u2514\u2500\u2500\u2500\u2500\u2500\u2518" };
for (String s : data) {
System.out.println(s);
}
for (String s : data) {
System.console().writer().println(s);
}
}
}
On my Windows XP which has a system encoding of windows-1252 and a default console encoding of IBM850, this code will write:
???????
?Hello?
???????
+-----+
¦Hello¦
+-----+
Note that this behaviour depends on the console encoding being set to a different encoding to the system encoding. This is the default behaviour on Windows for a bunch of historical reasons.
I didn't try this but I think it works in all browsers:
target="_parent"
Other way for get a list just local branch is:
git branch -a | grep -v 'remotes'
This is similar to the answer I posted on: Preview a Git push
Drop these functions into your Bash profile:
You can use this like:
This will work with any branch.
function parse_git_branch {
git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'
}
function gbin {
echo branch \($1\) has these commits and \($(parse_git_branch)\) does not
git log ..$1 --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local
}
function gbout {
echo branch \($(parse_git_branch)\) has these commits and \($1\) does not
git log $1.. --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local
}
You could write an extension method:
public static void InvokeIfRequired(this Control c, Action<Control> action)
{
if(c.InvokeRequired)
{
c.Invoke(new Action(() => action(c)));
}
else
{
action(c);
}
}
And use it like this:
object1.InvokeIfRequired(c => { c.Visible = true; });
EDIT: As Simpzon points out in the comments you could also change the signature to:
public static void InvokeIfRequired<T>(this T c, Action<T> action)
where T : Control
Spring's Web MVC framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for upload files. The default handler is a very simple Controller interface, just offering a ModelAndView handleRequest(request,response) method. This can already be used for application controllers, but you will prefer the included implementation hierarchy, consisting of, for example AbstractController, AbstractCommandController and SimpleFormController. Application controllers will typically be subclasses of those. Note that you can choose an appropriate base class: if you don't have a form, you don't need a form controller. This is a major difference to Struts
Create hash as:
h = Hash.new
=> {}
Now insert into hash as:
h = Hash["one" => 1]
I have solved same issue with following:
export M2_HOME=/usr/share/maven
Follow the steps :
Go to File -> Settings -> Appearance&Behaviour -> Appearance
Change the theme to whatever you like.
Then restart the android studio.
You need to put it in the join
clause, not the where
:
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON
user_category_subscriptions.category_id = categories.category_id
and user_category_subscriptions.user_id =1
See, with an inner join
, putting a clause in the join
or the where
is equivalent. However, with an outer join
, they are vastly different.
As a join
condition, you specify the rowset that you will be joining to the table. This means that it evaluates user_id = 1
first, and takes the subset of user_category_subscriptions
with a user_id
of 1
to join to all of the rows in categories
. This will give you all of the rows in categories
, while only the categories
that this particular user has subscribed to will have any information in the user_category_subscriptions
columns. Of course, all other categories
will be populated with null
in the user_category_subscriptions
columns.
Conversely, a where
clause does the join, and then reduces the rowset. So, this does all of the joins and then eliminates all rows where user_id
doesn't equal 1
. You're left with an inefficient way to get an inner join
.
Hopefully this helps!
There's a situation where the cell has white space, you can't see it, use
df['col'].replace(' ', np.nan, inplace=True)
to replace white space as NaN, then
df= df.dropna(subset=['col'])
Is it possible to simulate abstract base class in JavaScript?
Certainly. There are about a thousand ways to implement class/instance systems in JavaScript. Here is one:
// Classes magic. Define a new class with var C= Object.subclass(isabstract),
// add class members to C.prototype,
// provide optional C.prototype._init() method to initialise from constructor args,
// call base class methods using Base.prototype.call(this, ...).
//
Function.prototype.subclass= function(isabstract) {
if (isabstract) {
var c= new Function(
'if (arguments[0]!==Function.prototype.subclass.FLAG) throw(\'Abstract class may not be constructed\'); '
);
} else {
var c= new Function(
'if (!(this instanceof arguments.callee)) throw(\'Constructor called without "new"\'); '+
'if (arguments[0]!==Function.prototype.subclass.FLAG && this._init) this._init.apply(this, arguments); '
);
}
if (this!==Object)
c.prototype= new this(Function.prototype.subclass.FLAG);
return c;
}
Function.prototype.subclass.FLAG= new Object();
var cat = new Animal('cat');
That's not really an abstract base class of course. Do you mean something like:
var Animal= Object.subclass(true); // is abstract
Animal.prototype.say= function() {
window.alert(this._noise);
};
// concrete classes
var Cat= Animal.subclass();
Cat.prototype._noise= 'meow';
var Dog= Animal.subclass();
Dog.prototype._noise= 'bark';
// usage
var mycat= new Cat();
mycat.say(); // meow!
var mygiraffe= new Animal(); // error!
This will keep the right aspect ratio.
public ImageIcon scaleImage(ImageIcon icon, int w, int h)
{
int nw = icon.getIconWidth();
int nh = icon.getIconHeight();
if(icon.getIconWidth() > w)
{
nw = w;
nh = (nw * icon.getIconHeight()) / icon.getIconWidth();
}
if(nh > h)
{
nh = h;
nw = (icon.getIconWidth() * nh) / icon.getIconHeight();
}
return new ImageIcon(icon.getImage().getScaledInstance(nw, nh, Image.SCALE_DEFAULT));
}
Sure, you could use an enum. Would something like the following work?
enum Alignment {
LEFT,
RIGHT
}
private static String drawCellValue(int maxCellLength, String cellValue, Alignment alignment) { }
If you wanted to use a boolean, you could rename the align parameter to something like alignLeft. I agree that this implementation is not as clean, but if you don't anticipate a lot of changes and this is not a public interface, it might be a good choice.
Use saveas:
h=figure;
plot(x,y,'-bs','Linewidth',1.4,'Markersize',10);
% ...
saveas(h,name,'fig')
saveas(h,name,'jpg')
This way, the figure is plotted, and automatically saved to '.jpg' and '.fig'. You don't need to wait for the plot to appear and click 'save as' in the menu. Way to go if you need to plot/save a lot of figures.
If you really do not want to let the plot appear (it has to be loaded anyway, can't avoid that, else there is also nothing to save), you can hide it:
h=figure('visible','off')
If you installed SQL Server with the default collation options, you might find that the following queries return the same results:
CREATE TABLE mytable
(
mycolumn VARCHAR(10)
)
GO
SET NOCOUNT ON
INSERT mytable VALUES('Case')
GO
SELECT mycolumn FROM mytable WHERE mycolumn='Case'
SELECT mycolumn FROM mytable WHERE mycolumn='caSE'
SELECT mycolumn FROM mytable WHERE mycolumn='case'
You can alter your query by forcing collation at the column level:
SELECT myColumn FROM myTable
WHERE myColumn COLLATE Latin1_General_CS_AS = 'caSE'
SELECT myColumn FROM myTable
WHERE myColumn COLLATE Latin1_General_CS_AS = 'case'
SELECT myColumn FROM myTable
WHERE myColumn COLLATE Latin1_General_CS_AS = 'Case'
-- if myColumn has an index, you will likely benefit by adding
-- AND myColumn = 'case'
SELECT DATABASEPROPERTYEX('<database name>', 'Collation')
As changing this setting can impact applications and SQL queries, I would isolate this test first. From SQL Server 2000, you can easily run an ALTER TABLE statement to change the sort order of a specific column, forcing it to be case sensitive. First, execute the following query to determine what you need to change it back to:
EXEC sp_help 'mytable'
The second recordset should contain the following information, in a default scenario:
Column_Name Collation
mycolumn SQL_Latin1_General_CP1_CI_AS
Whatever the 'Collation' column returns, you now know what you need to change it back to after you make the following change, which will force case sensitivity:
ALTER TABLE mytable
ALTER COLUMN mycolumn VARCHAR(10)
COLLATE Latin1_General_CS_AS
GO
SELECT mycolumn FROM mytable WHERE mycolumn='Case'
SELECT mycolumn FROM mytable WHERE mycolumn='caSE'
SELECT mycolumn FROM mytable WHERE mycolumn='case'
If this screws things up, you can change it back, simply by issuing a new ALTER TABLE statement (be sure to replace my COLLATE identifier with the one you found previously):
ALTER TABLE mytable
ALTER COLUMN mycolumn VARCHAR(10)
COLLATE SQL_Latin1_General_CP1_CI_AS
If you are stuck with SQL Server 7.0, you can try this workaround, which might be a little more of a performance hit (you should only get a result for the FIRST match):
SELECT mycolumn FROM mytable WHERE
mycolumn = 'case' AND
CAST(mycolumn AS VARBINARY(10)) = CAST('Case' AS VARBINARY(10))
SELECT mycolumn FROM mytable WHERE
mycolumn = 'case' AND
CAST(mycolumn AS VARBINARY(10)) = CAST('caSE' AS VARBINARY(10))
SELECT mycolumn FROM mytable WHERE
mycolumn = 'case' AND
CAST(mycolumn AS VARBINARY(10)) = CAST('case' AS VARBINARY(10))
-- if myColumn has an index, you will likely benefit by adding
-- AND myColumn = 'case'
You can't return two (or multiple) columns in your subquery to do the comparison in the WHERE A_ID IN (subquery)
clause - which column is it supposed to compare A_ID
to? Your subquery must only return the one column needed for the comparison to the column on the other side of the IN
. So the query needs to be of the form:
SELECT * From ThisTable WHERE ThisColumn IN (SELECT ThatColumn FROM ThatTable)
You also want to add sorting so you can select just from the top rows, but you don't need to return the COUNT as a column in order to do your sort; sorting in the ORDER
clause is independent of the columns returned by the query.
Try something like this:
select count(distinct dNum)
from myDB.dbo.AQ
where A_ID in
(SELECT DISTINCT TOP (0.1) PERCENT A_ID
FROM myDB.dbo.AQ
WHERE M > 1 and B = 0
GROUP BY A_ID
ORDER BY COUNT(DISTINCT dNum) DESC)
dotnet nuget locals all --clear
Download and install the NuGet command line tool.
nuget locals all -clear
del %LOCALAPPDATA%\NuGet\Cache\*.nupkg /q
(can be used in a .bat
file)
rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg
Or 'quiet' mode (without error messages):
rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg 2> $null
%userprofile%\.nuget\packages
~/.nuget/
%windir%/ServiceProfiles/[account under build service runs]\AppData\Local\NuGet\Cache
Example:
C:\Windows\ServiceProfiles\NetworkService\AppData\Local\NuGet\Cache
This answer is a rollup of all the existing answers for your convenience
If you use fragments you can prepare XML layout and than stratch critical elements programmatically
int thirdScreenWidth = (int)(screenWidth *0.33);
View view = inflater.inflate(R.layout.fragment_second, null);
View _container = view.findViewById(R.id.rim1container);
_container.getLayoutParams().width = thirdScreenWidth * 2;
_container = view.findViewById(R.id.rim2container);
_container.getLayoutParams().width = screenWidth - thirdScreenWidth * 2;
_container = view.findViewById(R.id.rim3container);
_container.getLayoutParams().width = screenWidth - thirdScreenWidth * 2;
This layout for 3 equal columns. First element takes 2x2 Result in the picture
try this:
sudo pip install -i https://testpypi.python.org/pypi psycopg2==2.7b2
.. this is especially helpful if you're running into egg error
on aws ec2 instances if you run into gcc error; try this
1. sudo yum install gcc python-setuptools python-devel postgresql-devel
2. sudo su -
3. sudo pip install psycopg2
If you are uploading your files through GIT from your local machine then you can use the same command you are using in your local machine while you are connected to your live server using BASH or something like.You can use this as like you use locally.
php artisan cache:clear
php artisan route:cache
It should work.
PHPSESSID
reveals you are using PHP. If you don't want this you can easily change the name using the session.name
in your php.ini file or using the session_name()
function.
string cat = "cat";
string human = "human";
cout << cat.compare(human) << endl;
This code will give -1 as a result. This is due to the first non-matching character of the compared string 'h' is lower or appears after 'c' in alphabetical order, even though the compared string, 'human' is longer than 'cat'.
I find the return value described in cplusplus.com is more accurate which are-:
0 : They compare equal
<0 : Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.
more than 0 : Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.
Moreover, IMO cppreference.com's description is simpler and so far best describe to my own experience.
negative value if
*this
appears before the character sequence specified by the arguments, in lexicographical orderzero if both character sequences compare equivalent
positive value if
*this
appears after the character sequence specified by the arguments, in lexicographical order
I think most of the answers here were confusing especially those saying that mutex can be released only by the process that holds it but semaphore can be signaled by ay process. The above line is kind of vague in terms of semaphore. To understand we should know that there are two kinds of semaphore one is called counting semaphore and the other is called a binary semaphore. In counting semaphore handles access to n number of resources where n can be defined before the use. Each semaphore has a count variable, which keeps the count of the number of resources in use, initially, it is set to n. Each process that wishes to uses a resource performs a wait() operation on the semaphore (thereby decrementing the count). When a process releases a resource, it performs a release() operation (incrementing the count). When the count becomes 0, all the resources are being used. After that, the process waits until the count becomes more than 0. Now here is the catch only the process that holds the resource can increase the count no other process can increase the count only the processes holding a resource can increase the count and the process waiting for the semaphore again checks and when it sees the resource available it decreases the count again. So in terms of binary semaphore, only the process holding the semaphore can increase the count, and count remains zero until it stops using the semaphore and increases the count and other process gets the chance to access the semaphore.
The main difference between binary semaphore and mutex is that semaphore is a signaling mechanism and mutex is a locking mechanism, but binary semaphore seems to function like mutex that creates confusion, but both are different concepts suitable for a different kinds of work.
If it's a static method, you can call it by using the class name in place of an object.
This is what I did:
How about something like this...
Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")
Do While Not rs.EOF
Debug.Print rs("PictureLocation") & " - " & rs("ID")
rs.MoveNext
Loop
Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.
One option is to replace table with CSS4 flex divs:
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
That works in new browsers i.e. IE11+ see table at the bottom of the article.
Of course there is. Check out mysql_query
, and mysql_fetch_row
if you use MySQL.
Example from PHP manual:
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
This will work
<div style="width:800px;">
<div style="width:300px; float:left;"></div>
<div style="width:300px; float:right;"></div>
</div>
<div style="clear: both;"></div>
pure javascript no jQuery
function sah() {_x000D_
$("#div2").attr("disabled", "disabled").off('click');_x000D_
var x1=$("#div2").hasClass("disabledDiv");_x000D_
_x000D_
(x1==true)?$("#div2").removeClass("disabledDiv"):$("#div2").addClass("disabledDiv");_x000D_
sah1(document.getElementById("div1"));_x000D_
_x000D_
}_x000D_
_x000D_
function sah1(el) {_x000D_
try {_x000D_
el.disabled = el.disabled ? false : true;_x000D_
} catch (E) {}_x000D_
if (el.childNodes && el.childNodes.length > 0) {_x000D_
for (var x = 0; x < el.childNodes.length; x++) {_x000D_
sah1(el.childNodes[x]);_x000D_
}_x000D_
}_x000D_
}
_x000D_
#div2{_x000D_
padding:5px 10px;_x000D_
background-color:#777;_x000D_
width:150px;_x000D_
margin-bottom:20px;_x000D_
}_x000D_
.disabledDiv {_x000D_
pointer-events: none;_x000D_
opacity: 0.4;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div id="div1">_x000D_
<div id="div2" onclick="alert('Hello')">Click me</div>_x000D_
<input type="text" value="SAH Computer" />_x000D_
<br />_x000D_
<input type="button" value="SAH Computer" />_x000D_
<br />_x000D_
<input type="radio" name="sex" value="Male" />Male_x000D_
<Br />_x000D_
<input type="radio" name="sex" value="Female" />Female_x000D_
<Br />_x000D_
</div>_x000D_
<Br />_x000D_
<Br />_x000D_
<input type="button" value="Click" onclick="sah()" />
_x000D_
I know everybody is ethically against this, but I understand there are reasons of practical joking where this is desired. I think Chrome took a solid stance on this by enforcing a mandatory one second separation time between alert messages. This gives the visitor just enough time to close the page or refresh if they're stuck on an annoying prank site.
So to answer your question, it's all a matter of timing. If you alert more than once per second, Chrome will create that checkbox. Here's a simple example of a workaround:
var countdown = 99;
function annoy(){
if(countdown>0){
alert(countdown+" bottles of beer on the wall, "+countdown+" bottles of beer! Take one down, pass it around, "+(countdown-1)+" bottles of beer on the wall!");
countdown--;
// Time must always be 1000 milliseconds, 999 or less causes the checkbox to appear
setTimeout(function(){
annoy();
}, 1000);
}
}
// Don't alert right away or Chrome will catch you
setTimeout(function(){
annoy();
}, 1000);
I don’t think that’s a good idea. Even if you find an appropriate regular expression (maybe using Unicode character properties), this wouldn’t prevent users from entering pseudo-names like John Doe, Max Mustermann (there even is a person with that name), Abcde Fghijk or Ababa Bebebe.
I use this syntax
Map<Integer, List<Choice>> choiceMap =
choices.stream().collect(Collectors.groupingBy(choice -> choice.getName()));
This will produce a string 96 characters in length, from the Base64 range (uppers, lowers, numbers, + and /). Adding 3 "NEWID()" will increase the length by 32, with no Base64 padding (=).
SELECT
CAST(
CONVERT(NVARCHAR(MAX),
CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
,2)
AS XML).value('xs:base64Binary(xs:hexBinary(.))', 'VARCHAR(MAX)') AS StringValue
If you are applying this to a set, make sure to introduce something from that set so that the NEWID() is recomputed, otherwise you'll get the same value each time:
SELECT
U.UserName
, LEFT(PseudoRandom.StringValue, LEN(U.Pwd)) AS FauxPwd
FROM Users U
CROSS APPLY (
SELECT
CAST(
CONVERT(NVARCHAR(MAX),
CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), U.UserID) -- Causes a recomute of all NEWID() calls
,2)
AS XML).value('xs:base64Binary(xs:hexBinary(.))', 'VARCHAR(MAX)') AS StringValue
) PseudoRandom
http://joda-time.sourceforge.net/quickstart.html
Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:
* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class
class Model_File_update(APIView):
parser_classes = (MultiPartParser, FormParser)
permission_classes = [IsAuthenticated] # it will check if the user is authenticated or not
authentication_classes = [JSONWebTokenAuthentication] # it will authenticate the person by JSON web token
def put(self, request):
id = request.GET.get('id')
obj = Model.objects.get(id=id)
serializer = Model_Upload_Serializer(obj, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=200)
else:
return Response(serializer.errors, status=400)
The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.
For example:
char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;
execvp(cmd, argv); //This will run "ls -la" as if it were a command
I am using Azure DevOps to deploy the containerize applications, I am easily manage to overcome this problem by using the build ID
Everytime its builds and generate the new Build ID, I use this build ID as tag for docker image here is example
imagename:buildID
once your image is build (CI) successfully, in CD pipeline in deployment yml file I have give image name as
imagename:env:buildID
here evn:buildid is the azure devops variable which having value of build ID.
so now every time I have new changes to build(CI) and deploy(CD).
please comment if you need build definition for CI/CD.
I used Calumah's function posted above, but I did run into an issue with his code as poisted.
The rows are joined with a semicolon
csv.push(row.join(';'));
but the link generated has "text/csv" as the content type
Maybe in Windows that isn't a problem, but in Excel for Mac that throws things off. I changed the array join to a comma and it worked perfect.
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
Not sure from what version, but I use 1.3.14 and you can just use:
window.location.href = '/employee/1';
No need to inject $location
or $window
in the controller and no need to get the current host address.
String test = "HELLO HOW ARE YOU";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test);
The above code wont work .....
so put the below code by convert to lower then apply the function
String test = "HELLO HOW ARE YOU";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test.ToLower());
Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:
new Integer(null);
Although it might be tempting to expose an object on the isolated scope of a directive to facilitate communicating with it, doing can lead to confusing "spaghetti" code, especially if you need to chain this communication through a couple levels (controller, to directive, to nested directive, etc.)
We originally went down this path but after some more research found that it made more sense and resulted in both more maintainable and readable code to expose events and properties that a directive will use for communication via a service then using $watch on that service's properties in the directive or any other controls that would need to react to those changes for communication.
This abstraction works very nicely with AngularJS's dependency injection framework as you can inject the service into any items that need to react to those events. If you look at the Angular.js file, you'll see that the directives in there also use services and $watch in this manner, they don't expose events over the isolated scope.
Lastly, in the case that you need to communicate between directives that are dependent on one another, I would recommend sharing a controller between those directives as the means of communication.
AngularJS's Wiki for Best Practices also mentions this:
Only use .$broadcast(), .$emit() and .$on() for atomic events Events that are relevant globally across the entire app (such as a user authenticating or the app closing). If you want events specific to modules, services or widgets you should consider Services, Directive Controllers, or 3rd Party Libs
- $scope.$watch() should replace the need for events
- Injecting services and calling methods directly is also useful for direct communication
- Directives are able to directly communicate with each other through directive-controllers
The conversion in SQL server fails sometimes not because of the Date or Time formats used, It is Merely because you are trying to store wrong data that is not acceptable to the system.
Example:
Create Table MyTable (MyDate);
Insert Into MyTable(MyDate) Values ('2015-02-29');
The SQL server will throw the following error:
Conversion failed when converting date and/or time from character string.
The reason for this error is simply there is no such date (Feb-29) in Year (2015).
Flushing the session forces Hibernate to synchronize the in-memory state of the Session
with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you:
Allowing to explicitly flush the Session
gives finer control that may be required in some circumstances (to get an ID assigned, to control the size of the Session,...).
This is an iterable function without yield
. It make use of the iter
function and a closure which keeps it's state in a mutable (list
) in the enclosing scope for python 2.
def count(low, high):
counter = [0]
def tmp():
val = low + counter[0]
if val < high:
counter[0] += 1
return val
return None
return iter(tmp, None)
For Python 3, closure state is kept in an immutable in the enclosing scope and nonlocal
is used in local scope to update the state variable.
def count(low, high):
counter = 0
def tmp():
nonlocal counter
val = low + counter
if val < high:
counter += 1
return val
return None
return iter(tmp, None)
Test;
for i in count(1,10):
print(i)
1
2
3
4
5
6
7
8
9
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
My solution was to use DOSKEY to set up some aliases to for the commands I use the most:
DOSKEY svc=TortoiseProc.exe /command:commit /path:.
DOSKEY svu=TortoiseProc.exe /command:update /path:.
DOSKEY svl=TortoiseProc.exe /command:log /path:.
DOSKEY svd=TortoiseProc.exe /command:diff /path:$*
Google "doskey persist" for tips on how to set up a .cmd file that runs every time you open the command prompt like a .*rc file in Unix.
you can run raw query like this way too.
DB::table('setting_colleges')->first();
You'd better ping 127.0.0.1. Windows ping pauses for one second between pings so you if you want to sleep for 10 seconds, use
ping -n 11 127.0.0.1 > nul
This way you don't need to worry about unexpected early returns (say, there's no default route and the 123.45.67.89 is instantly known to be unreachable.)
check the /tmp/tmp/server.pid
there is a pid inside.
Usually, I ill do "kill -9 THE_PID" in the cmd
select sequence_owner, sequence_name from dba_sequences;
DBA_SEQUENCES -- all sequences that exist
ALL_SEQUENCES -- all sequences that you have permission to see
USER_SEQUENCES -- all sequences that you own
Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES
, there is no SEQUENCE_OWNER
column in USER_SEQUENCES
.
Just a quick addition, because I tackled the same issue today:
With Go 1.13 it is possible to use the new isZero()
method:
if reflect.ValueOf(session).IsZero() {
// do stuff...
}
I didn't test this regarding performance, but I guess that this should be faster, than comparing via reflect.DeepEqual()
.