"Change to if (typeof $next == 'object' && $next.length) $next[0].offsetWidth" -did not help. if you convert Bootstrap 3 to php(for WordPress theme), when adding WP_Query ($loop = new WP_Query( $args );) insert $count = 0;. And and at the end before endwhile; add $count++;.
My descriptions for the three:
position: absolute
descendents)position: absolute
ones) without scrolling.Then there is also:
I created a more comprehensive and cleaner version that some people might find useful for remembering which name corresponds to which value. I used Chrome Dev Tool's color code and labels are organized symmetrically to pick up analogies faster:
Note 1: clientLeft
also includes the width of the vertical scroll
bar if the direction of the text is set to right-to-left (since the
bar is displayed to the left in that case)
Note 2: the outermost line represents the closest positioned parent
(an element whose position
property is set to a value different than
static
or initial
). Thus, if the direct container isn’t a positioned
element, then the line doesn’t represent the first container in
the hierarchy but another element higher in the hierarchy. If no
positioned parent is found, the browser will take the html
or body
element as reference
Hope somebody finds it useful, just my 2 cents ;)
As this is specifically tagged for jQuery -
$("#myElement")[0].getBoundingClientRect();
or
$("#myElement").get(0).getBoundingClientRect();
(These are functionally identical, in some older browsers .get()
was slightly faster)
Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...
Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect()
calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...
FireFox have problemes for getBBox(), i need to do this in vanillaJS.
I've a better Way and is the same result as real svg.getBBox() function !
With this good post : Get the real size of a SVG/G element
var el = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle
console.log( rect.width );
console.log( rect.height);
You can also get this error if you don't specify center
or zoom
in your map options.
Responsive resist jQuery marquee simple plugin. Tutorial:
// start plugin
(function($){
$.fn.marque = function(options, callback){
// check callback
if(typeof callback == 'function'){
callback.call(this);
} else{
console.log("second argument (callback) is not a function");
// throw "callback must be a function"; //only if callback for some reason is required
// return this; //only if callback for some reason is required
}
//set and overwrite default functions
var defOptions = $.extend({
speedPixelsInOneSecound: 150, //speed will behave same for different screen where duration will be different for each size of the screen
select: $('.message div'),
clickSelect: '', // selector that on click will redirect user ... (optional)
clickUrl: '' //... to this url. (optional)
}, options);
//Run marque plugin
var windowWidth = $(window).width();
var textWidth = defOptions.select.outerWidth();
var duration = (windowWidth + textWidth) * 1000 / defOptions.speedPixelsInOneSecound;
var startingPosition = (windowWidth + textWidth);
var curentPosition = (windowWidth + textWidth);
var speedProportionToLocation = curentPosition / startingPosition;
defOptions.select.css({'right': -(textWidth)});
defOptions.select.show();
var animation;
function marquee(animation){
curentPosition = (windowWidth + defOptions.select.outerWidth());
speedProportionToLocation = curentPosition / startingPosition;
animation = defOptions.select.animate({'right': windowWidth+'px'}, duration * speedProportionToLocation, "linear", function(){
defOptions.select.css({'right': -(textWidth)});
});
}
var play = setInterval(marquee, 200);
//add onclick behaviour
if(defOptions.clickSelect != '' && defOptions.clickUrl != ''){
defOptions.clickSelect.click(function(){
window.location.href = defOptions.clickUrl;
});
}
return this;
};
}(jQuery));
// end plugin
Use this custom jQuery plugin as bellow:
//use example
$(window).marque({
speedPixelsInOneSecound: 150, // spped pixels/secound
select: $('.message div'), // select an object on which you want to apply marquee effects.
clickSelect: $('.message'), // select clicable object (optional)
clickUrl: 'services.php' // define redirection url (optional)
});
An HTML response from the web server normally indicates that an error page has been served instead of the response from the WCF service. My first suggestion would be to check that the user you're running the WCF client under has access to the resource.
I know this is an old post but I had the same question but didn't find an answer that set the element fixed relative to a parent div
. The scroll bar on medium.com is a great pure CSS solution for setting something position: fixed;
relative to a parent element instead of the viewport (kinda*). It is achieved by setting the parent div
to position: relative;
and having a button wrapper with position: absolute;
and the button of course is position: fixed;
as follows:
<div class="wrapper">
<div class="content">
Your long content here
</div>
<div class="button-wrapper">
<button class="button">This is your button</button>
</div>
</div>
<style>
.wrapper {
position: relative;
}
.button-wrapper {
position: absolute;
right: 0;
top: 0;
width: 50px;
}
.button {
position: fixed;
top: 0;
width: 50px;
}
</style>
*Since fixed elements don't scroll with the page the vertical position will still be relative to the viewport but the horizontal position is relative to the parent with this solution.
My original answer was written in 2009. While it still works, I'd like to update it for 2017. Browsers can still behave differently. I trust the jQuery team to do a great job at maintaining cross-browser consistency. However, it's not necessary to include the entire library. In the jQuery source, the relevant portion is found on line 37 of dimensions.js. Here it is extracted and modified to work standalone:
function getWidth() {_x000D_
return Math.max(_x000D_
document.body.scrollWidth,_x000D_
document.documentElement.scrollWidth,_x000D_
document.body.offsetWidth,_x000D_
document.documentElement.offsetWidth,_x000D_
document.documentElement.clientWidth_x000D_
);_x000D_
}_x000D_
_x000D_
function getHeight() {_x000D_
return Math.max(_x000D_
document.body.scrollHeight,_x000D_
document.documentElement.scrollHeight,_x000D_
document.body.offsetHeight,_x000D_
document.documentElement.offsetHeight,_x000D_
document.documentElement.clientHeight_x000D_
);_x000D_
}_x000D_
_x000D_
console.log('Width: ' + getWidth() );_x000D_
console.log('Height: ' + getHeight() );
_x000D_
Since all browsers behave differently, you'll need to test for values first, and then use the correct one. Here's a function that does this for you:
function getWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
if (document.documentElement && document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
}
if (document.body) {
return document.body.clientWidth;
}
}
and similarly for height:
function getHeight() {
if (self.innerHeight) {
return self.innerHeight;
}
if (document.documentElement && document.documentElement.clientHeight) {
return document.documentElement.clientHeight;
}
if (document.body) {
return document.body.clientHeight;
}
}
Call both of these in your scripts using getWidth()
or getHeight()
. If none of the browser's native properties are defined, it will return undefined
.
'vb.net
'Extended file stributes
'visual basic .net sample
Dim sFile As Object
Dim oShell = CreateObject("Shell.Application")
Dim oDir = oShell.Namespace("c:\temp")
For i = 0 To 34
TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(oDir, i) & vbCrLf
For Each sFile In oDir.Items
TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(sFile, i) & vbCrLf
Next
TextBox1.Text = TextBox1.Text & vbCrLf
Next
If you are just looping through 10k rows in column A, then dump the row into a variant array and then loop through that.
You can then either add the elements to a new array (while adding rows when needed) and using Transpose() to put the array onto your range in one move, or you can use your iterator variable to track which row you are on and add rows that way.
Dim i As Long
Dim varray As Variant
varray = Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value
For i = 1 To UBound(varray, 1)
' do stuff to varray(i, 1)
Next
Here is an example of how you could add rows after evaluating each cell. This example just inserts a row after every row that has the word "foo" in column A. Not that the "+2" is added to the variable i during the insert since we are starting on A2. It would be +1 if we were starting our array with A1.
Sub test()
Dim varray As Variant
Dim i As Long
varray = Range("A2:A10").Value
'must step back or it'll be infinite loop
For i = UBound(varray, 1) To LBound(varray, 1) Step -1
'do your logic and evaluation here
If varray(i, 1) = "foo" Then
'not how to offset the i variable
Range("A" & i + 2).EntireRow.Insert
End If
Next
End Sub
I incurred this error once.
It turns out I had named my program ProgramMame.ccp instead of ProgramName.cpp
easy to do ...
Hope this may help
I see users in comments wondering how to disable cell editing while allowing row deletion : I managed to do this by setting all columns individually to read only, instead of the DataGrid itself.
<DataGrid IsReadOnly="False">
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True"/>
<DataGridTextColumn IsReadOnly="True"/>
</DataGrid.Columns>
</DataGrid>
As an update, for Angular 7, a very good example, loading plus http interceptor, here: https://nezhar.com/blog/create-a-loading-screen-for-angular-apps/.
For version 6, you need a small adjustment when you use Subject. You need to add the generic type.
loadingStatus: Subject<boolean> = new Subject();
I'm using angular material, so instead of a loading text, you can use mat-spinner.
<mat-spinner></mat-spinner>
Update: the code from the previous page will not complete work (regarding the interceptor part), but here you have the complete solution: https://github.com/nezhar/snypy-frontend
And as Miranda recommended into comments, here is also the solution:
The loading screen component:
loading-screen.component.ts
import { Component, ElementRef, ChangeDetectorRef, OnDestroy, AfterViewInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { LoadingScreenService } from '../services/loading-screen.service';
@Component({
selector: 'app-loading-screen',
templateUrl: './loading-screen.component.html',
styleUrls: ['./loading-screen.component.css']
})
export class LoadingScreenComponent implements AfterViewInit, OnDestroy {
loading: boolean = false;
loadingSubscription: Subscription;
constructor(
private loadingScreenService: LoadingScreenService,
private _elmRef: ElementRef,
private _changeDetectorRef: ChangeDetectorRef
) { }
ngAfterViewInit(): void {
this._elmRef.nativeElement.style.display = 'none';
this.loadingSubscription = this.loadingScreenService.loadingStatus.pipe().subscribe(
(status: boolean) => {
this._elmRef.nativeElement.style.display = status ? 'block' : 'none';
this._changeDetectorRef.detectChanges();
}
);
}
ngOnDestroy() {
console.log("inside destroy loading component");
this.loadingSubscription.unsubscribe();
}
}
loading-screen.component.html
<div id="overlay">
<mat-spinner class="content"></mat-spinner>
</div>
loading-screen.component.css
#overlay {
position: fixed; /* Sit on top of the page content */
display: block; /* Hidden by default */
width: 100%; /* Full width (cover the whole page) */
height: 100%; /* Full height (cover the whole page) */
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(60, 138, 255, 0.1); /* Black background with opacity */
opacity: 0.5;
z-index: 2; /* Specify a stack order in case you're using a different order for other elements */
cursor: progress; /* Add a pointer on hover */
}
.content {
position: absolute;
top: 50%;
left: 50%;
font-size: 50px;
color: white;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
}
Don't forget to add the component to your root component. In my case, AppComponent
app.component.html
<app-loading-screen></app-loading-screen>
The service that will manage the component: loading-screen.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoadingScreenService {
constructor() { }
private _loading: boolean = false;
loadingStatus: Subject<boolean> = new Subject();
get loading(): boolean {
console.log("get loading: " + this._loading);
return this._loading;
}
set loading(value) {
console.log("get loading: " + value);
this._loading = value;
this.loadingStatus.next(value);
}
startLoading() {
console.log("startLoading");
this.loading = true;
}
stopLoading() {
console.log("stopLoading");
this.loading = false;
}
}
Here is the http interceptor, which will show/hide the component, using the previous service.
loading-screen-interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { LoadingScreenService } from '../services/loading-screen.service';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
@Injectable()
export class LoadingScreenInterceptor implements HttpInterceptor {
activeRequests: number = 0;
constructor(
private loadingScreenService: LoadingScreenService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("inside interceptor");
if (this.activeRequests === 0) {
this.loadingScreenService.startLoading();
}
this.activeRequests++;
return next.handle(request).pipe(
finalize(() => {
this.activeRequests--;
if (this.activeRequests === 0) {
this.loadingScreenService.stopLoading();
}
})
)
};
}
And in your app.module.ts, don't forget to config the interceptor
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: LoadingScreenInterceptor,
multi: true
}
]
fire this in the browser
http://localhost:8983/solr/update?stream.body=<delete><query>*:*</query></delete>&commit=true
this commmand will delete all the documents in index in solr
I was struggling a lot with different solutions including \vspace{-Xmm} on the top and bottom of the page and dealing with warnings and errors. Finally I found this answer:
You can change the margins of just one or more pages and then restore it to its default:
\usepackage{geometry}
...
...
...
\newgeometry{top=5mm, bottom=10mm} % use whatever margins you want for left, right, top and bottom.
...
... %<The contents of enlarged page(s)>
...
\restoregeometry %so it does not affect the rest of the pages.
...
...
...
PS:
1- This can also fix the following warning:
LaTeX Warning: Float too large for page by ...pt on input line ...
2- For more detailed answer look at this.
3- I just found that this is more elaboration on Kevin Chen's answer.
The browser is trying to convert chucknorris
into hex colour code, because it’s not a valid value.
chucknorris
, everything except c
is not a valid hex value.c00c00000000
.This seems to be an issue primarily with Internet Explorer and Opera (12) as both Chrome (31) and Firefox (26) just ignore this.
P.S. The numbers in brackets are the browser versions I tested on.
On a lighter note
Chuck Norris doesn’t conform to web standards. Web standards conform to him. #BADA55
Several things:
Age
is not an integer - it is a nullable integer type. They are not the same. See the documentation for Nullable<T>
on MSDN for details.
??
is the null coalesce operator, not the ternary operator (actually called the conditional operator).
To check if a nullable type has a value use HasValue
, or check directly against null
:
if(Age.HasValue)
{
// Yay, it does!
}
if(Age == null)
{
// It is null :(
}
With Spring you could easily read it from the resources folder (either main/resources or test/resources):
For example create a file: test/resources/subfolder/sample.json
@Test
public void testReadFile() {
String json = this.readFile("classpath:subfolder/sample.json");
System.out.println(json);
}
public String readFile(String path) {
try {
File file = ResourceUtils.getFile(path);
return new String(Files.readAllBytes(file.toPath()));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I found that this works when run in the Package Manager Console:
dotnet ef migrations list | select -Last 2 | select -First 1 | ForEach-Object { Update-Database -Migration $_ }
You could create a script that makes it easier.
Both answers are wrong. You can. You need to call
$.ajaxSetup({
async: false
});
before your json ajax call. And you can set it to true after call retuns ( if there are other usages of ajax on page if you want them async )
1> Add this namspace. using Newtonsoft.Json.Linq;
2> use this source code.
JObject joResponse = JObject.Parse(response);
JObject ojObject = (JObject)joResponse["response"];
JArray array= (JArray)ojObject ["chats"];
int id = Convert.ToInt32(array[0].toString());
The problem id because of inp.read();
method. Its return single character at a time and because you are storing it into int type of array so that is just storing ascii value of that.
What you can do simply
for(int i=0;i<T;i++) {
String s= inp.readLine();
String[] intValues = inp.readLine().split(" ");
int[] m= new int[2];
m[0]=Integer.parseInt(intValues[0]);
m[1]=Integer.parseInt(intValues[1]);
// Checking whether I am taking the inputs correctly
System.out.println(s);
System.out.println(m[0]);
System.out.println(m[1]);
}
I had the same issue and finally it was resolved by disconnecting from all VPN .
Here's a C# method to do this. Remember to add your own error handling - this mostly assumes that things work for the sake of brevity. It's 4.0+ framework only, but that's mostly because of the optional worksheetNumber
parameter. You can overload the method if you need to support earlier versions.
static void ConvertExcelToCsv(string excelFilePath, string csvOutputFile, int worksheetNumber = 1) {
if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);
// connection string
var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO\"", excelFilePath);
var cnn = new OleDbConnection(cnnStr);
// get schema, then data
var dt = new DataTable();
try {
cnn.Open();
var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (schemaTable.Rows.Count < worksheetNumber) throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet");
string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", "");
string sql = String.Format("select * from [{0}]", worksheet);
var da = new OleDbDataAdapter(sql, cnn);
da.Fill(dt);
}
catch (Exception e) {
// ???
throw e;
}
finally {
// free resources
cnn.Close();
}
// write out CSV data
using (var wtr = new StreamWriter(csvOutputFile)) {
foreach (DataRow row in dt.Rows) {
bool firstLine = true;
foreach (DataColumn col in dt.Columns) {
if (!firstLine) { wtr.Write(","); } else { firstLine = false; }
var data = row[col.ColumnName].ToString().Replace("\"", "\"\"");
wtr.Write(String.Format("\"{0}\"", data));
}
wtr.WriteLine();
}
}
}
This is really just an expansion of BBB's answer which lead to to get my experiment working.
This script will simply create a file /tmp/testfile when you click on the button that says "Open Script".
This requires 3 files.
The File Tree:
root@test:/var/www/html# tree testscript/
testscript/
+-- index.html
+-- testexec.php
+-- test.sh
1. The main WebPage:
root@test:/var/www/html# cat testscript/index.html
<form action="/testscript/testexec.php">
<input type="submit" value="Open Script">
</form>
2. The PHP Page that runs the script and redirects back to the main page:
root@test:/var/www/html# cat testscript/testexec.php
<?php
shell_exec("/var/www/html/testscript/test.sh");
header('Location: http://192.168.1.222/testscript/index.html?success=true');
?>
3. The Script :
root@test:/var/www/html# cat testscript/test.sh
#!/bin/bash
touch /tmp/testfile
I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:
gcc -o exec main.o add.o
But my program is a C++ program. Using the g++
compiler solved my issue:
g++ -o exec main.o add.o
I was always under the impression that gcc
could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.
As the previous comment mentioned you can't do this in Postman. however, I found this Chrome app in the web store. It is very simple, but it's working really well with my local web socket connections.
Only solution that works was create a new conda env with the name you want (you will, unfortunately, delete the old one to keep the name). Then create a new env with a new python version and re-run your install.sh
script with the conda/pip installs (or the yaml file or whatever you use to keep your requirements):
conda remove --name original_name --all
conda create --name original_name python=3.8
sh install.sh # or whatever you usually do to install dependencies
doing conda install python=3.8
doesn't work for me. Also, why do you want 3.6? Move forward with the word ;)
If you want to update the conda version of your previous env what you can also do is the following (more complicated than it should be because you cannot rename envs in conda):
conda create --name temporary_env_name --clone original_env_name
conda deactivate
conda remove --name original_env_name --all # or its alias: `conda env remove --name original_env_name`
conda create --name original_env_name python=3.8 --clone temporary_env_name
now := []byte{0xFF,0xFF,0xFF,0xFF}
nowBuffer := bytes.NewReader(now)
var nowVar uint32
binary.Read(nowBuffer,binary.BigEndian,&nowVar)
fmt.Println(nowVar)
4294967295
def mostCommonElement(list):
count = {} // dict holder
max = 0 // keep track of the count by key
result = None // holder when count is greater than max
for i in list:
if i not in count:
count[i] = 1
else:
count[i] += 1
if count[i] > max:
max = count[i]
result = i
return result
mostCommonElement(["a","b","a","c"]) -> "a"
The best way i found is to override the "ProcessDialogKey" function. This way canceling a open control is still possible because the function is only called when no other control uses the pressed Key.
This is the same behaviour as when setting a CancelButton. Using the KeyDown Event fires always and thus the form would close even when it should cancel the edit of an open editor.
protected override bool ProcessDialogKey(Keys keyData)
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
return true;
}
return base.ProcessDialogKey(keyData);
}
Backend:
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json()); // add a middleware (so that express can parse request.body's json)
app.post('/api/courses', (request, response) => {
response.json(request.body);
});
Frontend:
fetch("/api/courses", {
method: 'POST',
body: JSON.stringify({ hi: 'hello' }), // convert Js object to a string
headers: new Headers({ "Content-Type": "application/json" }) // add headers
});
Make sure your id_rsa file doesn't have any extension like .txt or .rtf. Rich Text Format adds additional characters to your file and those gets added to byte array. Which eventually causes invalid private key error. Long story short, Copy the file, not content.
In PS 7, you can use ConvertFrom-SecureString
and -AsPlainText
:
$UnsecurePassword = ConvertFrom-SecureString -SecureString $SecurePassword -AsPlainText
ConvertFrom-SecureString
[-SecureString] <SecureString>
[-AsPlainText]
[<CommonParameters>]
Explanation from this source was helpful for me:
Concurrency is related to how an application handles multiple tasks it works on. An application may process one task at at time (sequentially) or work on multiple tasks at the same time (concurrently).
Parallelism on the other hand, is related to how an application handles each individual task. An application may process the task serially from start to end, or split the task up into subtasks which can be completed in parallel.
As you can see, an application can be concurrent, but not parallel. This means that it processes more than one task at the same time, but the tasks are not broken down into subtasks.
An application can also be parallel but not concurrent. This means that the application only works on one task at a time, and this task is broken down into subtasks which can be processed in parallel.
Additionally, an application can be neither concurrent nor parallel. This means that it works on only one task at a time, and the task is never broken down into subtasks for parallel execution.
Finally, an application can also be both concurrent and parallel, in that it both works on multiple tasks at the same time, and also breaks each task down into subtasks for parallel execution. However, some of the benefits of concurrency and parallelism may be lost in this scenario, as the CPUs in the computer are already kept reasonably busy with either concurrency or parallelism alone. Combining it may lead to only a small performance gain or even performance loss.
You can always try to kill the process in case you see this kind of issues. You can get the process ID either from PS or from pid file and kill the process.
I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.
Code:
import os
print(os.path.expanduser("~"))
Output Windows:
PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX
Output Linux (Ubuntu):
rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx
I also tested it on Python 2.7.17 and that works too.
The instructions in the official Python documentation worked for me: https://docs.python.org/2/using/windows.html#executing-scripts
Launch a command prompt.
Associate the correct file group with .py scripts:
assoc .py=Python.File
Redirect all Python files to the new executable:
ftype Python.File=C:\Path\to\pythonw.exe "%1" %*
The example shows how to associate the .py extension with the .pyw executable, but it works if you want to associate the .py extension with the Anaconda Python executable. You need administrative rights. The name "Python.File" could be anything, you just have to make sure is the same name in the ftype command. When you finish and before you try double-clicking the .py file, you must change the "Open with" in the file properties. The file type will be now ".py" and it is opened with the Anaconda python.exe.
Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.
So you have to exclude conflict dependencies. Try this:
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
This solved same problem with slf4j and Dozer.
Microsoft's Visual Studio Code text editor has built in support for .md files written in markdown syntax.
The syntax is automatically color-coded inside of the .md file, and a preview window of the rendered markdown can be viewed by pressing Shift+Ctrl+V
(Windows) or Shift+Cmd+V
(Mac).
To see them side-by-side, drag the preview tab to the right side of the editor, or use Ctrl+K V
(Windows) or Cmd+K V
(Mac) instead.
VS Code uses the marked library for parsing, and has Github Flavored Markdown support enabled by default, but it will not display the Github Emoji inline like Github's Atom text editor does.
Also, VS Code supports has several markdown plugins available for extended functionality.
This should do the trick:
image = open("image.png", "wb")
image.write(base64string.decode('base64'))
image.close()
A recursive solution. It's not the most efficient but I find it a bit more readable than the other examples and it doesn't rely on functools.
def deep_get(d, keys):
if not keys or d is None:
return d
return deep_get(d.get(keys[0]), keys[1:])
Example
d = {'meta': {'status': 'OK', 'status_code': 200}}
deep_get(d, ['meta', 'status_code']) # => 200
deep_get(d, ['garbage', 'status_code']) # => None
A more polished version
def deep_get(d, keys, default=None):
"""
Example:
d = {'meta': {'status': 'OK', 'status_code': 200}}
deep_get(d, ['meta', 'status_code']) # => 200
deep_get(d, ['garbage', 'status_code']) # => None
deep_get(d, ['meta', 'garbage'], default='-') # => '-'
"""
assert type(keys) is list
if d is None:
return default
if not keys:
return d
return deep_get(d.get(keys[0]), keys[1:], default)
You are checking whether the string contains all illegal characters. Change the ||
s to &&
s.
Here is an example using pg_basebackup
I chose to go this route because it backs up the entire database cluster (users, databases, etc.).
I'm posting this as a solution on here because it details every step I had to take, feel free to add recommendations or improvements after reading other answers on here and doing some more research.
For Postgres 12 and Ubuntu 18.04 I had to do these actions:
On the server that is currently running the database:
Update pg_hba.conf
, for me located at /etc/postgresql/12/main/pg_hba.conf
Add the following line (substitute 192.168.0.100 with the IP address of the server you want to copy the database to).
host replication postgres 192.168.0.100/32 trust
Update postgresql.conf
, for me located at /etc/postgresql/12/main/postgresql.conf
. Add the following line:
listen_addresses = '*'
Restart postgres:
sudo service postgresql restart
On the host you want to copy the database cluster to:
sudo service postgresql stop
sudo su root
rm -rf /var/lib/postgresql/12/main/*
exit
sudo -u postgres pg_basebackup -h 192.168.0.101 -U postgres -D /var/lib/postgresql/12/main/
sudo service postgresql start
Big picture - stop the service, delete everything in the data directory (mine is in /var/lib/postgreql/12
). The permissions on this directory are drwx------
with user and group postgres
. I could only do this as root
, not even with sudo -u postgres
. I'm unsure why. Ensure you are doing this on the new server you want to copy the database to! You are deleting the entire database cluster.
Make sure to change the IP address from 192.168.0.101
to the IP address you are copying the database from. Copy the data from the original server with pg_basebackup
. Start the service.
Update pg_hba.conf
and postgresql.conf
to match the original server configuration - before you made any changes adding the replication
line and the listen_addresses
line (in my care I had to add the ability to log-in locally via md5 to pg_hba.conf).
Note there are considerations for max_wal_senders
and wal_level
that can be found in the documentation. I did not have to do anything with this.
trim()
will remove all leading and trailing blanks. But be aware: Your string isn't changed. trim()
will return a new string instance instead.
You may want to look into to Simple Logging Facade for Java (SLF4J). It is a facade that wraps around Log4j that doesn't require an initial setup call like Log4j. It is also fairly easy to switch out Log4j for Slf4j as the API differences are minimal.
Your condition id !== 0
will always be different that zero because you are assigning a string value. On pages where the element with id views_slideshow_controls_text_next_slideshow-block
is not found, you will still try to append the img element, which causes the Cannot read property 'appendChild' of null
error.
Instead of assigning a string value, you can assign the DOM element and verify if it exists within the page.
window.onload = function loadContIcons() {
var elem = document.createElement("img");
elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
elem.setAttribute("class", "up_icon");
var container = document.getElementById("views_slideshow_controls_text_next_slideshow-block");
if (container !== null) {
container.appendChild(elem);
} else console.log("aaaaa");
var elem1 = document.createElement("img");
elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
elem1.setAttribute("class", "down_icon");
container = document.getElementById("views_slideshow_controls_text_previous_slideshow-block");
if (container !== null) {
container.appendChild(elem1);
} else console.log("aaaaa");
}
In Oracle you can do this:
SELECT * FROM table1 WHERE (col_a,col_b) IN (SELECT col_x,col_y FROM table2)
set /a number=%random% %% [maximum]-[minimum]
example "
set /a number=%random% %% 100-50
will give a random number between 100 and 50. Be sure to only use one percentage sign as the operand if you are not using the line in a batch script!
If you use WinForms:
Use the AppendText(myTxt)
method on the TextBox
instead (.net 3.5+):
private void button1_Click(object sender, EventArgs e)
{
string sent = chatBox.Text;
displayBox.AppendText(sent);
displayBox.AppendText(Environment.NewLine);
}
Text in itself has typically a low memory footprint (you can say a lot within f.ex. 10kb which is "nothing"). The TextBox does not render all text that is in the buffer, only the visible part so you don't need to worry too much about lag. The slower operations are inserting text. Appending text is relatively fast.
If you need a more complex handling of the content you can use StringBuilder
combined with the textbox. This will give you a very efficient way of handling text.
You could simply get the character length of the current directory, and remove them from your absolute list
setlocal EnableDelayedExpansion
for /L %%n in (1 1 500) do if "!__cd__:~%%n,1!" neq "" set /a "len=%%n+1"
setlocal DisableDelayedExpansion
for /r . %%g in (*.log) do (
set "absPath=%%g"
setlocal EnableDelayedExpansion
set "relPath=!absPath:~%len%!"
echo(!relPath!
endlocal
)
I also wanted to do this, but with a method that receives a BOOL parameter. Wrapping the bool value with NSNumber, FAILED TO PASS THE VALUE. I have no idea why.
So I ended up doing a simple hack. I put the required parameter in another dummy function and call that function using the performSelector, where withObject = nil;
[self performSelector:@selector(dummyCaller:) withObject:nil afterDelay:5.0];
-(void)dummyCaller {
[self myFunction:YES];
}
The way to keep SELECT dbo.fCalculateEstimateDate(647)
call working is:
ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100) AS
Declare @Result varchar(100)
SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
Return @Result
Begin
End
CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100) AS
Begin
<Function Body>
End
star is expanded by Unix shell. Your call is not accessing shell, it's merely trying to remove a file with the name ending with the star
Reference docs of docker: https://docs.docker.com/install/linux/linux-postinstall/#configure-where-the-docker-daemon-listens-for-connections
There are 2 ways in configuring the docker daemon port
1) Configuring at /etc/default/docker file:
DOCKER_OPTS="-H tcp://127.0.0.1:5000 -H unix:///var/run/docker.sock"
2) Configuring at /etc/docker/daemon.json:
{
"debug": true,
"hosts": ["tcp://127.0.0.1:5000", "unix:///var/run/docker.sock"]
}
If the docker default socket is not configured Docker will wait for infinite period.i.e
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
NOTE : BUT DON'T CONFIGURE IN BOTH THE CONFIGURATION FILES, the following error may occur :
Waiting for /var/run/docker.sock
unable to configure the Docker daemon with file /etc/docker/daemon.json: the following directives are specified both as a flag and in the configuration file: hosts: (from flag: [tcp://127.0.0.1:5000 unix:///var/run/docker.sock], from file: tcp://127.0.0.1:5000)
The reason for adding both the user port[ tcp://127.0.0.1:5000] and default docker socket[unix:///var/run/docker.sock] is that the user port enables the access to the docker APIs whereas the default socket enables the CLI. In case the default port[unix:///var/run/docker.sock] is not mentioned in /etc/default/docker file the following error may occur:
# docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
This error is not because that the docker is not running, but because of default docker socket is not enabled.
Once the configuration is enabled restart the docker service and verify the docker port is enabled or not:
# netstat -tunlp | grep -i 5000
tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN 31661/dockerd
Applicable for Docker Version 17.04, may vary with different versions of docker.
If you want to move your commits to an existing branch, it will look like this:
git checkout existingbranch
git merge master
git checkout master
git reset --hard HEAD~3 # Go back 3 commits. You *will* lose uncommitted work.
git checkout existingbranch
You can store uncommitted edits to your stash before doing this, using git stash
. Once complete, you can retrieve the stashed uncommitted edits with git stash pop
WARNING: This method works because you are creating a new branch with the first command: git branch newbranch
. If you want to move commits to an existing branch you need to merge your changes into the existing branch before executing git reset --hard HEAD~3
(see Moving to an existing branch above). If you don't merge your changes first, they will be lost.
Unless there are other circumstances involved, this can be easily done by branching and rolling back.
# Note: Any changes not committed will be lost.
git branch newbranch # Create a new branch, saving the desired commits
git reset --hard HEAD~3 # Move master back by 3 commits (Make sure you know how many commits you need to go back)
git checkout newbranch # Go to the new branch that still has the desired commits
But do make sure how many commits to go back. Alternatively, you can instead of HEAD~3
, simply provide the hash of the commit (or the reference like origin/master) you want to "revert back to" on the master (/current) branch, e.g:
git reset --hard a1b2c3d4
*1 You will only be "losing" commits from the master branch, but don't worry, you'll have those commits in newbranch!
WARNING: With Git version 2.0 and later, if you later git rebase
the new branch upon the original (master
) branch, you may need an explicit --no-fork-point
option during the rebase to avoid losing the carried-over commits. Having branch.autosetuprebase always
set makes this more likely. See John Mellor's answer for details.
You can get an input value without adding 'onChange' function.
Just add to the input element a 'ref attr:
And then use this.refs to get the input value when you need it.
I wanted to add one more point is, if you are storing a really large number like 902054990011312 then one can easily see the difference of INT(20)
and BIGINT(20)
. It is advisable to store in BIGINT
.
For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly
and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.
This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.
To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.
cc -DDISPLAY_STRING demo.c
If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.
#define TERMINAL "/dev/ttyUSB0"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
int set_interface_attribs(int fd, int speed)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error from tcgetattr: %s\n", strerror(errno));
return -1;
}
cfsetospeed(&tty, (speed_t)speed);
cfsetispeed(&tty, (speed_t)speed);
tty.c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8; /* 8-bit characters */
tty.c_cflag &= ~PARENB; /* no parity bit */
tty.c_cflag &= ~CSTOPB; /* only need 1 stop bit */
tty.c_cflag &= ~CRTSCTS; /* no hardware flowcontrol */
/* setup for non-canonical mode */
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
tty.c_oflag &= ~OPOST;
/* fetch bytes as they become available */
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 1;
if (tcsetattr(fd, TCSANOW, &tty) != 0) {
printf("Error from tcsetattr: %s\n", strerror(errno));
return -1;
}
return 0;
}
void set_mincount(int fd, int mcount)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error tcgetattr: %s\n", strerror(errno));
return;
}
tty.c_cc[VMIN] = mcount ? 1 : 0;
tty.c_cc[VTIME] = 5; /* half second timer */
if (tcsetattr(fd, TCSANOW, &tty) < 0)
printf("Error tcsetattr: %s\n", strerror(errno));
}
int main()
{
char *portname = TERMINAL;
int fd;
int wlen;
char *xstr = "Hello!\n";
int xlen = strlen(xstr);
fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0) {
printf("Error opening %s: %s\n", portname, strerror(errno));
return -1;
}
/*baudrate 115200, 8 bits, no parity, 1 stop bit */
set_interface_attribs(fd, B115200);
//set_mincount(fd, 0); /* set to pure timed read */
/* simple output */
wlen = write(fd, xstr, xlen);
if (wlen != xlen) {
printf("Error from write: %d, %d\n", wlen, errno);
}
tcdrain(fd); /* delay for output */
/* simple noncanonical input */
do {
unsigned char buf[80];
int rdlen;
rdlen = read(fd, buf, sizeof(buf) - 1);
if (rdlen > 0) {
#ifdef DISPLAY_STRING
buf[rdlen] = 0;
printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
unsigned char *p;
printf("Read %d:", rdlen);
for (p = buf; rdlen-- > 0; p++)
printf(" 0x%x", *p);
printf("\n");
#endif
} else if (rdlen < 0) {
printf("Error from read: %d: %s\n", rdlen, strerror(errno));
} else { /* rdlen == 0 */
printf("Timeout from read\n");
}
/* repeat read to get full message */
} while (1);
}
For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.
Answering normajeans' question about setting default value. Create a defaults object with same properties and merge with the arguments object
If using ES6:
function yourFunction(args){
let defaults = {opt1: true, opt2: 'something'};
let params = {...defaults, ...args}; // right-most object overwrites
console.log(params.opt1);
}
Older Browsers using Object.assign(target, source):
function yourFunction(args){
var defaults = {opt1: true, opt2: 'something'};
var params = Object.assign(defaults, args) // args overwrites as it is source
console.log(params.opt1);
}
I wrote a function (debug_display
) which can print, arrays, objects, and file info in pretty way.
<?php
function debug_display($var,$show = false) {
if($show) { $dis = 'block'; }else { $dis = 'none'; }
ob_start();
echo '<div style="display:'.$dis.';text-align:left; direction:ltr;"><b>Idea Debug Method : </b>
<pre>';
if(is_bool($var)) {
echo $var === TRUE ? 'Boolean(TRUE)' : 'Boolean(FALSE)';
}else {
if(FALSE == empty($var) && $var !== NULL && $var != '0') {
if(is_array($var)) {
echo "Number of Indexes: " . count($var) . "\n";
print_r($var);
} elseif(is_object($var)) {
print_r($var);
} elseif(@is_file($var)){
$stat = stat($var);
$perm = substr(sprintf('%o',$stat['mode']), -4);
$accesstime = gmdate('Y/m/d H:i:s', $stat['atime']);
$modification = gmdate('Y/m/d H:i:s', $stat['mtime']);
$change = gmdate('Y/m/d H:i:s', $stat['ctime']);
echo "
file path : $var
file size : {$stat['size']} Byte
device number : {$stat['dev']}
permission : {$perm}
last access time was : {$accesstime}
last modified time was : {$modification}
last change time was : {$change}
";
}elseif(is_string($var)) {
print_r(htmlentities(str_replace("\t", ' ', $var)));
} else {
print_r($var);
}
}else {
echo 'Undefined';
}
}
echo '</pre>
</div>';
$output = ob_get_contents();
ob_end_clean();
echo $output;
unset($output);
}
If one really wanted to they could make there own version of scanf()
like so:
import java.util.ArrayList;
import java.util.Scanner;
public class Testies {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<String> strings = new ArrayList<String>();
// get input
System.out.println("Give me input:");
scanf(strings, nums);
System.out.println("Ints gathered:");
// print numbers scanned in
for(Integer num : nums){
System.out.print(num + " ");
}
System.out.println("\nStrings gathered:");
// print strings scanned in
for(String str : strings){
System.out.print(str + " ");
}
System.out.println("\nData:");
for(int i=0; i<strings.size(); i++){
System.out.println(nums.get(i) + " " + strings.get(i));
}
}
// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> nums){
Scanner getLine = new Scanner(System.in);
Scanner input = new Scanner(getLine.nextLine());
while(input.hasNext()){
// get integers
if(input.hasNextInt()){
nums.add(input.nextInt());
}
// get strings
else if(input.hasNext()){
strings.add(input.next());
}
}
}
// pass it a string for input
public static void scanf(String in, ArrayList<String> strings, ArrayList<Integer> nums){
Scanner input = (new Scanner(in));
while(input.hasNext()){
// get integers
if(input.hasNextInt()){
nums.add(input.nextInt());
}
// get strings
else if(input.hasNext()){
strings.add(input.next());
}
}
}
}
Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them. Also, hasNext()
should probably be at the bottom of the if-else if
sequence since hasNext()
will return true for all of the data in the string.
Output:
Give me input:
apples 8 9 pears oranges 5
Ints gathered:
8 9 5
Strings gathered:
apples pears oranges
Data:
8 apples
9 pears
5 oranges
Probably not the best example; but, the point is that Scanner
implements the Iterator
class. Making it easy to iterate through the scanners input using the hasNext<datatypehere>()
methods; and then storing the input.
You can get a link to a specific item in the app store or iTunes through the link maker at: http://itunes.apple.com/linkmaker/
Here is an example that sorts by the header. This table is dynamic and changes with the JSON size.
I was able to build a dynamic table off of some other people's examples and documentation. http://jsfiddle.net/lastlink/v7pszemn/1/
<tr>
<th class="{{header}}" ng-repeat="(header, value) in items[0]" ng-click="changeSorting(header)">
{{header}}
<i ng-class="selectedCls2(header)"></i>
</tr>
<tbody>
<tr ng-repeat="row in pagedItems[currentPage] | orderBy:sort.sortingOrder:sort.reverse">
<td ng-repeat="cell in row">
{{cell}}
</td>
</tr>
Although the columns are out of order, on my .NET project they are in order.
The HTTP POST payload is just a flat bunch of bytes. Django (like most frameworks) decodes it into a dictionary from either URL encoded parameters, or MIME-multipart encoding. If you just dump the JSON data in the POST content, Django won't decode it. Either do the JSON decoding from the full POST content (not the dictionary); or put the JSON data into a MIME-multipart wrapper.
In short, show the JavaScript code. The problem seems to be there.
OFFLINE SOLUTION - Haversine Algorithm
In Javascript
var _eQuatorialEarthRadius = 6378.1370;
var _d2r = (Math.PI / 180.0);
function HaversineInM(lat1, long1, lat2, long2)
{
return (1000.0 * HaversineInKM(lat1, long1, lat2, long2));
}
function HaversineInKM(lat1, long1, lat2, long2)
{
var dlong = (long2 - long1) * _d2r;
var dlat = (lat2 - lat1) * _d2r;
var a = Math.pow(Math.sin(dlat / 2.0), 2.0) + Math.cos(lat1 * _d2r) * Math.cos(lat2 * _d2r) * Math.pow(Math.sin(dlong / 2.0), 2.0);
var c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
var d = _eQuatorialEarthRadius * c;
return d;
}
var meLat = -33.922982;
var meLong = 151.083853;
var result1 = HaversineInKM(meLat, meLong, -32.236457779983745, 148.69094705162837);
var result2 = HaversineInKM(meLat, meLong, -33.609020205923713, 150.77061469270831);
C#
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var meLat = -33.922982;
double meLong = 151.083853;
var result1 = HaversineInM(meLat, meLong, -32.236457779983745, 148.69094705162837);
var result2 = HaversineInM(meLat, meLong, -33.609020205923713, 150.77061469270831);
Console.WriteLine(result1);
Console.WriteLine(result2);
}
static double _eQuatorialEarthRadius = 6378.1370D;
static double _d2r = (Math.PI / 180D);
private static int HaversineInM(double lat1, double long1, double lat2, double long2)
{
return (int)(1000D * HaversineInKM(lat1, long1, lat2, long2));
}
private static double HaversineInKM(double lat1, double long1, double lat2, double long2)
{
double dlong = (long2 - long1) * _d2r;
double dlat = (lat2 - lat1) * _d2r;
double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);
double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));
double d = _eQuatorialEarthRadius * c;
return d;
}
}
Reference: https://en.wikipedia.org/wiki/Great-circle_distance
this is answer for your question.
GridViewRow gvr = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
int RowIndex = gvr.RowIndex;
Step1: add permission on android manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Step2: onCreate() method
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_MEDIA);
} else {
readDataExternal();
}
Step3: override onRequestPermissionsResult method to get callback
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_MEDIA:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
readDataExternal();
}
break;
default:
break;
}
}
Note: readDataExternal() is method to get data from external storage.
Thanks.
I think the better solution is to place these lines in your vimrc file
set backupdir=~/vimtmp//,.
set directory=~/vimtmp//,.
The first line is for backup files, the second line for swap files. The double slash at the end ensures that there is no conflict in case of two files having the same name, see comments (at the time of this edit this option is only honored for swap files, not yet for backup files). The ,.
allow vim
to use the current directory if the former doesn't exist.
You have to create a directory in your home directory called vimtmp for this to work. Also, check that backups are enabled in your config (add set backup
if not).
That way you get the benefit of both worlds, you don't have to see the files, but if something does get futzed you can go get your backup file from vimtmp. Don't forget to clean the directory out every now and then.
For any system except IIS this is quite enough to define site self URL:
$siteURL='http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].'/';
or
$siteURL='http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].'/';
depends on what you exactly want: HTTP_HOST vs. SERVER_NAME
Other possible solution:
tv.setText(Integer.toString(a1)); // where a1 - int value
The structures as well as all other symbols in Core Graphics and other APIs have become cleaner and also include parameter names. https://developer.apple.com/reference/coregraphics#symbols
CGRect(x: Int, y: Int, width: Int, height: Int)
CGVector(dx: Int, dy: Int)
CGPoint(x: Double, y: Double)
CGSize(width: Int, height: Int)
CGPoint Example:
let newPoint = stackMid.convert(CGPoint(x: -10, y: 10), to: self)
CGVector Example:
self.physicsWorld.gravity = CGVector(dx: 0, dy: gravity)
CGSize Example:
hero.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 16, height: 18))
CGRect Example:
let back = SKShapeNode(rect: CGRect(x: 0-120, y: 1024-200-30, width: 240, height: 140), cornerRadius: 20)
Apple Blog
Swift syntax and API renaming changes in Swift 3 make the language feel more natural, and provide an even more Swift-y experience when calling Cocoa frameworks. Popular frameworks Core Graphics and Grand Central Dispatch have new, much cleaner interfaces in Swift.
You can't change img
tag's src
attribute using CSS
. Possible using Javascript onmouseover()
event handler.
HTML:
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover='hover()'/>
Javascript:
function hover() {
document.getElementById("my-img").src = "http://dummyimage.com/100x100/eb00eb/fff";
}
You should be able to do this just fine:
$.ajax({
url: 'controller/myaction',
data: JSON.stringify({
myKey: myArray
}),
success: function(data) { /* Whatever */ }
});
Then your action method would be like so:
public ActionResult(List<int> myKey)
{
// Do Stuff
}
For you, it looks like you just need to stringify your values. The JSONValueProvider in MVC will convert that back into an IEnumerable for you.
try Array.FindIndex(myArray, x => x.Contains("author"));
I found another handy solution, which avoids rebuilding all components again and again, in this article: http://bitstopixels.blogspot.ca/2017/04/react-native-windows-10-eperm-operation.html
react-native run-android
react-native run-android
to complete giving you the BUILD SUCCESSFUL message. (The app will be launched with a red error screen complaining connecting to server failed. Don't panic.)react-native start
to start the React Packager, this is the server indicated in the error message of the previous stepYou can check your g++
by command:
which g++
g++ --version
this will tell you which complier is currently it is pointing.
To switch to g++
4.7 (assuming that you have installed it in your machine),run:
sudo update-alternatives --config gcc
There are 2 choices for the alternative gcc (providing /usr/bin/gcc).
Selection Path Priority Status
------------------------------------------------------------
0 /usr/bin/gcc-4.6 60 auto mode
1 /usr/bin/gcc-4.6 60 manual mode
* 2 /usr/bin/gcc-4.7 40 manual mode
Then select 2
as selection(My machine already pointing to g++
4.7,so the *)
Once you switch the complier then again run g++ --version
to check the switching has happened correctly.
Now compile your program with
g++ -std=c++11 your_file.cpp -o main
synchronized(list) {
for (Object o : list) {}
}
In order to install Android Studio on Ubuntu Studio 14.04 and derivatives, do the following:
Step 1: Open a terminal using the Dash or pressing Ctrl + Alt + T
keys.
Step 2: If you have not, add that repository with the following command:
sudo add-apt-repository ppa:paolorotolo/android-studio
Step 3: Update the APT with the command:
sudo apt-get update
Step 4: Now install the program with the command:
sudo apt-get install android-studio
Step 5: Once installed, run the program by typing in Dash:
studio
It's quite easy. Just write this, for example:
npm install -g [email protected]
Or:
npm install -g npm@latest // For the last stable version
npm install -g npm@next // For the most recent release
Just finish it up.
string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";
DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
DataSet ds = new DataSet();
using (SqlCommand cmd = new SqlCommand(
sqlCommand, new SqlConnection(connectionString)))
{
cmd.Connection.Open();
DataTable table = new DataTable();
table.Load(cmd.ExecuteReader());
ds.Tables.Add(table);
}
return ds;
}
Your syntax is pretty screwy.
Change this:
input:not(disabled)not:[type="submit"]:focus{
to:
input:not(:disabled):not([type="submit"]):focus{
Seems that many people don't realize :enabled
and :disabled
are valid CSS selectors...
It is a basic law that Strings in java are immutable and case sensitive.
Note first that a double
is a binary fraction and does not really have decimal places.
If you need decimal places, use a BigDecimal
, which has a setScale()
method for truncation, or use DecimalFormat
to get a String
.
ES6:
function params(data) {_x000D_
return Object.keys(data).map(key => `${key}=${encodeURIComponent(data[key])}`).join('&');_x000D_
}_x000D_
_x000D_
console.log(params({foo: 'bar'}));_x000D_
console.log(params({foo: 'bar', baz: 'qux$'}));
_x000D_
Another way to turn off CSRF that won't render a null session is to add:
skip_before_action :verify_authenticity_token
in your Rails Controller. This will ensure you still have access to session info.
Again, make sure you only do this in API controllers or in other places where CSRF protection doesn't quite apply.
Add a new Production Certificate here, then download the .cer file and double click it to add it to Keychain.
All will be fine now, don't forget to restart Xcode!!!
If your server is called SERVERX for example, this is how I did it...
EXEC sp_serveroption 'SERVERX', 'DATA ACCESS', TRUE;
DECLARE @CMD VARCHAR(1000);
DECLARE @StudentID CHAR(10);
SET @StudentID = 'STUDENT01';
SET @CMD = 'SELECT * FROM OPENQUERY([SERVERX], ''SET FMTONLY OFF; SET NOCOUNT ON; EXECUTE MYDATABASE.dbo.MYSTOREDPROC ' + @StudentID + ''') WHERE SOMEFIELD = SOMEVALUE';
EXEC (@CMD);
To check this worked, I commented out the EXEC()
command line and replaced it with SELECT @CMD
to review the command before trying to execute it! That was to make sure all the correct number of single-quotes were in the right place. :-)
I hope that helps someone.
You need to store it in a String
variable first before displaying it like so:
String Txt = TxtBoxContent.getText();
System.out.println(Txt);
I had the exact same problem, this - "meta http-equiv="X-UA-Compatible" content="IE=7">" works great in IE8 and IE9, but not in IE10. There is a bug in the server browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10) aren't within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript.
My thanks to Scott Hanselman for this fix.
Here is the link -
This MS KP fix just adds missing files to the asp.net on your server. I installed it and rebooted my server and it now works perfectly. I would have thought that MS would have given this fix a wider distribution.
Rick
var calc = '<span style="display:none; margin:0 0 0 -999px">' + $('.move').text() + '</span>';
In addition to @tadman's answer I removed the wrappers in /usr/local/bin
as well as the file /etc/profile.d/rvm
.
The wrappers include:
erb
gem
irb
rake
rdoc
ri
ruby
testrb
When I write debug.write("") in the code, it outputs in the "Immediate window", not "Output window".
You can try it. For displaying the "Immediate" window (Debug ? Window ? Immediate).
I found another relatively easy solution for your question.
As you can see from the FragmentPagerAdapter source code, the fragments managed by FragmentPagerAdapter
store in the FragmentManager
under the tag generated using:
String tag="android:switcher:" + viewId + ":" + index;
The viewId
is the container.getId()
, the container
is your ViewPager
instance. The index
is the position of the fragment. Hence you can save the object id to the outState
:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("viewpagerid" , mViewPager.getId() );
}
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
if (savedInstanceState != null)
viewpagerid=savedInstanceState.getInt("viewpagerid", -1 );
MyFragmentPagerAdapter titleAdapter = new MyFragmentPagerAdapter (getSupportFragmentManager() , this);
mViewPager = (ViewPager) findViewById(R.id.pager);
if (viewpagerid != -1 ){
mViewPager.setId(viewpagerid);
}else{
viewpagerid=mViewPager.getId();
}
mViewPager.setAdapter(titleAdapter);
If you want to communicate with this fragment, you can get if from FragmentManager
, such as:
getSupportFragmentManager().findFragmentByTag("android:switcher:" + viewpagerid + ":0")
You can add a watchpoint for each variable you're interested in.
A watchpoint is a special breakpoint that stops the execution of an application whenever the value of a given expression changes, without specifying where it might occur. Unlike breakpoints (which are line-specific), watchpoints are associated with files. They take effect whenever a specified condition is true, regardless of when or where it occurred. You can set a watchpoint on a global variable by highlighting the variable in the editor, or by selecting it in the Outline view.
Google will eventually block your IP when you exceed a certain amount of requests.
git reset --hard HEAD
git fetch --all
git reset --hard origin/your_branch
script1.py
title="Hello world"
script2.py is where we using script1 variable
Method 1:
import script1
print(script1.title)
Method 2:
from script1 import title
print(title)
Mysql has a client-only set of utilities:
Mysql client shell https://dev.mysql.com/downloads/shell/
Other command line utilities https://dev.mysql.com/downloads/utilities/
Mac OSX version available.
Looks like you missed a few closing tags and you nshould have "http://" on the front of an external URL. Also, you should move your styles to external style sheets instead of using inline styles.
.box{
float:right;
}
.box a img{
vertical-align: middle;
border: 0px;
}
<div class="box">
<a href="<?php echo "http://www.someotherwebsite.com"; ?>">
<img src="<?php echo url::file_loc('img'); ?>media/img/twitter.png" alt="Image Decription">
</a>
</div>
As noted in other comments, it may be easier to use straight HTML, depending on your exact setup.
<div class="box">
<a href="http://www.someotherwebsite.com">
<img src="file_location/media/img/twitter.png" alt="Image Decription">
</a>
</div>
String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
LocalDateTime zdt = LocalDateTime.parse(dateTime,dtf);
LocalDateTime now = LocalDateTime.now();
ZoneId zone = ZoneId.of("Asia/Kolkata");
ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
long a= zdt.toInstant(zoneOffSet).toEpochMilli();
Log.d("time","---"+a);
you can get zone id form this a link!
var data = $('<div>').html('[{"Id":1,"Name":"Name}]')[0].textContent;
that should parse all the encoded values you need.
SELECT
p.fullname AS 'Fullname',
SUBSTRING_INDEX(p.fullname, ' ', 1) AS 'Firstname',
SUBSTRING(p.fullname, LOCATE(' ',p.fullname),
(LENGTH(p.fullname) - (LENGTH(SUBSTRING_INDEX(p.fullname, ' ', 1)) + LENGTH(SUBSTRING_INDEX(p.fullname, ' ', -1))))
) AS 'Middlename',
SUBSTRING_INDEX(p.fullname, ' ', -1) AS 'Lastname',
(LENGTH(p.fullname) - LENGTH(REPLACE(p.fullname, ' ', '')) + 1) AS 'Name Qt'
FROM people AS p
LIMIT 100;
Explaining:
Find firstname and lastname are easy, you have just to use SUBSTR_INDEX function Magic happens in middlename, where was used SUBSTR with Locate to find the first space position and LENGTH of fullname - (LENGTH firstname + LENGTH lastname) to get all the middlename.
Note that LENGTH of firstname and lastname were calculated using SUBSTR_INDEX
Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:
public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
$result = $this->model->with($with);
$dataSet = $result->where($where)
// Conditionally use $orderBy if not empty
->when(!empty($orderBy), function ($query) use ($orderBy) {
// Break $orderBy into pairs
$pairs = array_chunk($orderBy, 2);
// Iterate over the pairs
foreach ($pairs as $pair) {
// Use the 'splat' to turn the pair into two arguments
$query->orderBy(...$pair);
}
})
->paginate($limit)
->appends(Input::except('page'));
return $dataSet;
}
Now, you can make your call like this:
$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);
REPLACE(REPLACE(a.CUST_ADDRESS1,CHR(10),' '),CHR(13),' ') as ADDRESS
You are trying to use . as a . not as the wildcard for any character. Use \.
instead to indicate a period.
The best way using background with gradient as it does not increase app size of your app images are poison for android app so try to use it less instead of using one color as a background you can use multiple colors in one background.
Here is a very basic but modern implementation of required radio buttons with native HTML5 validation:
fieldset {
display: block;
margin-left: 0;
margin-right: 0;
padding-top: 0;
padding-bottom: 0;
padding-left: 0;
padding-right: 0;
border: none;
}
body {font-size: 15px; font-family: serif;}
input {
background: transparent;
border-radius: 0px;
border: 1px solid black;
padding: 5px;
box-shadow: none!important;
font-size: 15px; font-family: serif;
}
input[type="submit"] {padding: 5px 10px; margin-top: 5px;}
label {display: block; padding: 0 0 5px 0;}
form > div {margin-bottom: 1em; overflow: auto;}
.hidden {
opacity: 0;
position: absolute;
pointer-events: none;
}
.checkboxes label {display: block; float: left;}
input[type="radio"] + span {
display: block;
border: 1px solid black;
border-left: 0;
padding: 5px 10px;
}
label:first-child input[type="radio"] + span {border-left: 1px solid black;}
input[type="radio"]:checked + span {background: silver;}
_x000D_
<form>
<div>
<label for="name">Name (optional)</label>
<input id="name" type="text" name="name">
</div>
<fieldset>
<legend>Gender</legend>
<div class="checkboxes">
<label for="male"><input id="male" type="radio" name="gender" value="male" class="hidden" required="required"><span>Male</span></label>
<label for="female"><input id="female" type="radio" name="gender" value="female" class="hidden" required="required"><span>Female </span></label>
<label for="other"><input id="other" type="radio" name="gender" value="other" class="hidden" required="required"><span>Other</span></label>
</div>
</fieldset>
<input type="submit" value="Send" />
</form>
_x000D_
Although I am a big fan of the minimalistic approach of using native HTML5 validation, you might want to replace it with Javascript validation on the long run. Javascript validation gives you far more control over the validation process and it allows you to set real classes (instead of pseudo classes) to improve the styling of the (in)valid fields. This native HTML5 validation can be your fall-back in case of broken (or lack of) Javascript. You can find an example of that here, along with some other suggestions on how to make Better forms, inspired by Andrew Cole.
select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
'Awaiting'
Else
'Approved'
END AS StartDateStatus
From MyTable
I had to overcome this problem myself, when debugging web applications. -v
is great, but a little too verbose for my tastes. This is the (bash-only) solution I came up with:
curl -v http://example.com/ 2> >(sed '/^*/d')
This works because the output from -v
is sent to stderr, not stdout. By redirecting this to a subshell, we can sed
it to remove lines that start with *
. Since the real output does not pass through the subshell, it is not affected. Using a subshell is a little heavy-handed, but it's the easiest way to redirect stderr to another command. (As I noted, I'm only using this for testing, so it works fine for me.)
I am doing some large calculations which involves the mysql connection to stay long time and with heavy data. i was facing this "Mysql go away issue". So i tried t optimize the queries but that doen't helped me then i increased the mysql variables limit which is set to a lower value by default.
wait_timeout max_allowed_packet
To the limit what ever suits to you it should be the Any Number * 1024(Bytes). you can login to terminal using 'mysql -u username - p' command and can check and change for these variable limits.
In response to the "when to use it?" question:
I often use a static (class) variable to assign a unique instance ID to every instance of a class. I use the same code in every class, it is very simple:
//Instance ID ----------------------------------------
// Class variable holding the last assigned IID
private static int xID = 0;
// Lock to make threadsafe (can omit if single-threaded)
private static object xIDLock = new object();
// Private class method to return the next unique IID
// - accessible only to instances of the class
private static int NextIID()
{
lock (xIDLock) { return ++xID; }
}
// Public class method to report the last IID used
// (i.e. the number of instances created)
public static int LastIID() { return xID; }
// Instance readonly property containing the unique instance ID
public readonly int IID = NextIID();
//-----------------------------------------------------
This illustrates a couple of points about static variables and methods:
I find this useful because I develop applications in which swarms of objects are used and it is good to be able to track how many have been created, and to track/query individual instances.
I also use class variables to track things like totals and averages of properties of the instances which can be reported in real time. I think the class is a good place to keep summary information about all the instances of the class.
Those who updated their device to Android 4.2 Jelly Bean or higher or having a 4.2 JB or higher android powered device, will not found the Developers Options in Settings menu. The Developers Options hide by default on 4.2 jelly bean and later android versions. Follow the below steps to Unhide Developers Options.
Go to Settings>> More/General tab>> About (On Samsung Galaxy S3, Galaxy S4, Galaxy Note 8.0, Galaxy Tab 3 and other galaxy Smartphone and tablet having Android 4.2/4.3 Jelly Bean) OR
Go to Settings>> General>> About (On Samsung Galaxy Note 2, Galaxy Note 3 and some other Galaxy devices having Android 4.3 Jelly Bean or 4.4 KitKat) OR
Go to Settings> About> Software Information> More (On HTC One or other HTC devices having Android 4.2 Jelly Bean or higher) 2. Now Scroll onto Build Number and tap it 7 times repeatedly. A message will appear saying that u are now a developer.
Credit to www.androidofficer.com
http://docs.notepad-plus-plus.org/index.php/Inserting_Variable_Text
Notepad++ comes equipped with a Edit -> Column "Alt+C" Editor which can work on a rectangular selection in two different ways: Coledit.png inserting some fixed text on every line including and following the current line, at the column of the insertion point (aka caret). Initially selected text is left untouched. As the picture illustrates, a linear series of numbers can be inserted in the same manner. The starting value and increment are to be provided. Left padding with zeroes is an option, and the number may be entered in base 2, 8, 10 or 16 - this is how the computed values will be displayed too, padding being based on the largest.
It was discussed before here.
In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.
If you have a path for that file in the web server, you can get the real path in the server's file system using ServletContext.getRealPath(). Note that it is not guaranteed to work in every container (as a container is not required to unpack the WAR file and store the content in the file system - most do though). And I guess it won't work with files in /WEB-INF, as they don't have a virtual path.
The alternative would be to use ServletContext.getResource() which returns a URI. This URI may be a 'file:' URL, but there's no guarantee for that.
This is how I do it:
CSS:
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table
}
#content {
display: table-cell;
text-align: center;
vertical-align: middle
}
HTML:
<div id="content">
Content goes here
</div>
See
and
** Update**: 11/19/2019
Microsoft has released a new version of the control 150.1400.0
in their Nuget library. My short testing shows that it works again in the forms designer where 150.1357.0
and 150.1358.0
did not. This includes being able to resize and modify the ReportViewer Tasks on the control itself.
** Update**: 8/18/2019
Removing the latest version and rolling back to 150.900.148.0
seems to work on multiple computers I'm using with VS2017 and VS2019.
You can roll back to 150.900.148 in the Nuget solution package manager. It works similarly to the previous versions. Use the drop down box to select the older version.
It may be easier to manually delete references to post 150.900 versions of ReportViewer and readd them than it is to fix them.
Remember to restart Visual Studio after changing the toolbox entry.
Update: 8/7/2019
A newer version of the ReportViewer control has been released, probably coinciding with Visual Studio 2019. I was working with V150.1358.0.
Following the directions in this answer gets the control in the designer's toolbox. But once dropped on the form it doesn't display. The control shows up below the form as a non-visual component.
This is working as designed according to Microsoft SQL BI support. This is the group responsible for the control.
While you still cannot interact with the control directly, these additional steps give a workaround so the control can be sized on the form. While now visible, the designer treats the control as if it didn't exist.
I've created a feedback request at the suggestion of Microsoft SQL BI support. Please consider voting on it to get Microsoft's attention.
Microsoft Azure Feedback page - Restore Designtime features of the WinForms ReportViewer Control
Additional steps:
In the form's form.designer.cs file, add the Reportviewer control to the panel.
//
// panel1
//
this.panel1.Controls.Add(this.reportViewer1);
Return to the form's designer, you should see the reportViewer on the panel
Now you can position the reportViewer by actually interacting with the panel.
Update: Microsoft released a document on April 18, 2017 describing how to configure and use the reporting tool in Visual Studio 2017.
Visual Studio 2017 does not have the ReportViewer
tool installed by default in the ToolBox. Installing the extension Microsoft Rdlc Report Designer for Visual Studio and then adding that to the ToolBox results in a non-visual component that appears below the form.
Microsoft Support had told me this is a bug, but as of April 21, 2017 it is "working as designed".
The following steps need to be followed for each project that requires ReportViewer
.
ReportViewer
in the Toolbox, remove it. Highlight, right-click and delete.
Edited 8/7/2019 - It looks like the current version of the RDLC Report Designer extension no longer interferes. You need this to actually edit the reports.
If you have the Microsoft Rdlc Report Designer for Visual Studio extension installed, uninstall it.
Close your solution and restart Visual Studio. This is a crucial step, errors will occur if VS is not restarted when switching between solutions.
Tools/NuGet Package Manager/Package Manager Console
)At the PM> prompt enter this command, case matters.
Install-Package Microsoft.ReportingServices.ReportViewerControl.WinForms
You should see text describing the installation of the package.
Now we can temporarily add the ReportViewer
tool to the tool box.
Right-click in the toolbox and use Choose Items...
We need to browse to the proper DLL that is located in the solutions Packages
folder, so hit the browse button.
In our example we can paste in the packages folder as shown in the text of Package Manager Console.
C:\Users\jdoe\Documents\Projects\_Test\ReportViewerTest\WindowsFormsApp1\packages
Then double click on the folder named
Microsoft.ReportingServices.ReportViewerControl.Winforms.140.340.80
The version number will probably change in the future.
Then double-click on lib
and again on net40
.
Finally, double click on the file Microsoft.ReportViewer.WinForms.dll
You should see ReportViewer
checked in the dialog. Scroll to the right and you will see the version 14.0.0.0 associated to it.
Click OK.
ReportViewer
is now located in the ToolBox.
Drag the tool to the desired form(s).
Once completed, delete the ReportViewer
tool from the tool box. You can't use it with another project.
You may save the project and are good to go.
Remember to restart Visual Studio any time you need to open a project with ReportViewer
so that the DLL is loaded from the correct location. If you try and open a solution with a form with ReportViewer
without restarting you will see errors indicating that the “The variable 'reportViewer1' is either undeclared or was never assigned.
“.
If you add a new project to the same solution you need to create the project, save the solution, restart Visual Studio and then you should be able to add the ReportViewer
to the form. I have seen it not work the first time and show up as a non-visual component.
When that happens, removing the component from the form, deleting the Microsoft.ReportViewer.*
references from the project, saving and restarting usually works.
Use the Resource like
ResourceBundle rb = ResourceBundle.getBundle("com//sudeep//internationalization//MyApp",locale);
or
ResourceBundle rb = ResourceBundle.getBundle("com.sudeep.internationalization.MyApp",locale);
Just give the qualified path .. Its working for me!!!
A simple solution:
Encode the image as a jpeg and look for a substantial change in filesize.
I've implemented something similar with video thumbnails, and had a lot of success and scalability.
Here how you call timeout without calling additional functions.
setTimeout(this.setState.bind(this, {position:1}), 3000);
Uses function.prototype.bind()
setTimeout takes the location of the function and keeps it in the context.
setTimeout(this.setState, 3000, {position:1});
Probably uses the same bind method at some point
The setTimeout only takes the location of the function and the function already has the context? Anyway, it works!
NOTE: These work with any function you use in js.
Yes it's possible, as long as the datatypes are compatible. If they aren't, use a CONVERT() or CAST()
SELECT firstname + ' ' + lastname AS name FROM customers
2018 > JQUERY v.3.3 SOLUTION: Working globaly for all input, textarea with placeholder.
$(function(){
$('input, textarea').on('focus', function(){
if($(this).attr('placeholder')){
window.oldph = $(this).attr('placeholder');
$(this).attr('placeholder', ' ');
};
});
$('input, textarea').on('blur', function(){
if($(this).attr('placeholder')){
$(this).attr('placeholder', window.oldph);
};
});
});
Add following to your maven dependency
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
I used this to sort a gallery of images where the sort array would be altered by an ajax call. Hopefully it can be useful to someone.
var myArray = ['2', '3', '1'];_x000D_
var elArray = [];_x000D_
_x000D_
$('.imgs').each(function() {_x000D_
elArray[$(this).data('image-id')] = $(this);_x000D_
});_x000D_
_x000D_
$.each(myArray,function(index,value){_x000D_
$('#container').append(elArray[value]); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
<div class="imgs" data-image-id='1'>1</div>_x000D_
<div class="imgs" data-image-id='2'>2</div>_x000D_
<div class="imgs" data-image-id='3'>3</div>_x000D_
</div>
_x000D_
Fiddle: http://jsfiddle.net/ruys9ksg/
It looks like others had this problem also, and there is a simple Python script now, for converting output of mysqldump into CSV files.
wget https://raw.githubusercontent.com/jamesmishra/mysqldump-to-csv/master/mysqldump_to_csv.py
mysqldump -u username -p --host=rdshostname database table | python mysqldump_to_csv.py > table.csv
Just convert it to int
:
char registered = '®';
int code = (int) registered;
In fact there's an implicit conversion from char
to int
so you don't have to specify it explicitly as I've done above, but I would do so in this case to make it obvious what you're trying to do.
This will give the UTF-16 code unit - which is the same as the Unicode code point for any character defined in the Basic Multilingual Plane. (And only BMP characters can be represented as char
values in Java.) As Andrzej Doyle's answer says, if you want the Unicode code point from an arbitrary string, use Character.codePointAt()
.
Once you've got the UTF-16 code unit or Unicode code points, but of which are integers, it's up to you what you do with them. If you want a string representation, you need to decide exactly what kind of representation you want. (For example, if you know the value will always be in the BMP, you might want a fixed 4-digit hex representation prefixed with U+
, e.g. "U+0020"
for space.) That's beyond the scope of this question though, as we don't know what the requirements are.
Alt+H, then type letters FC, then pick the color.
You can use strtotime() for time calculation. Here is an example:
$checkTime = strtotime('09:00:59');
echo 'Check Time : '.date('H:i:s', $checkTime);
echo '<hr>';
$loginTime = strtotime('09:01:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!'; echo '<br>';
echo 'Time diff in sec: '.abs($diff);
echo '<hr>';
$loginTime = strtotime('09:00:59');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
echo '<hr>';
$loginTime = strtotime('09:00:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
Check the already-asked question - how to get time difference in minutes:
Subtract the past-most one from the future-most one and divide by 60.
Times are done in unix format so they're just a big number showing the number of seconds from January 1 1970 00:00:00 GMT
Either you need
std::function<void(Foo*)> f = &Foo::doSomething;
so that you can call it on any instance, or you need to bind a specific instance, for example this
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
The first answer is too complex, historic, and uninformative for my tastes.
It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,
Let's start with the first. Very often with something like Debian you'll see.
RUN apt-get update \
&& apt-get dist-upgrade \
&& apt-get install <whatever> \
&& apt-get clean
We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,
RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;
It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean
doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree
for an example of that).
By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from
syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean
), and you would otherwise have lots of un-needed files in your final image.
See also
Some of the above solutions are of the higher run time complexities. With the below algorithm, it can be achieved in O(n) time.
Algorithm:
Complexity: O(n) where n is the length of the String.
import java.io.IOException;
import java.util.ArrayList;
public class WordReverse {
public static void main(String[] args) throws IOException {
String inputStr = "Hello World";
String reversed = "";
ArrayList<String> alist = new ArrayList<String>();
for (int i = inputStr.length() - 1; i >= 0; i--) {
if (inputStr.charAt(i) != ' ') {
reversed = reversed + inputStr.charAt(i);
} else {
alist.add(reversed);
reversed = "";
}
}
alist.add(reversed);
String result = "";
for (int i = alist.size() - 1; i >= 0; i--) {
result = result + alist.get(i);
result = result + " ";
}
System.out.println(result);
}
}
In your project find references System.Web.Mvc check the version.
After that right click references -> assemblies and search system.web.mvc and setup it.
The problem causes the different versions of these assemblies.
Edit : Than select manage NuGet packages and install the updates (if you have multiple projects install updates to them also.)
Important update is Microsoft.AspNet.Mvc and Microsoft.Net.Compilers don't forget it!
I had to modify this slightly to be used on a Windows System. Here's the one-liner version for a windows box.
openssl.exe s_client -connect yoursitename.com:443 > CertInfo.txt && openssl x509 -text -in CertInfo.txt | find "Signature Algorithm" && del CertInfo.txt /F
Tested on Server 2012 R2 using http://iweb.dl.sourceforge.net/project/gnuwin32/openssl/0.9.8h-1/openssl-0.9.8h-1-bin.zip
Yep, in Windows 7 64 bit you have C:\Program Files
and C:\Program Files (x86)
. You can find Java folders in both of them, but you must add C:\Program Files\Java\jre7\bin
to environment variable PATH.
The above solution is incomplete, it missed the attribute src
.
this.src
and this.attribute('src')
are NOT the same, the first one contains the full reference to the image, for example http://my.host/error.jpg
, but the attribute just keeps the original value, error.jpg
Correct solution
<img src="foo.jpg" onerror="if (this.src != 'error.jpg' && this.attribute('src') != 'error.jpg') this.src = 'error.jpg';" />
There is a flag --files-from
that does exactly what you want. From man rsync
:
--files-from=FILE
Using this option allows you to specify the exact list of files to transfer (as read from the specified FILE or - for standard input). It also tweaks the default behavior of rsync to make transferring just the specified files and directories easier:
The --relative (-R) option is implied, which preserves the path information that is specified for each item in the file (use --no-relative or --no-R if you want to turn that off).
The --dirs (-d) option is implied, which will create directories specified in the list on the destination rather than noisily skipping them (use --no-dirs or --no-d if you want to turn that off).
The --archive (-a) option’s behavior does not imply --recursive (-r), so specify it explicitly, if you want it.
These side-effects change the default state of rsync, so the position of the --files-from option on the command-line has no bearing on how other options are parsed (e.g. -a works the same before or after --files-from, as does --no-R and all other options).
The filenames that are read from the FILE are all relative to the source dir -- any leading slashes are removed and no ".." references are allowed to go higher than the source dir. For example, take this command:
rsync -a --files-from=/tmp/foo /usr remote:/backup
If /tmp/foo contains the string "bin" (or even "/bin"), the /usr/bin directory will be created as /backup/bin on the remote host. If it contains "bin/" (note the trailing slash), the immediate contents of the directory would also be sent (without needing to be explicitly mentioned in the file -- this began in version 2.6.4). In both cases, if the -r option was enabled, that dir’s entire hierarchy would also be transferred (keep in mind that -r needs to be specified explicitly with --files-from, since it is not implied by -a). Also note that the effect of the (enabled by default) --relative option is to duplicate only the path info that is read from the file -- it does not force the duplication of the source-spec path (/usr in this case).
In addition, the --files-from file can be read from the remote host instead of the local host if you specify a "host:" in front of the file (the host must match one end of the transfer). As a short-cut, you can specify just a prefix of ":" to mean "use the remote end of the transfer". For example:
rsync -a --files-from=:/path/file-list src:/ /tmp/copy
This would copy all the files specified in the /path/file-list file that was located on the remote "src" host.
If the --iconv and --protect-args options are specified and the --files-from filenames are being sent from one host to another, the filenames will be translated from the sending host’s charset to the receiving host’s charset.
NOTE: sorting the list of files in the --files-from input helps rsync to be more efficient, as it will avoid re-visiting the path elements that are shared between adjacent entries. If the input is not sorted, some path elements (implied directories) may end up being scanned multiple times, and rsync will eventually unduplicate them after they get turned into file-list elements.
The problem you're having running from the command line is that you don't put ".class" after your class file.
java Practice 10 12
should work - as long as you're somewhere java can find the .class file.
Classpath issues are a whole 'nother story. If java still complains that it can't find your class, go to the same directory as your .class file (and it doesn't appear you're using packages...) and try -
java -cp . Practice 10 12
Don't know the nature of your app, but I have seen this error manifested multiple times because of a connection pool leak, so that would be worth checking out. On Linux, socket connections consume file descriptors as well as file system files. Just a thought.
HTML :
<h1>↓ SCROLL ↓</h1>
<table class="blue">
<thead>
<tr>
<th>Colonne 1</th>
<th>Colonne 2</th>
<th>Colonne 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
</tbody>
</table>
<h1 class="scrollMore">↓ SCROLL MORE ↓</h1>
<table class="purple">
<thead>
<tr>
<th>Colonne 1</th>
<th>Colonne 2</th>
<th>Colonne 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
<tr>
<td>Non</td>
<td>Mais</td>
<td>Allo !</td>
</tr>
</tbody>
</table>
<h1 class="up scrollMore">↑ UP ↑</h1>
CSS:
body{
font:1.2em normal Arial,sans-serif;
color:#34495E;
}
h1{
text-align:center;
text-transform:uppercase;
letter-spacing:-2px;
font-size:2.5em;
margin:20px 0;
}
.container{
width:90%;
margin:auto;
}
table{
border-collapse:collapse;
width:100%;
}
.blue{
border:2px solid #1ABC9C;
}
.blue thead{
background:#1ABC9C;
}
.purple{
border:2px solid #9B59B6;
}
.purple thead{
background:#9B59B6;
}
thead{
color:white;
}
th,td{
text-align:center;
padding:5px 0;
}
tbody tr:nth-child(even){
background:#ECF0F1;
}
tbody tr:hover{
background:#BDC3C7;
color:#FFFFFF;
}
.fixed{
top:0;
position:fixed;
width:auto;
display:none;
border:none;
}
.scrollMore{
margin-top:600px;
}
.up{
cursor:pointer;
}
JS (jQuery):
;(function($) {
$.fn.fixMe = function() {
return this.each(function() {
var $this = $(this),
$t_fixed;
function init() {
$this.wrap('<div class="container" />');
$t_fixed = $this.clone();
$t_fixed.find("tbody").remove().end().addClass("fixed").insertBefore($this);
resizeFixed();
}
function resizeFixed() {
$t_fixed.find("th").each(function(index) {
$(this).css("width",$this.find("th").eq(index).outerWidth()+"px");
});
}
function scrollFixed() {
var offset = $(this).scrollTop(),
tableOffsetTop = $this.offset().top,
tableOffsetBottom = tableOffsetTop + $this.height() - $this.find("thead").height();
if(offset < tableOffsetTop || offset > tableOffsetBottom)
$t_fixed.hide();
else if(offset >= tableOffsetTop && offset <= tableOffsetBottom && $t_fixed.is(":hidden"))
$t_fixed.show();
}
$(window).resize(resizeFixed);
$(window).scroll(scrollFixed);
init();
});
};
})(jQuery);
$(document).ready(function(){
$("table").fixMe();
$(".up").click(function() {
$('html, body').animate({
scrollTop: 0
}, 2000);
});
});
For beginner programmer: If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network).
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
Adding jQuery to Your Web Pages click here.
Reference: HERE
This does almost everything you want:
f = open('data.txt', 'rb')
while True:
char = f.read(1)
if not char: break
print "{:02x}".format(ord(char)),
With data.txt created like this:
f = open('data.txt', 'wb')
f.write("ab\r\ncd")
f.close()
I get the following output:
61 62 0d 0a 63 64
tl;dr -- 1. You are using poor variable names. 2. You are slicing your hex strings incorrectly. 3. Your code is never going to replace any newlines. You may just want to forget about that feature. You do not quite yet understand the difference between a character, its integer code, and the hex string that represents the integer. They are all different: two are strings and one is an integer, and none of them are equal to each other. 4. For some files, you shouldn't remove newlines.
===
1. Your variable names are horrendous.
That's fine if you never want to ask anybody questions. But since every one needs to ask questions, you need to use descriptive variable names that anyone can understand. Your variable names are only slightly better than these:
fname = 'data.txt'
f = open(fname, 'rb')
xxxyxx = f.read()
xxyxxx = len(xxxyxx)
print "Length of file is", xxyxxx, "bytes. "
yxxxxx = 0
while yxxxxx < xxyxxx:
xyxxxx = hex(ord(xxxyxx[yxxxxx]))
xyxxxx = xyxxxx[-2:]
yxxxxx = yxxxxx + 1
xxxxxy = chr(13) + chr(10)
xxxxyx = str(xxxxxy)
xyxxxxx = str(xyxxxx)
xyxxxxx.replace(xxxxyx, ' ')
print xyxxxxx
That program runs fine, but it is impossible to understand.
2. The hex() function produces strings of different lengths.
For instance,
print hex(61)
print hex(15)
--output:--
0x3d
0xf
And taking the slice [-2:] for each of those strings gives you:
3d
xf
See how you got the 'x' in the second one? The slice:
[-2:]
says to go to the end of the string and back up two characters, then grab the rest of the string. Instead of doing that, take the slice starting 3 characters in from the beginning:
[2:]
3. Your code will never replace any newlines.
Suppose your file has these two consecutive characters:
"\r\n"
Now you read in the first character, "\r", and convert it to an integer, ord("\r"), giving you the integer 13. Now you convert that to a string, hex(13), which gives you the string "0xd"
, and you slice off the first two characters giving you:
"d"
Next, this line in your code:
bndtx.replace(entx, ' ')
tries to find every occurrence of the string "\r\n"
in the string "d"
and replace it. There is never going to be any replacement because the replacement string is two characters long and the string "d"
is one character long.
The replacement won't work for "\r\n"
and "0d"
either. But at least now there is a possibility it could work because both strings have two characters. Let's reduce both strings to a common denominator: ascii codes. The ascii code for "\r" is 13, and the ascii code for "\n" is 10. Now what about the string "0d"
? The ascii code for the character "0"
is 48, and the ascii code for the character "d" is 100. Those strings do not have a single character in common. Even this doesn't work:
x = '0d' + '0a'
x.replace("\r\n", " ")
print x
--output:--
'0d0a'
Nor will this:
x = 'd' + 'a'
x.replace("\r\n", " ")
print x
--output:--
da
The bottom line is: converting a character to an integer then to a hex string does not end up giving you the original character--they are just different strings. So if you do this:
char = "a"
code = ord(char)
hex_str = hex(code)
print char.replace(hex_str, " ")
...you can't expect "a" to be replaced by a space. If you examine the output here:
char = "a"
print repr(char)
code = ord(char)
print repr(code)
hex_str = hex(code)
print repr(hex_str)
print repr(
char.replace(hex_str, " ")
)
--output:--
'a'
97
'0x61'
'a'
You can see that 'a' is a string with one character in it, and '0x61'
is a string with 4 characters in it: '0'
, 'x'
, '6'
, and '1'
, and you can never find a four character string inside a one character string.
4) Removing newlines can corrupt the data.
For some files, you do not want to replace newlines. For instance, if you were reading in a .jpg file, which is a file that contains a bunch of integers representing colors in an image, and some colors in the image happened to be represented by the number 13 followed by the number 10, your code would eliminate those colors from the output.
However, if you are writing a program to read only text files, then replacing newlines is fine. But then, different operating systems use different newlines. You are trying to replace Windows newlines(\r\n), which means your program won't work on files created by a Mac or Linux computer, which use \n for newlines. There are easy ways to solve that, but maybe you don't want to worry about that just yet.
I hope all that's not too confusing.
As of Android Studio 3.0 / Gradle Build Tools 3.0.0, APK artifacts can now be found in foo/bar/build/outputs/apk/flavorName/buildType
with respect to your project name, foo
, and your module name, bar
. There is now a directory for each apk
file sorted organized first by flavor (with respect to flavor dimensions) and then by build type.
Update for npm 5:
As of npm 5.0.0, installed/uninstalled modules are added/removed as a dependency by default, so the --save
option is no longer needed.
Run
npm uninstall <package>
For example:
npm uninstall mongodb
It will remove the module from the node_modules folder and also the package.json file.
Explanation and working solution here: Howto: div with onclick inside another div with onclick javascript
by executing this script in your inner click handler:
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
Use this
$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');
while($row = mysql_fetch_array($sql_results))
{
$subArray[location_id]=$row['location']; //location_id is key and $row['location'] is value which come fron database.
$subArray[x]=$row['x'];
$subArray[y]=$row['y'];
$array[] = $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';
Please use the below statement
select * from all_objects ao where ao.OBJECT_TYPE = 'TABLE' and ao.OWNER = 'YOUR_SCHEMA_NAME'
It's as easy as using select:
Get-Content file.txt | Select -Index (line - 1)
E.g. to get line 5
Get-Content file.txt | Select -Index 4
Or you can use:
(Get-Content file.txt)[4]
function Do-SendKeys {
param (
$SENDKEYS,
$WINDOWTITLE
)
$wshell = New-Object -ComObject wscript.shell;
IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
Sleep 1
IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'
Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:
<root>
<level value="ALL" />
<appender-ref ref="File1Appender" />
</root>
<logger name="SomeName">
<level value="ALL" />
<appender-ref ref="File1Appender2" />
</logger>
This is how I have done it in the past. Then something like this for the other log:
private static readonly ILog otherLog = LogManager.GetLogger("SomeName");
And you can get your normal logger as follows:
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Read the loggers and appenders section of the documentation to understand how this works.
Disable antivirus and try. I was also facing that problem... but in my case antivirus was blocking my application when I disabled antivirus it resolved.
StringBuilder will perform better, from a memory stand point. As for processing, the difference in time of execution may be negligible.
$id = 101;
$sql = 'SELECT * FROM ur_tbl t WHERE t.email_id = '. $id;
$email = Yii::app()->db->createCommand($sql)->queryAll();
var_dump($email);
This is a optimized version of the function which removes dependency on BitConverter function and makes it compatible with NETMF (.NET Micro Framework)
public static DateTime GetNetworkTime()
{
const string ntpServer = "pool.ntp.org";
var ntpData = new byte[48];
ntpData[0] = 0x1B; //LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(ntpServer).AddressList;
var ipEndPoint = new IPEndPoint(addresses[0], 123);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43];
ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47];
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
var networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
On macOS, go to the git root directory and enter git diff *
You can parse a date time string with a given timezone as well:
zone = "Pacific Time (US & Canada)"
ActiveSupport::TimeZone[zone].parse("2020-05-24 18:45:00")
=> Sun, 24 May 2020 18:45:00 PDT -07:00
The echo -e
must have been failing for you because of wrong escaping.
The following code works fine for me on a similar output from your_program with arguments
:
echo -e $(your_program with arguments | sed -e 's/0x\(..\)\.\?/\\x\1/g')
Please note however that your original hexstring consists of non-printable characters.
You need to use the LINQ Dynamic Query Library in order to pass parameters at runtime,
This will allow linq statements like
string orderedBy = "Description";
var query = (from p in products
orderby(orderedBy)
select p);
You're close. For arbitrary values, try something like the following:
public enum Day {
MONDAY("M"), TUESDAY("T"), WEDNESDAY("W"),
THURSDAY("R"), FRIDAY("F"), SATURDAY("Sa"), SUNDAY("Su"), ;
private final String abbreviation;
// Reverse-lookup map for getting a day from an abbreviation
private static final Map<String, Day> lookup = new HashMap<String, Day>();
static {
for (Day d : Day.values()) {
lookup.put(d.getAbbreviation(), d);
}
}
private Day(String abbreviation) {
this.abbreviation = abbreviation;
}
public String getAbbreviation() {
return abbreviation;
}
public static Day get(String abbreviation) {
return lookup.get(abbreviation);
}
}
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
We had the same error even though the user was properly mapped to the login.
After trying to delete the user it was discovered that a few SPs contained "with execute as" that user.
The issue was solved by dropping those SPs, dropping the user, recreating the user linked to login, and recreating the SPs.
Possibly it got in this state from restoring from backup (during a time when the related login didn't exist) or bulk schema syncing (if its possible to create an SP with execute as even though the user doesn't exist. Could also have been related to this answer.
Do you want to remove a specific line from file so use this snippet short and simple code you can easily remove any line with sentence or prefix(Symbol).
with open("file_name.txt", "r") as f:
lines = f.readlines()
with open("new_file.txt", "w") as new_f:
for line in lines:
if not line.startswith("write any sentence or symbol to remove line"):
new_f.write(line)
I cannot solve it with source ./myscript.sh
. It says the source not found error.
Failed also when using . ./myscript.sh
. It gives can't open myscript.sh.
So my option is put it in a text file to be called in the next script.
#!/bin/sh
echo "Perform Operation in su mode"
echo "ARCH=arm" >> environment.txt
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export "CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?" >> environment.txt
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...
Tnen call it whenever is needed:
while read -r line; do
line=$(sed -e 's/[[:space:]]*$//' <<<${line})
var=`echo $line | cut -d '=' -f1`; test=$(echo $var)
if [ -z "$(test)" ];then eval export "$line";fi
done <environment.txt
But this is obviously performing a 'string' comparison
No. The string will be automatically cast into a DATETIME value.
See 11.2. Type Conversion in Expression Evaluation.
When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.
If you want to create a small dots, just use icon from font awesome.
fa fa-circle
varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.
Check out the HTML5 PDF viewer:
You can sum numbers in a list simply with the sum() built-in:
sum(your_list)
It will sum as many number items as you have. Example:
my_list = range(10, 17)
my_list
[10, 11, 12, 13, 14, 15, 16]
sum(my_list)
91
For your specific case:
For your data convert the numbers into int
first and then sum the numbers:
data = ['5', '4', '9']
sum(int(i) for i in data)
18
This will work for undefined number of elements in your list (as long as they are "numbers")
Thanks for @senderle's comment re conversion in case the data is in string format.
Try deleting R.java and letting eclipse re-generate it.
For swift 3 purposes
theImageView.image = theImageView.image!.withRenderingMode(.alwaysTemplate)
theImageView.tintColor = UIColor.red
If you are using "MVC 5" you may not see the file, and you should follow these steps: http://www.techjunkieblog.com/2015/05/aspnet-mvc-empty-project-adding.html
If you are using "ASP.NET 5" it has stopped using "bundling and minification" instead was replaced by gulp, bower, and npm. More information see https://jeffreyfritz.com/2015/05/where-did-my-asp-net-bundles-go-in-asp-net-5/
The short answer here is the serial ID is computed via a hash if you don't specify it. (Static members are not inherited--they are static, there's only (1) and it belongs to the class).
http://docs.oracle.com/javase/6/docs/platform/serialization/spec/class.html
The getSerialVersionUID method returns the serialVersionUID of this class. Refer to Section 4.6, "Stream Unique Identifiers." If not specified by the class, the value returned is a hash computed from the class's name, interfaces, methods, and fields using the Secure Hash Algorithm (SHA) as defined by the National Institute of Standards.
If you alter a class or its hierarchy your hash will be different. This is a good thing. Your objects are different now that they have different members. As such, if you read it back in from its serialized form it is in fact a different object--thus the exception.
The long answer is the serialization is extremely useful, but probably shouldn't be used for persistence unless there's no other way to do it. Its a dangerous path specifically because of what you're experiencing. You should consider a database, XML, a file format and probably a JPA or other persistence structure for a pure Java project.
#Variables
$computername = Get-Content 'M:\Applications\Powershell\comp list\Test.txt'
$sourcefile = "\\server\Apps\LanSchool 7.7\Windows\Student.msi"
#This section will install the software
foreach ($computer in $computername)
{
$destinationFolder = "\\$computer\C$\download\LanSchool"
#This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it will create it.
if (!(Test-Path -path $destinationFolder))
{
New-Item $destinationFolder -Type Directory
}
Copy-Item -Path $sourcefile -Destination $destinationFolder
Invoke-Command -ComputerName $computer -ScriptBlock { & cmd /c "msiexec.exe /i c:\download\LanSchool\Student.msi" /qn ADVANCED_OPTIONS=1 CHANNEL=100}
}
I've searched all over for this myself and came up with zilch but have finally cobbled this working script together. It's working great! Thought I'd post here hopefully someone else can benefit. It pulls in a list of computers, copies the files down to the local machines and runs it. :) party on!
Toggle both modals
$('#modalOne').modal('toggle');
$('#modalTwo').modal('toggle');
If you just want the last date for each account, you'd use this:
var q = from n in table
group n by n.AccountId into g
select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};
If you want the whole record:
var q = from n in table
group n by n.AccountId into g
select g.OrderByDescending(t=>t.Date).FirstOrDefault();
Running adb commands on all connected devices
Create a bash (adb+)
adb devices | while read line
do
if [ ! "$line" = "" ] && [ `echo $line | awk '{print $2}'` = "device" ]
then
device=`echo $line | awk '{print $1}'`
echo "$device $@ ..."
adb -s $device $@
fi
done use it with
adb+ //+ command
The sort of thing that you are looking for is to be found in the curses module.
i.e.
import curses # Get the module
stdscr = curses.initscr() # initialise it
stdscr.clear() # Clear the screen
The important thing to remember is before any exit, you need to reset the terminal to a normal mode, this can be done with the following lines:
curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()
If you don't you will get all sort of strange behaviour. To ensure that this is always done I would suggest using the atexit module, something like:
import atexit
@atexit.register
def goodbye():
""" Reset terminal from curses mode on exit """
curses.nocbreak()
if stdscr:
stdscr.keypad(0)
curses.echo()
curses.endwin()
Will probably do nicely.
Try using No Wrap - In Head or No wrap - in body in your fiddle:
Working fiddle: http://jsfiddle.net/Q5hd6/
Explanation:
Angular begins compiling the DOM when the DOM is fully loaded. You register your code to run onLoad
(onload option in fiddle) => it's too late to register your myApp
module because angular begins compiling the DOM and angular sees that there is no module named myApp
and throws an exception.
By using No Wrap - In Head, your code looks like this:
<head>
<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js'></script>
<script type='text/javascript'>
//Your script.
</script>
</head>
Your script has a chance to run before angular begins compiling the DOM and myApp
module is already created when angular starts compiling the DOM.
try like this
= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "", FormatNumber( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )
You can either use:
<button onclick="window.history.back()">Back</button>
or..
<button onclick="window.history.go(-1)">Back</button>
The difference, of course, is back()
only goes back 1 page but go()
goes back/forward the number of pages you pass as a parameter, relative to your current page.
One other difference lies in the performance.
As the DLL is loaded at runtime by the .exe(s), the .exe(s) and the DLL work with shared memory concept and hence the performance is low relatively to static linking.
On the other hand, a .lib is code that is linked statically at compile time into every process that requests. Hence the .exe(s) will have single memory, thus increasing the performance of the process.
@m-ali answer is right but also keep in mind that logs could grow a lot if you don't commit the transaction after each chunk and perform a checkpoint. This is how I would do it and take this article http://sqlperformance.com/2013/03/io-subsystem/chunk-deletes as reference, with performance tests and graphs:
DECLARE @Deleted_Rows INT;
SET @Deleted_Rows = 1;
WHILE (@Deleted_Rows > 0)
BEGIN
BEGIN TRANSACTION
-- Delete some small number of rows at a time
DELETE TOP (10000) LargeTable
WHERE readTime < dateadd(MONTH,-7,GETDATE())
SET @Deleted_Rows = @@ROWCOUNT;
COMMIT TRANSACTION
CHECKPOINT -- for simple recovery model
END
A nice simple little jQuery solution:
$("form").bind("keypress", function (e) {
if (e.keyCode == 13) {
return false;
}
});
I had the same problem as I like using the Try-method-pattern which basically seems to be incompatible to the async-await-paradigm...
Important to me is that I can call the Try-method within a single if-clause and do not have to pre-define the out-variables before, but can do it in-line like in the following example:
if (TryReceive(out string msg))
{
// use msg
}
So I came up with the following solution:
Define a helper struct:
public struct AsyncOut<T, OUT>
{
private readonly T returnValue;
private readonly OUT result;
public AsyncOut(T returnValue, OUT result)
{
this.returnValue = returnValue;
this.result = result;
}
public T Out(out OUT result)
{
result = this.result;
return returnValue;
}
public T ReturnValue => returnValue;
public static implicit operator AsyncOut<T, OUT>((T returnValue ,OUT result) tuple) =>
new AsyncOut<T, OUT>(tuple.returnValue, tuple.result);
}
Define async Try-method like this:
public async Task<AsyncOut<bool, string>> TryReceiveAsync()
{
string message;
bool success;
// ...
return (success, message);
}
Call the async Try-method like this:
if ((await TryReceiveAsync()).Out(out string msg))
{
// use msg
}
For multiple out parameters you can define additional structs (e.g. AsyncOut<T,OUT1, OUT2>) or you can return a tuple.
yo can try this code
@using (Html.BeginForm("SignUp", "Account", FormMethod.Post)){<fieldset>
<legend>Sign Up</legend>
<table>
<tr>
<td>
@Html.Label("User Name")
</td>
<td>
@Html.TextBoxFor(account => account.Username)
</td>
</tr>
<tr>
<td>
@Html.Label("Email")
</td>
<td>
@Html.TextBoxFor(account => account.Email)
</td>
</tr>
<tr>
<td>
@Html.Label("Password")
</td>
<td>
@Html.TextBoxFor(account => account.Password)
</td>
</tr>
<tr>
<td>
@Html.Label("Confirm Password")
</td>
<td>
@Html.Password("txtPassword")
</td>
</tr>
<tr>
<td>
<input type="submit" name="btnSubmit" value="Sign Up" />
</td>
</tr>
</table>
</fieldset>}
Yes, you can definitely do this. Just use something like
.parent:hover .child {
/* ... */
}
According to this page it's supported by all major browsers.
I had a similar thing happen to me. I didn't want to stage the files just yet so I added them with git add
and then just did git reset
. This basically just added and then unstaged my changes but cleared the unmerged paths.
I would caution you: if you are using absolute paths, then your application cannot be installed in a "subdirectory" of the server!
eg, http://yourserver.com/yourapp may work, but http://myserver.com/apps/yourapp will not!
you could connect all the data you need from the file to a single string, and in the excel sheet seperate it with text to column. here is an example i did for same issue, enjoy:
Sub CP()
Dim ToolFile As String
Cells(3, 2).Select
For i = 0 To 5
r = ActiveCell.Row
ToolFile = Cells(r, 7).Value
On Error Resume Next
ActiveCell.Value = CP_getdatta(ToolFile)
'seperate data by "-"
Selection.TextToColumns Destination:=Range("C3"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Cells(r + 1, 2).Select
Next
End Sub
Function CP_getdatta(ToolFile As String) As String
Workbooks.Open Filename:=ToolFile, UpdateLinks:=False, ReadOnly:=True
Range("A56000").Select
Selection.End(xlUp).Select
x = CStr(ActiveCell.Value)
ActiveCell.Offset(0, 20).Select
Selection.End(xlToLeft).Select
While IsNumeric(ActiveCell.Value) = False
ActiveCell.Offset(0, -1).Select
Wend
' combine data to 1 string
CP_getdatta = CStr(x & "-" & ActiveCell.Value)
ActiveWindow.Close False
End Function
You can create a function which would allow you to do the same as timeout but also for other functions:
function run_cmd {
cmd="$1"; timeout="$2";
grep -qP '^\d+$' <<< $timeout || timeout=10
(
eval "$cmd" &
child=$!
trap -- "" SIGTERM
(
sleep $timeout
kill $child 2> /dev/null
) &
wait $child
)
}
And could run as below:
run_cmd "echoFooBar" 10
Note: The solution came from one of my questions: Elegant solution to implement timeout for bash commands and functions
It would seem overkill but Spring Forms handles this elegantly. That is of course if you are already using Spring MVC and you want to take advantage of the Spring Forms feature.
// jsp form
<form:select path="friendlyNumber" items="${friendlyNumberItems}" />
// the command class
public class NumberCmd {
private String[] friendlyNumber;
}
// in your Spring MVC controller submit method
@RequestMapping(method=RequestMethod.POST)
public String manageOrders(@ModelAttribute("nbrCmd") NumberCmd nbrCmd){
String[] selectedNumbers = nbrCmd.getFriendlyNumber();
}
Hate to add yet another answer, but my particular scenario isn't quite covered here. I had a local repo with a history of changes I wanted to preserve, and a non-empty repo created for me on Github (that is, with the default README.md). Yes, you can always re-create the Github repo as an empty repo, but in my case someone else has the permissions to create this particular repo, and I didn't want to trouble him, if there was an easy workaround.
In this scenario, you will encounter this error when you attempt to git push
after setting the remote origin:
! [rejected] master -> master (fetch first)
error: failed to push some refs to '[email protected]:<my repo>.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
As the error indicates, I needed to do a git pull
after setting the remote origin, but I needed to specify the --allow-unrelated-histories
option. Without this option, git pull
complains warning: no common commits
.
So here is the exact sequence of commands that worked for me:
git remote add origin <github repo url>
cp README.md README.md-save
git pull origin master --allow-unrelated-histories
mv README.md-save README.md
git commit -a
git push
The answers given so far are not ideal because they require a lot of needless work resolving merge conflicts, or they make too many assumptions which are frequently false. This is how to do it perfectly. The link is to my own site.
You have uncommited changes on my_branch
that you want to commit to master
, without committing all the changes from my_branch
.
git merge master
git stash -u
git checkout master
git stash apply
git reset
git add example.js
git commit
git checkout .
git clean -f -d
git checkout my_branch
git merge master
git stash pop
Start by merging master
into your branch, since you'll have to do that eventually anyway, and now is the best time to resolve any conflicts.
The -u
option (aka --include-untracked
) in git stash -u
prevents you from losing untracked files when you later do git clean -f -d
within master
.
After git checkout master
it is important that you do NOT git stash pop
, because you will need this stash later. If you pop the stash created in my_branch
and then do git stash
in master
, you will cause needless merge conflicts when you later apply that stash in my_branch
.
git reset
unstages everything resulting from git stash apply
. For example, files that have been modified in the stash but do not exist in master
get staged as "deleted by us" conflicts.
git checkout .
and git clean -f -d
discard everything that isn't committed: all changes to tracked files, and all untracked files and directories. They are already saved in the stash and if left in master
would cause needless merge conflicts when switching back to my_branch
.
The last git stash pop
will be based on the original my_branch
, and so will not cause any merge conflicts. However, if your stash contains untracked files which you have committed to master, git will complain that it "Could not restore untracked files from stash". To resolve this conflict, delete those files from your working tree, then git stash pop
, git add .
, and git reset
.
On OSX, you can take advantage of the UNIX-like command line - here's what I keep handy in my .bashrc to enable me to more easily restart a server that's running in background (-d) mode (note that you have to be in the Rails root directory when running this):
alias restart_rails='kill -9 `cat tmp/pids/server.pid`; rails server -d'
My initial response to the comment by @zane about how the PID file isn't removed was that it might be behavior dependent on the Rails version or OS type. However, it's also possible that the shell runs the second command (rails server -d
) sooner than the kill
can actually cause the previous running instance to stop.
So alternatively, kill -9 cat tmp/pids/server.pid && rails server -d
might be more robust; or you can specifically run the kill
, wait for the tmp/pids
folder to empty out, then restart your new server.
If you're getting this, you may have forgotten to put #include <thread>
at the beginning of your file. OP's signature seems like it should work.
public static Random rand = new Random(); // this happens once, and will be great at preventing duplicates
Note, this is not to be used for cryptographic purposes.
You can run OpenSSH on Cygwin, and even install it as a Windows service.
I once used it this way to easily add backups of a Unix system - it would rsync a bunch of files onto the Windows server, and the Windows server had full tape backups.
I would add a div around the image and make the image change in opacity on hover and add an inset box shadow to the div on hover.
img:hover{
opacity:.5;
}
.image:hover{
box-shadow: inset 10px 10px 100px 100px #000;
}
<div class="image"><img src="image.jpg" /></div>
For people who searched for php multidimensional array get values
and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach
, which is array_column
For example, if I only want to get hotel_name
from the below array, and form to another array:
$hotels = [
[
'hotel_name' => 'Hotel A',
'info' => 'Hotel A Info',
],
[
'hotel_name' => 'Hotel B',
'info' => 'Hotel B Info',
]
];
I can do this using array_column
:
$hotel_name = array_column($hotels, 'hotel_name');
print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']
For the actual answer for this question, it can also be beautified by array_column
and call_user_func_array('array_merge', $twoDimensionalArray);
Let's make the data in PHP:
$hotels = [
[
'hotel_name' => 'Hotel A',
'info' => 'Hotel A Info',
'rooms' => [
[
'room_name' => 'Luxury Room',
'bed' => 2,
'boards' => [
'board_id' => 1,
'price' => 200
]
],
[
'room_name' => 'Non Luxy Room',
'bed' => 4,
'boards' => [
'board_id' => 2,
'price' => 150
]
],
]
],
[
'hotel_name' => 'Hotel B',
'info' => 'Hotel B Info',
'rooms' => [
[
'room_name' => 'Luxury Room',
'bed' => 2,
'boards' => [
'board_id' => 3,
'price' => 900
]
],
[
'room_name' => 'Non Luxy Room',
'bed' => 4,
'boards' => [
'board_id' => 4,
'price' => 300
]
],
]
]
];
And here's the calculation:
$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');
foreach($boards as $board){
$board_id = $board['board_id'];
$price = $board['price'];
echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}
Which will give you the following result:
Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300
mysql> CREATE USER 'monty'@'192.168.%.%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'192.168.%.%'
If you are looking for a RB-tree implementation, then stl_tree.h might be appropriate for you too.
You do not have to install something.
parseInt(req.params.year, 10);
should work properly.
console.log(typeof parseInt(req.params.year)); // returns 'number'
What is your output, if you use parseInt? is it still a string?
BTW, HTTP 1/1 specification (RFC2616) suggests no more than 2 connections per server.
Clients that use persistent connections SHOULD limit the number of simultaneous connections that they maintain to a given server. A single-user client SHOULD NOT maintain more than 2 connections with any server or proxy. A proxy SHOULD use up to 2*N connections to another server or proxy, where N is the number of simultaneously active users. These guidelines are intended to improve HTTP response times and avoid congestion.
Task: Given two int arrays array1 and array2 of the same length, zip should return an array that's twice as long, in which the elements of array1 and array2 are interleaved. That is, element #0 of the result array is array1[0], element #1 is array2[0], element #2 is array1[1], element #3 is array2[1], and so on.
public static int [] zip(int [ ] array1, int [] array2) {
//make sure both arrays have same length
if (array1.length != array2.length) {
throw new IllegalArgumentException("Unequal array lengths - zip not possible");
}
int [] zippedArray = new int [array1.length+ array2.length];
int idx_1 = 0;
int idx_2 = 0;
//for each element of first array, add to new array if index of new array is even
for (int i=0; i < zippedArray.length; i+=2){
zippedArray[i]= array1[idx_1++];
}
for (int i=1; i < zippedArray.length; i+=2){
zippedArray[i]= array2[idx_2++];
}
//check contents of new array
for (int item: zippedArray){
System.out.print(item + " ");
}
return zippedArray;
}
In Laravel 6 there is a channel called 'stderr'. See config/logging.php
:
'stderr' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
],
In your controller:
use Illuminate\Support\Facades\Log;
Log::channel('stderr')->info('Something happened!');
It depends on if you mean '\n' (linefeed) or '\r\n' (carriage return + linefeed). The former is not the Windows default and will not show properly in some text editors (like Notepad).
You can do
sb.Append(Environment.NewLine);
sb.Append("\t");
or
sb.Append("\r\n\t");
If the case is accessing the IFrame via console, e. g. Chrome Dev Tools then you can just select the context of DOM requests via dropdown (see the picture).