This error occurs when versions of NodeJS and Node Sass are not matched.
you can resolve your issue by doing as below:
- Step 1: Remove Nodejs from your computer
- Step 2: Reinstall Nodejs version 14.15.1.
- Step 3: Uninstall Node sass by run the command npm uninstall node-sass
- Step 4: Reinstall Node sass version 4.14.1 by run the command npm install [email protected]
After all steps, you can run command ng serve -o
to run your application.
Change file type from tsx -> ts, jsx -> js
You can get this error if you are working on .tsx or .jsx file and you are just exporting styles etc and not jsx. In this case the error is solved by changing the file type to .ts or .js
This is a relatively new update, but it is much more straight forward. If you are using Jest 24.9.0 or higher you can just add testTimeout
to your config:
// in jest.config.js
module.exports = {
testTimeout: 30000
}
In my opinion, it's much cleaner and easier to understand if you extract the retrieval of environment variables into a utility (you probably want to include a check to fail fast if an environment variable is not set anyway), and then you can just mock the utility.
// util.js
exports.getEnv = (key) => {
const value = process.env[key];
if (value === undefined) {
throw new Error(`Missing required environment variable ${key}`);
}
return value;
};
// app.test.js
const util = require('./util');
jest.mock('./util');
util.getEnv.mockImplementation(key => `fake-${key}`);
test('test', () => {...});
If anyone get this error for ionic cordova install . just use this code npm install --no-optional
in your cmd.
And then run this code npm install -g ionic@latest cordova
Further to Peter Danis' post, I just wanted to emphasize the part of his solution involving "[passing] a function into expect(function).toThrow(blank or type of error)".
In Jest, when you test for a case where an error should be thrown, within your expect() wrapping of the function under testing, you need to provide one additional arrow function wrapping layer in order for it to work. I.e.
Wrong (but most people's logical approach):
expect(functionUnderTesting();).toThrow(ErrorTypeOrErrorMessage);
Right:
expect(() => { functionUnderTesting(); }).toThrow(ErrorTypeOrErrorMessage);
It's very strange, but it should make the testing run successfully.
I used axios-mock-adapter. In this case the service is described in ./chatbot. In the mock adapter you specify what to return when the API endpoint is consumed.
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';
describe('Chatbot', () => {
it('returns data when sendMessage is called', done => {
var mock = new MockAdapter(axios);
const data = { response: true };
mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);
chatbot.sendMessage(0, 'any').then(response => {
expect(response).toEqual(data);
done();
});
});
});
You can see it the whole example here:
Service: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js
Test: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js
In your test code your are trying to pass App
to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:
1) Where the click handler calls a function passed as a prop, e.g.
class App extends Component {
myClickFunc = () => {
console.log('clickity clickcty');
this.props.someCallback();
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now pass in a spy function as a prop to the component, and assert that it is called:
describe('my sweet test', () => {
it('clicks it', () => {
const spy = jest.fn();
const app = shallow(<App someCallback={spy} />)
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
2) Where the click handler sets some state on the component, e.g.
class App extends Component {
state = {
aProperty: 'first'
}
myClickFunc = () => {
console.log('clickity clickcty');
this.setState({
aProperty: 'second'
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now make assertions about the state of the component, i.e.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const p = app.find('.App-intro')
p.simulate('click')
expect(app.state('aProperty')).toEqual('second');
})
})
#1 Using Jest
This is how I use the Jest mock callback function to test the click event:
import React from 'react';
import { shallow } from 'enzyme';
import Button from './Button';
describe('Test Button component', () => {
it('Test click event', () => {
const mockCallBack = jest.fn();
const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
button.find('button').simulate('click');
expect(mockCallBack.mock.calls.length).toEqual(1);
});
});
I am also using a module called enzyme. Enzyme is a testing utility that makes it easier to assert and select your React Components
#2 Using Sinon
Also, you can use another module called Sinon which is a standalone test spy, stubs and mocks for JavaScript. This is how it looks:
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import Button from './Button';
describe('Test Button component', () => {
it('simulates click events', () => {
const mockCallBack = sinon.spy();
const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
button.find('button').simulate('click');
expect(mockCallBack).toHaveProperty('callCount', 1);
});
});
#3 Using Your own Spy
Finally, you can make your own naive spy (I don't recommend this approach unless you have a valid reason for that).
function MySpy() {
this.calls = 0;
}
MySpy.prototype.fn = function () {
return () => this.calls++;
}
it('Test Button component', () => {
const mySpy = new MySpy();
const mockCallBack = mySpy.fn();
const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
button.find('button').simulate('click');
expect(mySpy.calls).toEqual(1);
});
npm test __tests__/filename.test.ts
- to run a single file.
test.only('check single test', () => { expect(true).toBe(true)});
- to run a single test case
test.skip('to skip testcase, () => {expect(false).toBe(false_});
- to skip a test case
In my component I need access to window.location.search
. This is what I did in the Jest test:
Object.defineProperty(global, "window", {
value: {
location: {
search: "test"
}
}
});
In case window properties must be different in different tests, we can put window mocking into a function, and make it writable in order to override for different tests:
function mockWindow(search, pathname) {
Object.defineProperty(global, "window", {
value: {
location: {
search,
pathname
}
},
writable: true
});
}
And reset after each test:
afterEach(() => {
delete global.window.location;
});
Fast forwarding to 2020, I found this blog post to be the solution: Jest mock default and named export
Using only ES6 module syntax:
// esModule.js
export default 'defaultExport';
export const namedExport = () => {};
// esModule.test.js
jest.mock('./esModule', () => ({
__esModule: true, // this property makes it work
default: 'mockedDefaultExport',
namedExport: jest.fn(),
}));
import defaultExport, { namedExport } from './esModule';
defaultExport; // 'mockedDefaultExport'
namedExport; // mock function
Also one thing you need to know (which took me a while to figure out) is that you can't call jest.mock() inside the test; you must call it at the top level of the module. However, you can call mockImplementation() inside individual tests if you want to set up different mocks for different tests.
You need to put your code into ngOnInit
and use the this
keyword:
ngOnInit() {
this.booksByStoreID = this.books.filter(
book => book.store_id === this.store.id);
}
You need ngOnInit
because the input store
wouldn't be set into the constructor:
ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.
(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)
In your code, the books filtering is directly defined into the class content...
Make sure first that you have certificates installed on your Debian in /etc/ssl/certs
.
If not, reinstall them:
sudo apt-get install --reinstall ca-certificates
Since that package does not include root certificates, add:
sudo mkdir /usr/local/share/ca-certificates/cacert.org
sudo wget -P /usr/local/share/ca-certificates/cacert.org http://www.cacert.org/certs/root.crt http://www.cacert.org/certs/class3.crt
sudo update-ca-certificates
Make sure your git does reference those CA:
git config --global http.sslCAinfo /etc/ssl/certs/ca-certificates.crt
Jason C mentions another potential cause (in the comments):
It was the clock. The NTP server was down, the system clock wasn't set properly, I didn't notice or think to check initially, and the incorrect time was causing verification to fail.
You could use
Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column) Duplicates and blank lines have been removed and the data has been sorted alphabetically.
as indicated above. However, the way I did it because I need to replace the duplicates by blank lines and not just remove the lines, once sorted alphabetically:
REPLACE:
((^.*$)(\n))(?=\k<1>)
by
$3
This will convert:
Shorts
Shorts
Shorts
Shorts
Shorts
Shorts Two Pack
Shorts Two Pack
Signature Braces
Signature Braces
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
to:
Shorts
Shorts Two Pack
Signature Braces
Signature Cotton Trousers
That's how I did it because I specifically needed those lines.
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
some of the answers assume you have 'eslint-plugin-jest' installed, however without needing to do that, you can simply do this in your .eslintrc
file, add:
"globals": {
"jest": true,
}
You should use any()
In [98]: a['Names'].str.contains('Mel').any()
Out[98]: True
In [99]: if a['Names'].str.contains('Mel').any():
....: print "Mel is there"
....:
Mel is there
a['Names'].str.contains('Mel')
gives you a series of bool values
In [100]: a['Names'].str.contains('Mel')
Out[100]:
0 False
1 False
2 False
3 False
4 True
Name: Names, dtype: bool
"test": "jest api/ds_server/ds_server.test.js"
This works for me:
"jest": {
"collectCoverage": true,
"coverageReporters": ["json", "html"]
},
"scripts": {
"test": "jest --coverage"
},
Run:
yarn/npm test
Works great, minimal setup and no third parties.
According to Chrome's documentation:
Here's the updated workflow:What happens when you blackbox a script?
Exceptions thrown from library code will not pause (if Pause on exceptions is enabled), Stepping into/out/over bypasses the library code, Event listener breakpoints don't break in library code, The debugger will not pause on any breakpoints set in library code. The end result is you are debugging your application code instead of third party resources.
jquery\..*\.js
(glob pattern/human translation: jquery.*.js
)|
, like so: jquery\..*\.js|include\.postload\.js
(which acts like an "or this pattern", so to speak. Or keep adding them with the "Add" button.Bonus tip! I use Regex101 regularly (but there are many others: ) to quickly test my rusty regex patterns and find out where I'm wrong with the step-by-step regex debugger. If you are not yet "fluent" in Regular Expressions I recommend you start using sites that help you write and visualize them such as http://buildregex.com/ and https://www.debuggex.com/
You can also use the context menu when working in the Sources panel. When viewing a file, you can right-click in the editor and choose Blackbox Script. This will add the file to the list in the Settings panel:
It's an excellent tool to have:
Visual Event is an open-source Javascript bookmarklet which provides debugging information about events that have been attached to DOM elements. Visual Event shows:
- Which elements have events attached to them
- The type of events attached to an element
- The code that will be run with the event is triggered
- The source file and line number for where the attached function was defined (Webkit browsers and Opera only)
You can pause the code when you click somewhere in the page, or when the DOM is modified... and other kinds of JS breakpoints that will be useful to know. You should apply blackboxing here to avoid a nightmare.
In this instance, I want to know what exactly goes on when I click the button.
Open Dev Tools -> Sources tab, and on the right find Event
Listener Breakpoints
:
Expand Mouse
and select click
With Dev Tools activated, you can search the whole codebase (all code in all files) with ?+?+F or:
and searching #envio
or whatever the tag/class/id you think starts the party and you may get somewhere faster than anticipated.
Be aware sometimes there's not only an img
but lots of elements stacked, and you may not know which one triggers the code.
If this is a bit out of your knowledge, take a look at Chrome's tutorial on debugging.
Include jquery.validate.js before additional-methods.js
.
$.validate()
method is defined there
You didn't use FROM expression for a table
SELECT DISTINCT Description, Date as treatmentDate
**FROM <A TABLE>**
WHERE doothey.Patient P, doothey.Account A, doothey.AccountLine AL, doothey.Item.I
AND P.PatientID = A.PatientID
AND A.AccountNo = AL.AccountNo
AND AL.ItemNo = I.ItemNo
AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');
if name in ("Jesse", "jesse"):
would be the correct way to do it.
Although, if you want to use or
, the statement would be
if name == 'Jesse' or name == 'jesse':
>>> ("Jesse" or "jesse")
'Jesse'
evaluates to 'Jesse'
, so you're essentially not testing for 'jesse'
when you do if name == ("Jesse" or "jesse")
, since it only tests for equality to 'Jesse'
and does not test for 'jesse'
, as you observed.
If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?
Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("name");
allNames.add(name);
}
(typed straight into the browser, so not tested).
You have a number of choices:
TRUE
, FALSE
Boolean value.Use (as pointed in this answer)
SELECT CASE WHEN hide = 0 THEN FALSE ELSE TRUE END FROM
Or if Boolean is not supported:
SELECT CASE WHEN hide = 0 THEN 'false' ELSE 'true' END FROM
Please, never use this concat form:
String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text
+ "WHERE supplier_id = " + textBox1.Text;
use:
command.Parameters.AddWithValue("@attribute", value);
Always work object oriented
Edit: This is because when you parameterize your updates it helps prevent SQL injection.
There is also a shorthand of doing this:
NSArray *persons = @[person1, person2, person3];
It's equivalent to
NSArray *persons = [NSArray arrayWithObjects:person1, person2, person3, nil];
As iiFreeman said, you still need to do proper memory management if you're not using ARC.
I was facing a similar issue, I had a file on my project, and wanted to test a class which had to deal with loading files from the FS and process them some way. What I did was:
test.txt
to my test projectalt-enter
(file properties)BuildAction
to Content
and Copy to Output Directory
to Copy if newer
, I guess Copy always
would have done it as wellthen on my tests I just had to Path.Combine(Environment.CurrentDirectory, "test.txt")
and that's it. Whenever the project is compiled it will copy the file (and all it's parent path, in case it was in, say, a folder) to the bin\Debug
(or whatever configuration you are using) folder.
Hopes this helps someone
Try adding scrolling="no"
attribute like below:
<iframe frameborder="0" scrolling="no" style="height:380px;width:6000px;border:none;" src='https://yoururl'></iframe>
_x000D_
In my opinion
If you wanna write follow kind UTF-8.You should create a byte array.Then,you can do such as the following:
byte[] by=("<?xml version=\"1.0\" encoding=\"utf-8\"?>"+"Your string".getBytes();
Then, you can write each byte into file you created. Example:
OutputStream f=new FileOutputStream(xmlfile);
byte[] by=("<?xml version=\"1.0\" encoding=\"utf-8\"?>"+"Your string".getBytes();
for (int i=0;i<by.length;i++){
byte b=by[i];
f.write(b);
}
f.close();
Solved this using sudo chown -R _mysql:_mysql /usr/local/var/mysql
Thanks to Matteo Alessani
Here's a more simple version. In the cell you want the date to show up just type
=Today()
Format the cell to the date format you want and Bob's your uncle. :)
If your editor doesn't recognize tabs when doing a search and replace (like SciTE), you can paste the code into Word and search using Ctr-H and ^t which finds the tabs which then can be replace with 4 spaces.
Yet another alternative:
Select FORMAT(date,'MM.yy')
...
...
group by FORMAT(date,'MM.yy')
Here's A generic VBA Array To Range function that writes an array to the sheet in a single 'hit' to the sheet. This is much faster than writing the data into the sheet one cell at a time in loops for the rows and columns... However, there's some housekeeping to do, as you must specify the size of the target range correctly.
This 'housekeeping' looks like a lot of work and it's probably rather slow: but this is 'last mile' code to write to the sheet, and everything is faster than writing to the worksheet. Or at least, so much faster that it's effectively instantaneous, compared with a read or write to the worksheet, even in VBA, and you should do everything you possibly can in code before you hit the sheet.
A major component of this is error-trapping that I used to see turning up everywhere . I hate repetitive coding: I've coded it all here, and - hopefully - you'll never have to write it again.
A VBA 'Array to Range' function
Public Sub ArrayToRange(rngTarget As Excel.Range, InputArray As Variant)
' Write an array to an Excel range in a single 'hit' to the sheet
' InputArray must be a 2-Dimensional structure of the form Variant(Rows, Columns)
' The target range is resized automatically to the dimensions of the array, with
' the top left cell used as the start point.
' This subroutine saves repetitive coding for a common VBA and Excel task.
' If you think you won't need the code that works around common errors (long strings
' and objects in the array, etc) then feel free to comment them out.
On Error Resume Next
'
' Author: Nigel Heffernan
' HTTP://Excellerando.blogspot.com
'
' This code is in te public domain: take care to mark it clearly, and segregate
' it from proprietary code if you intend to assert intellectual property rights
' or impose commercial confidentiality restrictions on that proprietary code
Dim rngOutput As Excel.Range
Dim iRowCount As Long
Dim iColCount As Long
Dim iRow As Long
Dim iCol As Long
Dim arrTemp As Variant
Dim iDimensions As Integer
Dim iRowOffset As Long
Dim iColOffset As Long
Dim iStart As Long
Application.EnableEvents = False
If rngTarget.Cells.Count > 1 Then
rngTarget.ClearContents
End If
Application.EnableEvents = True
If IsEmpty(InputArray) Then
Exit Sub
End If
If TypeName(InputArray) = "Range" Then
InputArray = InputArray.Value
End If
' Is it actually an array? IsArray is sadly broken so...
If Not InStr(TypeName(InputArray), "(") Then
rngTarget.Cells(1, 1).Value2 = InputArray
Exit Sub
End If
iDimensions = ArrayDimensions(InputArray)
If iDimensions < 1 Then
rngTarget.Value = CStr(InputArray)
ElseIf iDimensions = 1 Then
iRowCount = UBound(InputArray) - LBound(InputArray)
iStart = LBound(InputArray)
iColCount = 1
If iRowCount > (655354 - rngTarget.Row) Then
iRowCount = 655354 + iStart - rngTarget.Row
ReDim Preserve InputArray(iStart To iRowCount)
End If
iRowCount = UBound(InputArray) - LBound(InputArray)
iColCount = 1
' It's a vector. Yes, I asked for a 2-Dimensional array. But I'm feeling generous.
' By convention, a vector is presented in Excel as an arry of 1 to n rows and 1 column.
ReDim arrTemp(LBound(InputArray, 1) To UBound(InputArray, 1), 1 To 1)
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
arrTemp(iRow, 1) = InputArray(iRow)
Next
With rngTarget.Worksheet
Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount))
rngOutput.Value2 = arrTemp
Set rngTarget = rngOutput
End With
Erase arrTemp
ElseIf iDimensions = 2 Then
iRowCount = UBound(InputArray, 1) - LBound(InputArray, 1)
iColCount = UBound(InputArray, 2) - LBound(InputArray, 2)
iStart = LBound(InputArray, 1)
If iRowCount > (65534 - rngTarget.Row) Then
iRowCount = 65534 - rngTarget.Row
InputArray = ArrayTranspose(InputArray)
ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iRowCount)
InputArray = ArrayTranspose(InputArray)
End If
iStart = LBound(InputArray, 2)
If iColCount > (254 - rngTarget.Column) Then
ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iColCount)
End If
With rngTarget.Worksheet
Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount + 1))
Err.Clear
Application.EnableEvents = False
rngOutput.Value2 = InputArray
Application.EnableEvents = True
If Err.Number <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
InputArray(iRow, iCol) = Trim(InputArray(iRow, iCol))
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Formula = InputArray
End If 'err<>0
If Err <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
If Left(InputArray(iRow, iCol), 1) = "=" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
If Left(InputArray(iRow, iCol), 1) = "+" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
If Left(InputArray(iRow, iCol), 1) = "*" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Value2 = InputArray
End If 'err<>0
If Err <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsObject(InputArray(iRow, iCol)) Then
InputArray(iRow, iCol) = "[OBJECT] " & TypeName(InputArray(iRow, iCol))
ElseIf IsArray(InputArray(iRow, iCol)) Then
InputArray(iRow, iCol) = Split(InputArray(iRow, iCol), ",")
ElseIf IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
If Len(InputArray(iRow, iCol)) > 255 Then
' Block-write operations fail on strings exceeding 255 chars. You *have*
' to go back and check, and write this masterpiece one cell at a time...
InputArray(iRow, iCol) = Left(Trim(InputArray(iRow, iCol)), 255)
End If
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Text = InputArray
End If 'err<>0
If Err <> 0 Then
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
iRowOffset = LBound(InputArray, 1) - 1
iColOffset = LBound(InputArray, 2) - 1
For iRow = 1 To iRowCount
If iRow Mod 100 = 0 Then
Application.StatusBar = "Filling range... " & CInt(100# * iRow / iRowCount) & "%"
End If
For iCol = 1 To iColCount
rngOutput.Cells(iRow, iCol) = InputArray(iRow + iRowOffset, iCol + iColOffset)
Next iCol
Next iRow
Application.StatusBar = False
Application.ScreenUpdating = True
End If 'err<>0
Set rngTarget = rngOutput ' resizes the range This is useful, *most* of the time
End With
End If
End Sub
You will need the source for ArrayDimensions:
This API declaration is required in the module header:
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(Destination As Any, _
Source As Any, _
ByVal Length As Long)
...And here's the function itself:
Private Function ArrayDimensions(arr As Variant) As Integer
'-----------------------------------------------------------------
' will return:
' -1 if not an array
' 0 if an un-dimmed array
' 1 or more indicating the number of dimensions of a dimmed array
'-----------------------------------------------------------------
' Retrieved from Chris Rae's VBA Code Archive - http://chrisrae.com/vba
' Code written by Chris Rae, 25/5/00
' Originally published by R. B. Smissaert.
' Additional credits to Bob Phillips, Rick Rothstein, and Thomas Eyde on VB2TheMax
Dim ptr As Long
Dim vType As Integer
Const VT_BYREF = &H4000&
'get the real VarType of the argument
'this is similar to VarType(), but returns also the VT_BYREF bit
CopyMemory vType, arr, 2
'exit if not an array
If (vType And vbArray) = 0 Then
ArrayDimensions = -1
Exit Function
End If
'get the address of the SAFEARRAY descriptor
'this is stored in the second half of the
'Variant parameter that has received the array
CopyMemory ptr, ByVal VarPtr(arr) + 8, 4
'see whether the routine was passed a Variant
'that contains an array, rather than directly an array
'in the former case ptr already points to the SA structure.
'Thanks to Monte Hansen for this fix
If (vType And VT_BYREF) Then
' ptr is a pointer to a pointer
CopyMemory ptr, ByVal ptr, 4
End If
'get the address of the SAFEARRAY structure
'this is stored in the descriptor
'get the first word of the SAFEARRAY structure
'which holds the number of dimensions
'...but first check that saAddr is non-zero, otherwise
'this routine bombs when the array is uninitialized
If ptr Then
CopyMemory ArrayDimensions, ByVal ptr, 2
End If
End Function
Also: I would advise you to keep that declaration private. If you must make it a public Sub in another module, insert the Option Private Module
statement in the module header. You really don't want your users calling any function with CopyMemoryoperations and pointer arithmetic.
As far as I know, shouldOverrideUrlLoading is not called for images but rather for hyperlinks... I think the appropriate method is
@Override
public void onLoadResource(WebView view, String url)
This method is called for every resource (image, styleesheet, script) that's loaded by the webview, but since it's a void, I haven't found a way to change that url and replace it so that it loads a local resource ...
I made this procedure for us to use at work.
cd ~
curl -s https://pypi.python.org/packages/source/p/pip/pip-1.3.1.tar.gz | tar xvz
cd pip-1.3.1
python setup.py install --user
cd ~
rm -rf pip-1.3.1
$HOME/.local/bin/pip install --user --upgrade pip distribute virtualenvwrapper
# Might want these three in your .bashrc
export PATH=$PATH:$HOME/.local/bin
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS="--distribute"
source $HOME/.local/bin/virtualenvwrapper.sh
mkvirtualenv mypy
workon mypy
pip install --upgrade distribute
pip install pudb # Or whatever other nice package you might want.
Key points for the security minded:
It works great for both known and unknown height elements. Make sure to set the outer div to height: 100%;
and reset the default margin
on body
. See the browser support tables.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
height: 100%;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
.header, .footer {_x000D_
background: silver;_x000D_
}_x000D_
.content {_x000D_
flex: 1;_x000D_
overflow: auto;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="header">Header</div>_x000D_
<div class="content">_x000D_
<div style="height:1000px;">Content</div>_x000D_
</div>_x000D_
<div class="footer">Footer</div>_x000D_
</div>
_x000D_
For both known and unknown height elements. It also works in legacy browsers including IE8.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
display: table;_x000D_
}_x000D_
.header, .content, .footer {_x000D_
display: table-row;_x000D_
}_x000D_
.header, .footer {_x000D_
background: silver;_x000D_
}_x000D_
.inner {_x000D_
display: table-cell;_x000D_
}_x000D_
.content .inner {_x000D_
height: 100%;_x000D_
position: relative;_x000D_
background: pink;_x000D_
}_x000D_
.scrollable {_x000D_
position: absolute;_x000D_
left: 0; right: 0;_x000D_
top: 0; bottom: 0;_x000D_
overflow: auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="header">_x000D_
<div class="inner">Header</div>_x000D_
</div>_x000D_
<div class="content">_x000D_
<div class="inner">_x000D_
<div class="scrollable">_x000D_
<div style="height:1000px;">Content</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="footer">_x000D_
<div class="inner">Footer</div>_x000D_
</div>_x000D_
</div>
_x000D_
calc()
If header and footer are fixed height, you can use CSS calc()
.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
height: 50px;_x000D_
background: silver;_x000D_
}_x000D_
.content {_x000D_
height: calc(100% - 100px);_x000D_
overflow: auto;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="header">Header</div>_x000D_
<div class="content">_x000D_
<div style="height:1000px;">Content</div>_x000D_
</div>_x000D_
<div class="footer">Footer</div>_x000D_
</div>
_x000D_
If the header and footer are known height, and they are also percentage you can just do the simple math making them together of 100% height.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
height: 10%;_x000D_
background: silver;_x000D_
}_x000D_
.content {_x000D_
height: 80%;_x000D_
overflow: auto;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="header">Header</div>_x000D_
<div class="content">_x000D_
<div style="height:1000px;">Content</div>_x000D_
</div>_x000D_
<div class="footer">Footer</div>_x000D_
</div>
_x000D_
i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?
I would say technically it might not be an HTTP failure, since the resource was (presumably) validly specified, the user was authenticated, and there was no operational failure (however even the spec does include some reserved codes like 402 Payment Required which aren't strictly speaking HTTP-related either, though it might be advisable to have that at the protocol level so that any device can recognize the condition).
If that's actually the case, I would add a status field to the response with application errors, like
<status><code>4</code><message>Date range is invalid</message></status>
NOTE: git whatchanged
is deprecated, use git log
instead
New users are encouraged to use git-log[1] instead. The
whatchanged
command is essentially the same as git-log[1] but defaults to show the raw format diff output and to skip merges.The command is kept primarily for historical reasons; fingers of many people who learned Git long before
git log
was invented by reading Linux kernel mailing list are trained to type it.
You can use the command git whatchanged --stat
to get a list of files that changed in each commit (along with the commit message).
I made a new checkout from the same project to a different location then copied the .svn folder from it and replaced with my old .svn folder. After that called the svn update function and everything were synced properly up to date.
Best result for me so far:
div to be centered:
position: absolute;
top: 50%;
transform: translateY(-50%);
margin: 0 auto;
right: 0;
left: 0;
3 characters before and 4 characters after
$> echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}'
23_string_and
Use DATE_ADD function
DATE_ADD(datecolumn, INTERVAL 30 MINUTE);
Java 7 added support for walking directories with symlink handling:
import java.nio.file.*;
public static void removeRecursive(Path path) throws IOException
{
Files.walkFileTree(path, new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException
{
// try to delete the file anyway, even if its attributes
// could not be read, since delete-only access is
// theoretically possible
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException
{
if (exc == null)
{
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
else
{
// directory iteration failed; propagate exception
throw exc;
}
}
});
}
I use this as a fallback from platform-specific methods (in this untested code):
public static void removeDirectory(Path directory) throws IOException
{
// does nothing if non-existent
if (Files.exists(directory))
{
try
{
// prefer OS-dependent directory removal tool
if (SystemUtils.IS_OS_WINDOWS)
Processes.execute("%ComSpec%", "/C", "RD /S /Q \"" + directory + '"');
else if (SystemUtils.IS_OS_UNIX)
Processes.execute("/bin/rm", "-rf", directory.toString());
}
catch (ProcessExecutionException | InterruptedException e)
{
// fallback to internal implementation on error
}
if (Files.exists(directory))
removeRecursive(directory);
}
}
(SystemUtils is from Apache Commons Lang. Processes is private but its behavior should be obvious.)
Custom Format for using . is not recognised by Excel, hence that could be the reason it could not sort.
Steps to mitigate; change the format to dd/mm/yyyy, sort as required , change the format to dd.mm.yyyy
I saw this and in CSS3 you can now place code in like this. Lets say I want it to cover the whole background I would do something like this. Then with hsla(0,0%,100%,0.70)
or rgba you use a white background with whatever percentage saturation or opacity to get the look you desire.
.body{
background-attachment: fixed;
background-image: url(../images/Store1.jpeg);
display: block;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 1;
background-color: hsla(0,0%,100%,0.70);
background-blend-mode: overlay;
background-repeat: no-repeat;
}
As far as I can see everything is right with your code. Your error is:
SMTP Error: Could not authenticate.
Which means that the credentials you've sending are rejected by the SMTP server. Make sure the host, port, username and password are good.
If you want to use STARTTLS, try adding:
$mail->SMTPSecure = 'tls';
If you want to use SMTPS (SSL), try adding:
$mail->SMTPSecure = 'ssl';
Keep in mind that:
Maybe this example can help (GMail secure SMTP).
The above solutions are great, but if you're using WampServer you might find setting the curl.cainfo
variable in php.ini
doesn't work.
I eventually found WampServer has two php.ini
files:
C:\wamp\bin\apache\Apachex.x.x\bin
C:\wamp\bin\php\phpx.x.xx
The first is apparently used for when PHP files are invoked through a web browser, while the second is used when a command is invoked through the command line or shell_exec()
.
TL;DR
If using WampServer, you must add the curl.cainfo
line to both php.ini
files.
You can use substring
function:
s.substring(0,s.length() - 2));
With the first 0
, you say to substring
that it has to start in the first character of your string and with the s.length() - 2
that it has to finish 2 characters before the String ends.
For more information about substring
function you can see here:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
You want to read raw lines to avoid problems with backslashes in the input (use -r
):
while read -r line; do
printf "<%s>\n" "$line"
done < file.txt
This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in
while IFS= read -r line; do
printf "%s\n" "$line"
done < file.txt
This now is an equivalent of cat < file.txt
as long as file.txt
ends with a newline.
Note that you must double quote "$line"
in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.
As unwind said, this isn't really something you do in Python - variables are actually name mappings to objects.
However, here's one way to try and do it:
>>> a = 1
>>> for k, v in list(locals().iteritems()):
if v is a:
a_as_str = k
>>> a_as_str
a
>>> type(a_as_str)
'str'
I'm using version 4.4.2 and none of the other answers worked for me. But adding useMongoClient
to the options and putting it into a variable that you call close
on seemed to work.
var db = mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: true })
//do stuff
db.close()
I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload
instruction was immediately evaluated, and then the $
usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).
So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.
var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
console.log("script loaded :)");
onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
For my needs, it works fine now. Hope this can help others :)
I suggest you do it a different way.
In the following code I set as a Range
the column with the sports name F and loop through each cell of it, check if it is "hockey" and if yes I insert the values in the other sheet one by one, by using Offset.
I do not think it is very complicated and even if you are just learning VBA, you should probably be able to understand every step. Please let me know if you need some clarification
Sub TestThat()
'Declare the variables
Dim DataSh As Worksheet
Dim HokySh As Worksheet
Dim SportsRange As Range
Dim rCell As Range
Dim i As Long
'Set the variables
Set DataSh = ThisWorkbook.Sheets("Data")
Set HokySh = ThisWorkbook.Sheets("Hoky")
Set SportsRange = DataSh.Range(DataSh.Cells(3, 6), DataSh.Cells(Rows.Count, 6).End(xlUp))
'I went from the cell row3/column6 (or F3) and go down until the last non empty cell
i = 2
For Each rCell In SportsRange 'loop through each cell in the range
If rCell = "hockey" Then 'check if the cell is equal to "hockey"
i = i + 1 'Row number (+1 everytime I found another "hockey")
HokySh.Cells(i, 2) = i - 2 'S No.
HokySh.Cells(i, 3) = rCell.Offset(0, -1) 'School
HokySh.Cells(i, 4) = rCell.Offset(0, -2) 'Background
HokySh.Cells(i, 5) = rCell.Offset(0, -3) 'Age
End If
Next rCell
End Sub
For someone who needs quick reference of C# Escape Sequences that can be used in string
literals:
\t Horizontal tab (ASCII code value: 9)
\n Line feed (ASCII code value: 10)
\r Carriage return (ASCII code value: 13)
\' Single quotation mark
\" Double quotation mark
\\ Backslash
\? Literal question mark
\x12 ASCII character in hexadecimal notation (e.g. for 0x12)
\x1234 Unicode character in hexadecimal notation (e.g. for 0x1234)
It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline
which gets adjusted to current OS settings. With .Net Core it gets really important.
You could also use the String-Editor of Android Studio, it automatically generates line brakes and stuff like that...
If you have created the migrations, you could execute them in the Startup.cs as follows.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
}
...
This will create the database and the tables using your added migrations.
If you're not using Entity Framework Migrations, and instead just need your DbContext model created exactly as it is in your context class at first run, then you can use:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.EnsureCreated();
}
...
Instead.
If you need to delete your database prior to making sure it's created, call:
context.Database.EnsureDeleted();
Just before you call EnsureCreated()
Adapted from: http://docs.identityserver.io/en/latest/quickstarts/7_entity_framework.html?highlight=entity
for bootstrap4 vertical center of few items
d-flex for flex rules
flex-column for vertical direction on items
justify-content-center for centering
style='height: 300px;' must have for set points where center be calc or use h-100 class
<div class="d-flex flex-column justify-content-center bg-secondary" style="
height: 300px;
">
<div class="p-2 bg-primary">Flex item</div>
<div class="p-2 bg-primary">Flex item</div>
<div class="p-2 bg-primary">Flex item</div>
</div>
Importing large sql file to MySql via command line
Example: mysql -u root -p aanew < aanew.sql
You are creating an array of three elements and assigning all three to the same thing, which is itself an array of three elements (three Doubles).
When you do the modifications you are modifying the floats in the internal array.
You have to move the css
folder into your web
folder. It seems that your web
folder on the hard drive equals the /ServletApp
folder as seen from the www. Other content than inside your web
folder cannot be accessed from the browsers.
The url of the CSS link is then
<link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
I have found a fix
BufferedReader br = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream(path)));
Replace "Main" with the java class you coded it in. replace "path" with the path within the jar file.
for example, if you put State1.txt in the package com.issac.state, then type the path as "/com/issac/state/State1" if you run Linux or Mac. If you run Windows then type the path as "\com\issac\state\State1". Don't add the .txt extension to the file unless the File not found exception occurs.
CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.
You need to define the animation keyframes and apply it to the element:
@keyframes changewidth {
from {
width: 100px;
}
to {
width: 300px;
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.
I have been writing a base class for all of my Pages and I came to the same issue. I had code like the following and It didn't work. By tracing, control passes from RedirectToLoginPage() statement to the next line without to be redirected.
if (_requiresAuthentication)
{
if (!User.Identity.IsAuthenticated)
FormsAuthentication.RedirectToLoginPage();
// check authorization for restricted pages only
if (_isRestrictedPage) AuthorizePageAndButtons();
}
I found out that there are two solutions. Either to modify FormsAuthentication.RedirectToLoginPage(); to be
if (!User.Identity.IsAuthenticated)
Response.Redirect(FormsAuthentication.LoginUrl);
OR to modify the web.config by adding
<authorization>
<deny users="?" />
</authorization>
In the second case, while tracing, control didn't reach the requested page. It has been redirected immediately to the login url before hitting the break point. Hence, The SignOut() method isn't the issue, the redirect method is the one.
I hope that may help someone
Regards
Cross join and inner join are the same with the only difference that in inner join we booleanly filter some of the outcomes of the cartesian product
table1
x--------------------------------------x
| fieldA | fieldB | fieldC |
x----------|-------------|-------------x
| A | B | option1 |
| A | B1 | option2 |
x--------------------------------------x
table2
x--------------------------------------x
| fieldA | fieldB | fieldC |
x----------|-------------|-------------x
| A | B | optionB1 |
| A1 | B1 | optionB2 |
x--------------------------------------x
cross join
A,B,option1,A,B,optionB1
A,B,option1,A1,B1,optionB2
A,B1,option2,A,B,optionB1
A,B1,option2,A1,B1,optionB2
inner join on field1 (only with the value is the same in both tables)
A,B,option1,A,B,optionB1
A,B1,option2,A,B,optionB1
inner join on field1
A,B,option1,A,B,optionB1
It is on design of our data where we decide that there is only one case of the field we are using for the join. Join only cross join both tables and get only the lines accomplishing special boolean expression.
Note that if the fields we are doing our Joins on would be null in both tables we would pass the filter. It is up to us or the database manufacturer to add extra rules to avoid or permit nulls. Adhering to the basics it is just a cross join followed by a filter.
I solved this problem by restarting PHPStorm (insert your programm instead) as administrator
Python has a %
operator for this.
>>> a = 5
>>> b = "hello"
>>> buf = "A = %d\n , B = %s\n" % (a, b)
>>> print buf
A = 5
, B = hello
>>> c = 10
>>> buf = "C = %d\n" % c
>>> print buf
C = 10
See this reference for all supported format specifiers.
You could as well use format
:
>>> print "This is the {}th tome of {}".format(5, "knowledge")
This is the 5th tome of knowledge
As it mentioned in another answers, a reference is inherently const.
int &ref = obj;
Once you initialized a reference with an object, you can't unbound this reference with its object it refers to. A reference works just like an alias.
When you declare a const
reference, it is nothing but a reference which refers to a const object.
const int &ref = obj;
The declarative sentences above like const
and int
is determining the available features of the object which will be referenced by the reference. To be more clear, I want to show you the pointer
equivalent of a const
reference;
const int *const ptr = &obj;
So the above line of code is equivalent to a const
reference in its working way. Additionally, there is a one last point which I want to mention;
A reference must be initialized only with an object
So when you do this, you are going to get an error;
int &r = 0; // Error: a nonconst reference cannot be initialized to a literal
This rule has one exception. If the reference is declared as const, then you can initialize it with literals as well;
const int &r = 0; // a valid approach
Apart from all the good answers already given, I'd like to add to @johan-leino's great answer. In my case, for some arbitrary reason, the CodeBehind
attribute was omitted from the @Page
directive/.aspx file. Likewise, it might be worthwhile to check the CodeFile
attribute for @Control
directives/.ascx files (obviously in conjunction with an Inherits
attribute in both cases).
Depending on the exact scenario and reason required to 'force' a regenerate of .designer.cs, one could also try to format the document (potentially indicating a parsing error) before (quick) saving (regardless whether there were any changes or not) and check the Error List for warnings.
Unless write to binary files, use print. Below example good for formatting csv files:
def write_row(file_, *columns):
print(*columns, sep='\t', end='\n', file=file_)
Usage:
PHI = 45
with open('file.csv', 'a+') as f:
write_row(f, 'header', 'phi:', PHI, 'serie no. 2')
write_row(f) # newline
write_row(f, data[0], data[1])
Notes:
'{}, {}'.format(1, 'the_second')
- https://pyformat.info/, PEP-3101*columns
in function definition - dispatches any number of arguments to list - see question on *args & **kwargsHere I have my example which works just fine:
declare
ex number;
begin
select MAX(MAX_FK_ID) + 1 into ex from TABLE;
If ex > 0 then
begin
execute immediate 'DROP SEQUENCE SQ_NAME';
exception when others then
null;
end;
execute immediate 'CREATE SEQUENCE SQ_NAME INCREMENT BY 1 START WITH ' || ex || ' NOCYCLE CACHE 20 NOORDER';
end if;
end;
If you are on Windows, here is a PowerShell script that will print the 10 largest files in your repository:
$revision_objects = git rev-list --objects --all;
$files = $revision_objects.Split() | Where-Object {$_.Length -gt 0 -and $(Test-Path -Path $_ -PathType Leaf) };
$files | Get-Item -Force | select fullname, length | sort -Descending -Property Length | select -First 10
Check the sql log in the LOG directory of your instance - see if anything is going on there. You'll need to stop the service to open the log - or restart and you can read the old one - named with .1 on the end.
With the error you're getting, you need to enable TCP/IP or Named pipes for named connections. Shared memory connection should work, but you seem to not be using that. Are you trying to connect through SSMS?
In my log I see entries like this...
Server local connection provider is ready to accept connection on [\\.\pipe\mssql$sqlexpress\sql\query ]
As the comments said, .\SQLEXPRESS should work. Also worstationName\SQLEXPRESS will work.
Removing any and all whitespace:
foo = ''.join(foo.split())
Removing last three characters:
foo = foo[:-3]
Converting to capital letters:
foo = foo.upper()
All of that code in one line:
foo = ''.join(foo.split())[:-3].upper()
You can simply pass your data frame into the following function:
rotate_x <- function(data, column_to_plot, labels_vec, rot_angle) {
plt <- barplot(data[[column_to_plot]], col='steelblue', xaxt="n")
text(plt, par("usr")[3], labels = labels_vec, srt = rot_angle, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
Usage:
rotate_x(mtcars, 'mpg', row.names(mtcars), 45)
You can change the rotation angle of the labels as needed.
As others have mentioned, the norm is to set a stop flag. For something lightweight (no subclassing of Thread, no global variable), a lambda callback is an option. (Note the parentheses in if stop()
.)
import threading
import time
def do_work(id, stop):
print("I am thread", id)
while True:
print("I am thread {} doing something".format(id))
if stop():
print(" Exiting loop.")
break
print("Thread {}, signing off".format(id))
def main():
stop_threads = False
workers = []
for id in range(0,3):
tmp = threading.Thread(target=do_work, args=(id, lambda: stop_threads))
workers.append(tmp)
tmp.start()
time.sleep(3)
print('main: done sleeping; time to stop the threads.')
stop_threads = True
for worker in workers:
worker.join()
print('Finis.')
if __name__ == '__main__':
main()
Replacing print()
with a pr()
function that always flushes (sys.stdout.flush()
) may improve the precision of the shell output.
(Only tested on Windows/Eclipse/Python3.3)
For my use-case, I required id generation that was guaranteed to be unique globally; without exception. I struggled with the problem for a while, and came up with a solution called tuid (Truly Unique ID). It generates an id with the first 32 characters being system-generated and the remaining digits representing milliseconds since epoch. In situations where I need to generate id's on client-side javascript, it works well. Have a look:
This is my list of extensions.
The list on this is pretty comprehensive, so I spent sometime to find the extensions that I need. Here is the snapshot. Hope it will help someone.
I tried installing Codemaid, and it appeared to be a nifty addon, but my Visual Studio response became very slow. Felt like some threads were doing some work all the time when Codemaid was on. So uninstalling for now.
You're running bundle exec
on a program. The program's creators wrote it when certain versions of gems were available. The program Gemfile specifies the versions of the gems the creators decided to use. That is, the script was made to run correctly against these gem versions.
Your system-wide Gemfile may differ from this Gemfile. You may have newer or older gems with which this script doesn't play nice. This difference in versions can give you weird errors.
bundle exec
helps you avoid these errors. It executes the script using the gems specified in the script's Gemfile rather than the systemwide Gemfile. It executes the certain gem versions with the magic of shell aliases.
See more on the man page.
Here's an example Gemfile:
source 'http://rubygems.org'
gem 'rails', '2.8.3'
Here, bundle exec
would execute the script using rails version 2.8.3 and not some other version you may have installed system-wide.
[type=submit]{
margin-left: 121px;
margin-top: 19px;
width: 84px;
height: 40px;
font-size:14px;
font-weight:700;
}
If you really want _.pluck
support back, you can use a mixin:
const _ = require("lodash")
_.mixin({
pluck: _.map
})
Because map
now supports a string (the "iterator") as an argument instead of a function.
seq[::n]
is a sequence of each n
-th item in the entire sequence.
Example:
>>> range(10)[::2]
[0, 2, 4, 6, 8]
The syntax is:
seq[start:end:step]
So you can do (in Python 2):
>>> range(100)[5:18:2]
[5, 7, 9, 11, 13, 15, 17]
If you need to actually get a File
object, you could do the following:
URL url = this.getClass().getResource("/test.wsdl");
File testWsdl = new File(url.getFile());
Which has the benefit of working cross platform, as described in this blog post.
Forcing HTTPS with the .htaccess
File
==> Redirect All Web Traffic :-
To force all web traffic to use HTTPS, insert the following lines of code in the .htaccess
file in your website’s root folder.
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
==> Redirect Only Specified Domain :-
To force a specific domain to use HTTPS, use the following lines of code in the .htaccess
file in your website’s root folder:
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
If this doesn’t work, try removing the first two lines.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
Make sure to replace example.com with the domain name you’re trying force to https. Additionally, you need to replace www.example.com with your actual domain name.
==> Redirect Specified Folder :-
If you want to force SSL on a specific folder, insert the code below into a .htaccess
file placed in that specific folder:
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} folder
RewriteRule ^(.*)$ https://www.example.com/folder/$1 [R=301,L]
Make sure you change the folder reference to the actual folder name. Then be sure to replace www.example.com/folder with your actual domain name and folder you want to force the SSL on.
System.out.println
System
is a class in the java.lang
package.
out
is a static
data member of the System
class and references a variable of the PrintStream
class.
Use the enumerate()
function to generate the index along with the elements of the sequence you are looping over:
for index, w in enumerate(loopme):
print "CURRENT WORD IS", w, "AT CHARACTER", index
// To delete all the folders and files within folders recursively
File sdDir = new File(sdPath);
if(sdDir.exists())
deleteRecursive(sdDir);
// Delete any folder on a device if exists
void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteRecursive(child);
fileOrDirectory.delete();
}
You can't use the API
using POST
or GET
if they are not build to call using these methods separetly. Like if your API say
/service/function?param1=value1¶m2=value2
is accessed by using GET
method. Then you can not call it using POST
method if it is not specified as POST
method by its creator. If you do that you may got 405 Method not allowed
status.
Generally in POST
method you need to send the content in body with specified format which is described in content-type
header for ex. application/json
for json data.
And after that the request body gets deserialized at server end. So you need to pass the serialized data from the client and it is decided by the service developer.
But in general terms GET
is used when server returns some data to the client and have not any impact on server whereas POST
is used to create some resource on server. So generally it should not be same.
After insuring that the string "strOutput" has a correct XML structure, you can do this:
Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");
I realize that this is an old question with many fine answers. However when I found this I also found a more recent article on TechNet by Saeid Hasani
T-SQL: How to Generate Random Passwords
While the solution focuses on passwords it applies to the general case. Saeid works through various considerations to arrive at a solution. It is very instructive.
A script containing all the code blocks form the article is separately available via the TechNet Gallery, but I would definitely start at the article.
You need to account for DateTime Kind too.
public static DateTime GetTime(this DateTime d)
{
return new DateTime(d.TimeOfDay.Ticks, d.Kind);
}
I had the same issue. I had to provide the full path using Windows conventions. At this step:
Enter file in which to save the key (/c/Users/Eva/.ssh/id_rsa):
Provide the following value:
c:\users\eva\.ssh\id_rsa
You can create a custom loading screen instead of splash screen. if you show a splash screen for 10 sec, it's not a good idea for user experience. So it's better to add a custom loading screen. For a custom loading screen you may need some different images to make that feel like a gif. after that add the images in the res
folder and make a class like this :-
public class LoadingScreen {private ImageView loading;
LoadingScreen(ImageView loading) {
this.loading = loading;
}
public void setLoadScreen(){
final Integer[] loadingImages = {R.mipmap.loading_1, R.mipmap.loading_2, R.mipmap.loading_3, R.mipmap.loading_4};
final Handler loadingHandler = new Handler();
Runnable runnable = new Runnable() {
int loadingImgIndex = 0;
public void run() {
loading.setImageResource(loadingImages[loadingImgIndex]);
loadingImgIndex++;
if (loadingImgIndex >= loadingImages.length)
loadingImgIndex = 0;
loadingHandler.postDelayed(this, 500);
}
};
loadingHandler.postDelayed(runnable, 500);
}}
In your MainActivity, you can pass a to the LoadingScreen class like this :-
private ImageView loadingImage;
Don't forget to add an ImageView in activity_main. After that call the LoadingScreen class like this;
LoadingScreen loadingscreen = new LoadingScreen(loadingImage);
loadingscreen.setLoadScreen();
I hope this will help you
There are very good examples here to start trying with, but all of them are based on adding some extra or external element like a "div" as a reference element to drag it, and calculate the new dimensions or position of the original element.
Here's an example that doesn't use any extra elements. We could add borders, padding or margin without affecting its operation. In this example we have not added color, nor any visual reference to the borders nor to the lower right corner as a clue where you can enlarge or reduce dimensions, but using the cursor around the resizable elements the clues appears!
let resizerForCenter = new Resizer('center')
resizerForCenter.initResizer()
See it in action with CodeSandbox:
In this example we use ES6, and a module that exports a class called Resizer. An example is worth a thousand words:
Or with the code snippet:
const html = document.querySelector('html')_x000D_
_x000D_
class Resizer {_x000D_
constructor(elemId) {_x000D_
this._elem = document.getElementById(elemId)_x000D_
/**_x000D_
* Stored binded context handlers for method passed to eventListeners!_x000D_
* _x000D_
* See: https://stackoverflow.com/questions/9720927/removing-event-listeners-as-class-prototype-functions_x000D_
*/_x000D_
this._checkBorderHandler = this._checkBorder.bind(this)_x000D_
this._doResizeHandler = this._doResize.bind(this)_x000D_
this._initResizerHandler = this.initResizer.bind(this)_x000D_
this._onResizeHandler = this._onResize.bind(this)_x000D_
}_x000D_
_x000D_
initResizer() {_x000D_
this.stopResizer()_x000D_
this._beginResizer()_x000D_
}_x000D_
_x000D_
_beginResizer() {_x000D_
this._elem.addEventListener('mousemove', this._checkBorderHandler, false)_x000D_
}_x000D_
_x000D_
stopResizer() {_x000D_
html.style.cursor = 'default'_x000D_
this._elem.style.cursor = 'default'_x000D_
_x000D_
window.removeEventListener('mousemove', this._doResizeHandler, false)_x000D_
window.removeEventListener('mouseup', this._initResizerHandler, false)_x000D_
_x000D_
this._elem.removeEventListener('mousedown', this._onResizeHandler, false)_x000D_
this._elem.removeEventListener('mousemove', this._checkBorderHandler, false)_x000D_
}_x000D_
_x000D_
_doResize(e) {_x000D_
let elem = this._elem_x000D_
_x000D_
let boxSizing = getComputedStyle(elem).boxSizing_x000D_
let borderRight = 0_x000D_
let borderLeft = 0_x000D_
let borderTop = 0_x000D_
let borderBottom = 0_x000D_
_x000D_
let paddingRight = 0_x000D_
let paddingLeft = 0_x000D_
let paddingTop = 0_x000D_
let paddingBottom = 0_x000D_
_x000D_
switch (boxSizing) {_x000D_
case 'content-box':_x000D_
paddingRight = parseInt(getComputedStyle(elem).paddingRight)_x000D_
paddingLeft = parseInt(getComputedStyle(elem).paddingLeft)_x000D_
paddingTop = parseInt(getComputedStyle(elem).paddingTop)_x000D_
paddingBottom = parseInt(getComputedStyle(elem).paddingBottom)_x000D_
break_x000D_
case 'border-box':_x000D_
borderRight = parseInt(getComputedStyle(elem).borderRight)_x000D_
borderLeft = parseInt(getComputedStyle(elem).borderLeft)_x000D_
borderTop = parseInt(getComputedStyle(elem).borderTop)_x000D_
borderBottom = parseInt(getComputedStyle(elem).borderBottom)_x000D_
break_x000D_
default: break_x000D_
}_x000D_
_x000D_
let horizontalAdjustment = (paddingRight + paddingLeft) - (borderRight + borderLeft)_x000D_
let verticalAdjustment = (paddingTop + paddingBottom) - (borderTop + borderBottom)_x000D_
_x000D_
let newWidth = elem.clientWidth + e.movementX - horizontalAdjustment + 'px'_x000D_
let newHeight = elem.clientHeight + e.movementY - verticalAdjustment + 'px'_x000D_
_x000D_
let cursorType = getComputedStyle(elem).cursor_x000D_
switch (cursorType) {_x000D_
case 'all-scroll':_x000D_
elem.style.width = newWidth_x000D_
elem.style.height = newHeight_x000D_
break_x000D_
case 'col-resize':_x000D_
elem.style.width = newWidth_x000D_
break_x000D_
case 'row-resize':_x000D_
elem.style.height = newHeight_x000D_
break_x000D_
default: break_x000D_
}_x000D_
}_x000D_
_x000D_
_onResize(e) {_x000D_
// On resizing state!_x000D_
let elem = e.target_x000D_
let newCursorType = undefined_x000D_
let cursorType = getComputedStyle(elem).cursor_x000D_
switch (cursorType) {_x000D_
case 'nwse-resize':_x000D_
newCursorType = 'all-scroll'_x000D_
break_x000D_
case 'ew-resize':_x000D_
newCursorType = 'col-resize'_x000D_
break_x000D_
case 'ns-resize':_x000D_
newCursorType = 'row-resize'_x000D_
break_x000D_
default: break_x000D_
}_x000D_
_x000D_
html.style.cursor = newCursorType // Avoid cursor's flickering _x000D_
elem.style.cursor = newCursorType_x000D_
_x000D_
// Remove what is not necessary, and could have side effects!_x000D_
elem.removeEventListener('mousemove', this._checkBorderHandler, false);_x000D_
_x000D_
// Events on resizing state_x000D_
/**_x000D_
* We do not apply the mousemove event on the elem to resize it, but to the window to prevent the mousemove from slippe out of the elem to resize. This work bc we calculate things based on the mouse position_x000D_
*/_x000D_
window.addEventListener('mousemove', this._doResizeHandler, false);_x000D_
window.addEventListener('mouseup', this._initResizerHandler, false);_x000D_
}_x000D_
_x000D_
_checkBorder(e) {_x000D_
const elem = e.target_x000D_
const borderSensitivity = 5_x000D_
const coor = getCoordenatesCursor(e)_x000D_
const onRightBorder = ((coor.x + borderSensitivity) > elem.scrollWidth)_x000D_
const onBottomBorder = ((coor.y + borderSensitivity) > elem.scrollHeight)_x000D_
const onBottomRightCorner = (onRightBorder && onBottomBorder)_x000D_
_x000D_
if (onBottomRightCorner) {_x000D_
elem.style.cursor = 'nwse-resize'_x000D_
} else if (onRightBorder) {_x000D_
elem.style.cursor = 'ew-resize'_x000D_
} else if (onBottomBorder) {_x000D_
elem.style.cursor = 'ns-resize'_x000D_
} else {_x000D_
elem.style.cursor = 'auto'_x000D_
}_x000D_
_x000D_
if (onRightBorder || onBottomBorder) {_x000D_
elem.addEventListener('mousedown', this._onResizeHandler, false)_x000D_
} else {_x000D_
elem.removeEventListener('mousedown', this._onResizeHandler, false)_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
function getCoordenatesCursor(e) {_x000D_
let elem = e.target;_x000D_
_x000D_
// Get the Viewport-relative coordinates of cursor._x000D_
let viewportX = e.clientX_x000D_
let viewportY = e.clientY_x000D_
_x000D_
// Viewport-relative position of the target element._x000D_
let elemRectangle = elem.getBoundingClientRect()_x000D_
_x000D_
// The function returns the largest integer less than or equal to a given number._x000D_
let x = Math.floor(viewportX - elemRectangle.left) // - elem.scrollWidth_x000D_
let y = Math.floor(viewportY - elemRectangle.top) // - elem.scrollHeight_x000D_
_x000D_
return {x, y}_x000D_
}_x000D_
_x000D_
let resizerForCenter = new Resizer('center')_x000D_
resizerForCenter.initResizer()_x000D_
_x000D_
let resizerForLeft = new Resizer('left')_x000D_
resizerForLeft.initResizer()_x000D_
_x000D_
setTimeout(handler, 10000, true); // 10s_x000D_
_x000D_
function handler() {_x000D_
resizerForCenter.stopResizer()_x000D_
}
_x000D_
body {_x000D_
background-color: white;_x000D_
}_x000D_
_x000D_
#wrapper div {_x000D_
/* box-sizing: border-box; */_x000D_
position: relative;_x000D_
float:left;_x000D_
overflow: hidden;_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
#left {_x000D_
background-color: blueviolet;_x000D_
}_x000D_
#center {_x000D_
background-color:lawngreen ;_x000D_
}_x000D_
#right {_x000D_
background: blueviolet;_x000D_
}_x000D_
#wrapper {_x000D_
border: 5px solid hotpink;_x000D_
display: inline-block;_x000D_
_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
<title>Resizer v0.0.1</title>_x000D_
</head>_x000D_
<body>_x000D_
<div id="wrapper">_x000D_
<div id="left">Left</div>_x000D_
<div id="center">Center</div>_x000D_
<div id="right">Right</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Another case is http redirection. If your page redirects http requests to https, then may be your partial view tries to redirect by itself.
It causes same problem again. For this problem, you can reorganize your .net error pages or iis error pages configuration.
Just make sure you are redirecting requests to right error or not found page and make sure this error page contains non problematic partial. If your page supports only https, do not forward requests to error page without using https, if error page contains partial, this partials tries to redirect seperately from requested url, it causes problem.
For concatenating selectors together when nesting, you need to use the parent selector (&
):
.class {
margin:20px;
&:hover {
color:yellow;
}
}
For me when i did - dotnet restore still error was occurring.
I went to
1 Tool -> NuGet Package Maneger -> Package Manager settings -> click on "Clear on Nuget Catche(s)"
2 dotnet restore
resolved issues.
As explained here by Filip - http://www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/
You can add a method too at runtime.
x.Add("Shout", new Action(() => { Console.WriteLine("Hellooo!!!"); }));
x.Shout();
Jar class/package is for specific Jar file mechanisms where there is a manifest that is used by the Jar files in some cases.
The Zip file class/package handles any compressed files that include Jar files, which is a type of compressed file.
The Jar classes thus extend the Zip package classes.
New Font-Awesome v5 has Power Transforms
You can rotate any icon by adding attribute data-fa-transform
to icon
<i class="fas fa-magic" data-fa-transform="rotate-45"></i>
Here is a fiddle
For more information, check this out : Font-Awesome5 Power Tranforms
You can use the sibling selector ~
:
h1.hc-reform ~ p{
clear:both;
}
This selects all the p
elements that come after .hc-reform
, not just the first one.
As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:
#!/usr/bin/python
import sys
from subprocess import call
if __name__ == '__main__':
for line in sys.stdin.xreadlines():
old, new, ref = line.strip().split(' ')
if ref == 'refs/heads/master':
print "=============================================="
print "Pushing to master. Triggering jenkins. "
print "=============================================="
sys.stdout.flush()
call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])
In this case I trigger jenkins jobs only when pushing to master and not other branches.
I know that this question is old but i would like to contribute too:
The main difference between others responses is the hashmap return.
@GetMapping("...")
@ResponseBody
public Map<String, Object> endPointExample(...) {
Map<String, Object> rtn = new LinkedHashMap<>();
rtn.put("pic", image);
rtn.put("potato", "King Potato");
return rtn;
}
This will return:
{"pic":"a17fefab83517fb...beb8ac5a2ae8f0449","potato":"King Potato"}
Back in 2013, that was not possible. Microsoft didn't provide any executable for this.
See this link for some VBS way to do this. https://superuser.com/questions/201371/create-zip-folder-from-the-command-line-windows
From Windows 8 on, .NET Framework 4.5 is installed by default, with System.IO.Compression.ZipArchive and PowerShell available, one can write scripts to achieve this, see https://stackoverflow.com/a/26843122/71312
If the string is empty, comboBox.getSelectedItem().toString()
will give a NullPointerException
. So better to typecast by (String)
.
If you're using the standard SVN installation the svn:// connection will work on tcpip port 3690 and so it's basically impossible to connect unless you change your network configuration (you said only Http traffic is allowed) or you install the http module and Apache on the server hosting your SVN server.
On PyCharm Community or Professional Edition 2019.1+ :
file2.txt file3.txt
, or --myFlag myArg --anotherFlag mySecondArg
)Don't forget to seed the RNG with srand() first.
You can also use list subsetting to select the element you want to convert. It would be useful if your list had more than 1 element.
as.numeric(a[[1]])
You need to be more explicit and add the start and end times as well, down to the milliseconds:
select *
from xxx
where dates between '2012-10-26 00:00:00.000' and '2012-10-27 23:59:59.997'
The database can very well interpret '2012-10-27'
as '2012-10-27 00:00:00.000'
.
Total Commander also has a binary compare option:
go to: File \\Compare by content
ps. I guess some people may alredy be using this tool and may not be aware of the built-in feature.
pip has a --no-dependencies
switch. You should use that.
For more information, run pip install -h
, where you'll see this line:
--no-deps, --no-dependencies
Ignore package dependencies
You need to do this:
OleDbConnection connection = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet DS = new DataSet();
connection.Open();
string query =
@"SELECT tbl_Computer.*, tbl_Besitzer.*
FROM tbl_Computer
INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID
WHERE (((tbl_Besitzer.Vorname)='ma'))";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection);
DBAdapter.Fill(DS);
By the way, what is this DataSet1? This should be "DataSet".
This is because in line
graph(x**3+2*x-4, range(-10, 11))
x is not defined.
The easiest way is to pass the function you want to plot as a string and use eval
to evaluate it as an expression.
So your code with minimal modifications will be
import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
x = np.array(x_range)
y = eval(formula)
plt.plot(x, y)
plt.show()
and you can call it as
graph('x**3+2*x-4', range(-10, 11))
Using moment.js example:
var from = '11-04-2017' // OR $("#datepicker").val();
var milliseconds = moment(from, "DD-MM-YYYY").format('x');
var f = new Date(milliseconds)
Found on dotnet-snippets.de
With reflection this works and sets the real RootFolder!
using System;
using System.Reflection;
using System.Windows.Forms;
namespace YourNamespace
{
public class RootFolderBrowserDialog
{
#region Public Properties
/// <summary>
/// The description of the dialog.
/// </summary>
public string Description { get; set; } = "Chose folder...";
/// <summary>
/// The ROOT path!
/// </summary>
public string RootPath { get; set; } = "";
/// <summary>
/// The SelectedPath. Here is no initialization possible.
/// </summary>
public string SelectedPath { get; private set; } = "";
#endregion Public Properties
#region Public Methods
/// <summary>
/// Shows the dialog...
/// </summary>
/// <returns>OK, if the user selected a folder or Cancel, if no folder is selected.</returns>
public DialogResult ShowDialog()
{
var shellType = Type.GetTypeFromProgID("Shell.Application");
var shell = Activator.CreateInstance(shellType);
var folder = shellType.InvokeMember(
"BrowseForFolder", BindingFlags.InvokeMethod, null,
shell, new object[] { 0, Description, 0, RootPath, });
if (folder is null)
{
return DialogResult.Cancel;
}
else
{
var folderSelf = folder.GetType().InvokeMember(
"Self", BindingFlags.GetProperty, null,
folder, null);
SelectedPath = folderSelf.GetType().InvokeMember(
"Path", BindingFlags.GetProperty, null,
folderSelf, null) as string;
// maybe ensure that SelectedPath is set
return DialogResult.OK;
}
}
#endregion Public Methods
}
}
Please read the whole answer before attempting to run with sudo
Try running sudo /dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme
The sudo command executes the commands which follow it with 'superuser' or 'root' privileges. This should allow you to execute almost anything from the command line. That said, DON'T DO THIS! If you are running a script on your computer and don't need it to access core components of your operating system (I'm guessing you're not since you are invoking the script on something inside your home directory (~/)), then it should be running from your home directory, ie:
~/dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme
Move it to ~/ or a sub directory and execute from there. You should never have permission issues there and there wont be a risk of it accessing or modifying anything critical to your OS.
If you are still having problems you can check the permissions on the file by running ls -l
while in the same directory as the ruby script. You will get something like this:
$ ls -l
total 13
drwxr-xr-x 4 or019268 Administ 12288 Apr 10 18:14 TestWizard
drwxr-xr-x 4 or019268 Administ 4096 Aug 27 12:41 Wizard.Controls
drwxr-xr-x 5 or019268 Administ 8192 Sep 5 00:03 Wizard.UI
-rw-r--r-- 1 or019268 Administ 1375 Sep 5 00:03 readme.txt
You will notice that the readme.txt file says -rw-r--r--
on the left. This shows the permissions for that file. The 9 characters from the right can be split into groups of 3 characters of 'rwx' (read, write, execute). If I want to add execute rights to this file I would execute chmod 755 readme.txt
and that permissions portion would become rwxr-xr-x
. I can now execute this file if I want to by running ./readme.txt
(./ tells the bash to look in the current directory for the intended command rather that search the $PATH variable).
schluchc alludes to looking at the man page for chmod, do this by running man chmod
. This is the best way to get documentation on a given command, man <command>
Today, you could try editorconfig, there is also a vim plugin for it. With this, you are able not only change indentation size in vim, but in many other editors, keep consistent coding styles.
Below is a simple editorconfig, as you can see, the python files will have 4 spaces for indentation, and pug template files will only have 2.
# 4 space indentation for python files
[*.py]
indent_style = space
indent_size = 4
# 2 space indentation for pug templates
[*.pug]
indent_size = 2
You can bind key press event with your input box and returning false
if characters are more than 160 will solve the problem jsfiddle.
JavaScript:
$('textarea').keypress(function(){
if(this.value.length > 160){
return false;
}
$("#remainingC").html("Remaining characters : " + (160 - this.value.length));
});?
HTML
<textarea></textarea>?
<span id='remainingC'></span>
Take a pointer to the first element instead:
process_data (&something [0]);
I just went through this. If you want to manually move your Eclipse installation you need to find and edit relative references in the following files.
Relative to Eclipse install dir:
For me in all these files there was a ../ reference to a .p2 folder in my home directory. Found them all using a simple grep:
grep '../../../../' * -R
Then just hit it with sed or manually go change it. In my case I moved it up one folder so easy fix:
grep -rl '../../../../' * -R | xargs sed -i 's/..\/..\/..\/..\//..\/..\/..\//g'
Now Eclipse runs fine again.
http://www.quadrillian.com/ this enables you to create an entire test suite for your API and run it from your browser and share it with others.
I've been looking around for this, but then I realize, damn my website uses php!!! Why not use the trim function on the text input and play with the max length....
Here is a possible solution too for those using php: http://ideone.com/PsTaI
<?php
$s = "In the beginning there was a tree.";
$max_length = 10;
if (strlen($s) > $max_length)
{
$offset = ($max_length - 3) - strlen($s);
$s = substr($s, 0, strrpos($s, ' ', $offset)) . '...';
}
echo $s;
?>
if you think your url is valid then this will work all the time
domain = "http://google.com".split("://")[1].split("/")[0]
It seems that the only parameter that allows you to inject custom text is the "quote".
https://www.facebook.com/sharer/sharer.php?u=THE_URL"e=THE_CUSTOM_TEXT
i come across this problem cause my debug.keystore is expired, so i deleted the debug.keystore under .android folder, and the eclipse will regenerate a new debug.keystore, then i fixed th
Use substring method like this::
str.substring(str.length()-2);
Say the other guy created bar on top of foo, but you created baz in the meantime and then merged, giving a history of
$ git lola * 2582152 (HEAD, master) Merge branch 'otherguy' |\ | * c7256de (otherguy) bar * | b7e7176 baz |/ * 9968f79 foo
Note: git lola is a non-standard but useful alias.
No dice with git revert
:
$ git revert HEAD fatal: Commit 2582152... is a merge but no -m option was given.
Charles Bailey gave an excellent answer as usual. Using git revert
as in
$ git revert --no-edit -m 1 HEAD [master e900aad] Revert "Merge branch 'otherguy'" 0 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 bar
effectively deletes bar
and produces a history of
$ git lola * e900aad (HEAD, master) Revert "Merge branch 'otherguy'" * 2582152 Merge branch 'otherguy' |\ | * c7256de (otherguy) bar * | b7e7176 baz |/ * 9968f79 foo
But I suspect you want to throw away the merge commit:
$ git reset --hard HEAD^ HEAD is now at b7e7176 baz $ git lola * b7e7176 (HEAD, master) baz | * c7256de (otherguy) bar |/ * 9968f79 foo
As documented in the git rev-parse
manual
<rev>^
, e.g. HEAD^,v1.5.1^0
A suffix^
to a revision parameter means the first parent of that commit object.^<n>
means the n-th parent (i.e.<rev>^
is equivalent to<rev>^1
). As a special rule,<rev>^0
means the commit itself and is used when<rev>
is the object name of a tag object that refers to a commit object.
so before invoking git reset
, HEAD^
(or HEAD^1
) was b7e7176 and HEAD^2
was c7256de, i.e., respectively the first and second parents of the merge commit.
Be careful with git reset --hard
because it can destroy work.
You can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
I agree with @aaronasterling's answer. However, if you want a non-binary string that you can cast into an int, then you can use the canonical algorithm:
def decToBin(n):
if n==0: return ''
else:
return decToBin(n/2) + str(n%2)
A common task I experienced was having to take one repo directory in staging and copy it to another repo - both under SVN and both called the same name. The way that worked for me was the following:
svn --force delete PROBLEMATIC-DIR
svn export "https://OLD REPO-A/ new-repo-A"
svn add new-repo-A
svn commit new-repo-A
There is a C# wrapper for that which is open source, hosted on Codeplex called Web Image Cropping
Register the control
<%@ Register Assembly="CS.Web.UI.CropImage" Namespace="CS.Web.UI" TagPrefix="cs" %>
Resizing
<asp:Image ID="Image1" runat="server" ImageUrl="images/328.jpg" />
<cs:CropImage ID="wci1" runat="server" Image="Image1"
X="10" Y="10" X2="50" Y2="50" />
Cropping in code behind - Call Crop method when button clicked for example;
wci1.Crop(Server.MapPath("images/sample1.jpg"));
Convert.ToInt32(myValue);
Though I don't know what it will do when it's greater than int.MaxValue.
Here is an example from my HOW TO Matlab page:
close all; clear all;
img = imread('lena.tif','tif');
imagesc(img)
img = fftshift(img(:,:,2));
F = fft2(img);
figure;
imagesc(100*log(1+abs(fftshift(F)))); colormap(gray);
title('magnitude spectrum');
figure;
imagesc(angle(F)); colormap(gray);
title('phase spectrum');
This gives the magnitude spectrum and phase spectrum of the image. I used a color image, but you can easily adjust it to use gray image as well.
ps. I just noticed that on Matlab 2012a the above image is no longer included. So, just replace the first line above with say
img = imread('ngc6543a.jpg');
and it will work. I used an older version of Matlab to make the above example and just copied it here.
On the scaling factor
When we plot the 2D Fourier transform magnitude, we need to scale the pixel values using log transform to expand the range of the dark pixels into the bright region so we can better see the transform. We use a c
value in the equation
s = c log(1+r)
There is no known way to pre detrmine this scale that I know. Just need to
try different values to get on you like. I used 100
in the above example.
The CSS place-items shorthand property sets the align-items and justify-items properties, respectively. If the second value is not set, the first value is also used for it.
.parent {
display: grid;
place-items: center;
}
May be this tutorial link will help http://custom-android-dn.blogspot.com/2013/03/how-to-create-custom-date-time-picker.html
You can pass as many arguments as you want, separating them by commas:
{{ path('_files_manage', {project: project.id, user: user.id}) }}
If only one checkbox should be checked in the same time use RadioButtonFor instead:
@Html.RadioButtonFor(model => model.Type,1, new { @checked = "checked" }) fultime
@Html.RadioButtonFor(model => model.Type,2) party
@Html.RadioButtonFor(model => model.Type,3) next option...
If one more one could be checked in the same time use excellent extension: CheckBoxListFor:
Hope,it will help
It depends on the context.
final
class or method, the C# equivalent is sealed
.final
field, the C# equivalent is readonly
.final
local variable or method parameter, there's no direct C# equivalent.The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:
XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
where xml2.Element("ID").Value == variable
select xml2).FirstOrDefault();
This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.
Marc
There's a static method values()
which is documented, but not where you'd expect it: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
enum MyEnum {
FIRST, SECOND, THIRD;
private static MyEnum[] allValues = values();
public static MyEnum fromOrdinal(int n) {return allValues[n];}
}
In principle, you can use just values()[i]
, but there are rumors that values()
will create a copy of the array each time it is invoked.
You can use TextWatcher for TextView, is more flexible than ClickLinstener (not best or worse, only more one way).
holder.bt_foo_ex.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// code during!
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// code before!
}
@Override
public void afterTextChanged(Editable s) {
// code after!
}
});
==
is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString
do not contain "a"
, but "a\n"
(if you look closely, you'll see the extra line break in your example output).
You can use the strings.TrimRight
function to remove trailing whitespaces from your input:
if strings.TrimRight(input, "\n") == "a" {
// ...
}
I found that my dfs both had the same type column (str
) but switching from join
to merge
solved the issue.
First you have to install a module call Serial. To do that go to the folder call Scripts which is located in python installed folder. If you are using Python 3 version it's normally located in location below,
C:\Python34\Scripts
Once you open that folder right click on that folder with shift key. Then click on 'open command window here'. After that cmd
will pop up. Write the below code in that cmd
window,
pip install PySerial
and press enter.after that PySerial module will be installed. Remember to install the module u must have an INTERNET connection.
after successfully installed the module open python IDLE and write down the bellow code and run it.
import serial
# "COM11" is the port that your Arduino board is connected.set it to port that your are using
ser = serial.Serial("COM11", 9600)
while True:
cc=str(ser.readline())
print(cc[2:][:-5])
Just use only required dependency, not all :))). For me, for normal work of logging process you need this dependency exclude others from pom.xml
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.8</version>
</dependency>
Despite setting up dimensions for the columns, they still seem to shrink as the window shrinks.
An initial setting of a flex container is flex-shrink: 1
. That's why your columns are shrinking.
It doesn't matter what width you specify (it could be width: 10000px
), with flex-shrink
the specified width can be ignored and flex items are prevented from overflowing the container.
I'm trying to set up a flexbox with 3 columns where the left and right columns have a fixed width...
You will need to disable shrinking. Here are some options:
.left, .right {
width: 230px;
flex-shrink: 0;
}
OR
.left, .right {
flex-basis: 230px;
flex-shrink: 0;
}
OR, as recommended by the spec:
.left, .right {
flex: 0 0 230px; /* don't grow, don't shrink, stay fixed at 230px */
}
7.2. Components of Flexibility
Authors are encouraged to control flexibility using the
flex
shorthand rather than with its longhand properties directly, as the shorthand correctly resets any unspecified components to accommodate common uses.
More details here: What are the differences between flex-basis and width?
An additional thing I need to do is hide the right column based on user interaction, in which case the left column would still keep its fixed width, but the center column would fill the rest of the space.
Try this:
.center { flex: 1; }
This will allow the center column to consume available space, including the space of its siblings when they are removed.
In Eclipse Ganymede (3.4.0):
There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating
event.
The Validating
event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true
the TextBox doesn't lose the focus.
MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order
Enter
GotFocus
Leave
Validating
Validated
LostFocus
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:
Enter
GotFocus
LostFocus
Leave
Validating
Validated
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text != "something")
e.Cancel = true;
}
You can use the ErrorProvider
to visualize that your TextBox is not valid.
Check out Using Error Provider Control in Windows Forms and C#
Try this!!
override func viewDidLoad() {
super.viewDidLoad()
var button = UIButton.buttonWithType(.Custom) as UIButton
button.frame = CGRectMake(160, 100, 200,40)
button.layer.cornerRadius =5.0
button.layer.borderColor = UIColor.redColor().CGColor
button.layer.borderWidth = 2.0
button.setImage(UIImage(named:"Placeholder.png"), forState: .Normal)
button.addTarget(self, action: "OnClickroundButton", forControlEvents: .TouchUpInside)
button.clipsToBounds = true
view.addSubview(button)
}
func OnClickroundButton() {
NSLog(@"roundButton Method Called");
}
Few note worthy differences between List and Set in Java are given as following :
1) Fundamental difference between List and Set in Java is allowing duplicate elements. List in Java allows duplicates while Set doesn't allow any duplicate. If you insert duplicate in Set it will replace the older value. Any implementation of Set in Java will only contains unique elements.
2) Another significant difference between List and Set in Java is order. List is an Ordered Collection while Set is an unordered Collection. List maintains insertion order of elements, means any element which is inserted before will go on lower index than any element which is inserted after. Set in Java doesn't maintain any order. Though Set provide another alternative called SortedSet which can store Set elements in specific Sorting order defined by Comparable and Comparator methods of Objects stored in Set.
3) Popular implementation of List interface in Java includes ArrayList, Vector and LinkedList. While popular implementation of Set interface includes HashSet, TreeSet and LinkedHashSet.
Its pretty clear that if you need to maintain insertion order or object and you collection can contain duplicates than List is a way to go. On the other hand if your requirement is to maintain unique collection without any duplicates than Set is the way to go.
Can also use here document and vi, the below script generates a FILE.txt with 3 lines and variable interpolation
VAR=Test
vi FILE.txt <<EOFXX
i
#This is my var in text file
var = $VAR
#Thats end of text file
^[
ZZ
EOFXX
Then file will have 3 lines as below. "i" is to start vi insert mode and similarly to close the file with Esc and ZZ.
#This is my var in text file
var = Test
#Thats end of text file
Well, i agree with the @Mishkin Berteig - Agile Coach answer. Using the form is the quick way to use the POST features.
Anyway, i see some mention about javascript, but no code. I have that for my own needs, which includes jquery for easy POST plus others.
Basically, using the driver.execute_script()
you can send any javascript, including Ajax queries.
#/usr/local/env/python
# -*- coding: utf8 -*-
# proxy is used to inspect data involved on the request without so much code.
# using a basic http written in python. u can found it there: http://voorloopnul.com/blog/a-python-proxy-in-less-than-100-lines-of-code/
import selenium
from selenium import webdriver
import requests
from selenium.webdriver.common.proxy import Proxy, ProxyType
jquery = open("jquery.min.js", "r").read()
#print jquery
proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = "127.0.0.1:3128"
proxy.socks_proxy = "127.0.0.1:3128"
proxy.ssl_proxy = "127.0.0.1:3128"
capabilities = webdriver.DesiredCapabilities.PHANTOMJS
proxy.add_to_capabilities(capabilities)
driver = webdriver.PhantomJS(desired_capabilities=capabilities)
driver.get("http://httpbin.org")
driver.execute_script(jquery) # ensure we have jquery
ajax_query = '''
$.post( "post", {
"a" : "%s",
"b" : "%s"
});
''' % (1,2)
ajax_query = ajax_query.replace(" ", "").replace("\n", "")
print ajax_query
result = driver.execute_script("return " + ajax_query)
#print result
#print driver.page_source
driver.close()
# this retuns that from the proxy, and is OK
'''
POST http://httpbin.org/post HTTP/1.1
Accept: */*
Referer: http://httpbin.org/
Origin: http://httpbin.org
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.0.0 Safari/538.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 7
Cookie: _ga=GAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; _gat=1
Connection: Keep-Alive
Accept-Encoding: gzip, deflate
Accept-Language: es-ES,en,*
Host: httpbin.org
None
a=1&b=2 <<---- that is OK, is the data contained into the POST
None
'''
No, this is not supported in MySQL stored routine syntax.
Feel free to submit a feature request at bugs.mysql.com.
Check my code that will work for integer and String.
Assume our first number is 129018. And we want to add zeros to that so the the length of final string will be 10. For that you can use following code
int number=129018;
int requiredLengthAfterPadding=10;
String resultString=Integer.toString(number);
int inputStringLengh=resultString.length();
int diff=requiredLengthAfterPadding-inputStringLengh;
if(inputStringLengh<requiredLengthAfterPadding)
{
resultString=new String(new char[diff]).replace("\0", "0")+number;
}
System.out.println(resultString);
I ran into this problem and it turned out that a referenced package/assembly was being encrypted by Windows. This happened because my company implemented a policy to require the My Documents folder to be encrypted and my Visual Studio solutions happened to be under that directory.
I could manually go into the file/directory properties in Windows Explorer and disable encryption. But in my case this was a temporary solution since the network policy would eventually change it back. I wound up moving my VS solution to another un-encrypted location.
You can use a form to do a POST to the same URL.
<form method="POST" name="refresh" id="refresh">
<input type="submit" value="Refresh" />
</form>
This gives you a button that refreshes the current page. It is a bit annoying because if the user presses the browser refresh button, they will get a do you want to resubmit the form
message.
In SSRS 2016 There is an option under the properties header "Localization" called "Calendar
", if you click on this it gives you these 2 options:
This works brilliantly when referencing data from a tables aswell
alternatively if this does not work for you, specify one of these formats under "Number" and in the cell "Format
":
dd/MM/yyyy
or MM/dd/yyyy
Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.
Here is a quick example using LocalDate from the Joda Time library:
LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();
Here you can follow a quick start tutorial.
<div class="content">
Counter-Strike 1.6 Steam
<img src="images/CSsteam.png">
<a href="#">Koupit</a>
</div>
/*Use this css*/
content {
width: 182px; /*328 co je 1/3 - 20margin left*/
height: 121px;
line-height: 20px;
margin-top: 0px;
margin-left: 9px;
margin-right:0px;
display:inline-block;
position:relative;
}
content a{
display:inline-block;
padding:10px;
position:absolute;
bottom:10px;
right:10px;
}
Number(new Date(2010, 6, 26))
Works the same way as things above. If you need seconds don't forget to / 1000
For a similar effect to form's target
attribute, you can also use the formtarget
attribute of input[type="submit]"
or button[type="submit"]
.
From MDN:
...this attribute is a name or keyword indicating where to display the response that is received after submitting the form. This is a name of, or keyword for, a browsing context (for example, tab, window, or inline frame). If this attribute is specified, it overrides the target attribute of the elements's form owner. The following keywords have special meanings:
- _self: Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
- _blank: Load the response into a new unnamed browsing context.
- _parent: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self.
- _top: Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as _self.
GetUserId()
is an extension method on IIdentity
and it is in Microsoft.AspNet.Identity.IdentityExtensions
. Make sure you have added the namespace with using Microsoft.AspNet.Identity;
.
Convert the integer into a string and then you can use the STUFF function to insert in your colons into time string. Once you've done that you can convert the string into a time datatype.
SELECT CAST(STUFF(STUFF(STUFF(cast(23421155 as varchar),3,0,':'),6,0,':'),9,0,'.') AS TIME)
That should be the simplest way to convert it to a time without doing anything to crazy.
In your example you also had an int where the leading zeros are not there. In that case you can simple do something like this:
SELECT CAST(STUFF(STUFF(STUFF(RIGHT('00000000' + CAST(421151 AS VARCHAR),8),3,0,':'),6,0,':'),9,0,'.') AS TIME)
There we have another possibility to remove a property value from the CSS.
Like using the replace method in js. But you have to know exactly the ID of the style, or you can write a for loop to detecting that by (count styles on the page, then check if any of those 'includes' or 'match' an !important
value. & you can count also - how much contains them, or just simply write a global [regexp: /str/gi] replacing method)
Mine is very simple, but I attach a jsBin, for example:
https://jsbin.com/geqodeg/edit?html,css,js,output
First I set the body background in CSS for yellow !important
, then I overrided by JS for darkPink.
In some cases this is the best way because your code may have change something and j=i+1 won't check that.
for (int i = 0; i < list.size(); i++){
for (int j = 0; j < list.size(); j++) {
if(i == j) {
//to do code here
continue;
}
}
}
A requirement for text-overflow: ellipsis;
to work is a one-line version of white-space
(pre
, nowrap
etc). Which means the text will never reach the second line.
Ergo. Not possible in pure CSS.
My source when I was looking for the exact same thing just now: http://www.quirksmode.org/css/textoverflow.html (Quirksmode ftw!)
EDIT If the good CSS gods will implement http://www.w3.org/TR/css-overflow-3/#max-lines we can haz this in pure CSS using fragments
(new) and max-lines
(new). Also some more info on http://css-tricks.com/line-clampin/
EDIT 2 WebKit/Blink has line-clamp
: -webkit-line-clamp: 2
will put ellipsis on 2nd line.
I know it's a bit late but, Microsoft has made their Xaml.Behaviors open source and it's now much easier to use interactivity with just one namespace.
Then use it like this,
<Button Width="150" Style="{DynamicResource MaterialDesignRaisedDarkButton}">
<behaviours:Interaction.Triggers>
<behaviours:EventTrigger EventName="Click">
<behaviours:InvokeCommandAction Command="{Binding OpenCommand}" PassEventArgsToCommand="True"/>
</behaviours:EventTrigger>
</behaviours:Interaction.Triggers>
Open
</Button>
PassEventArgsToCommand="True" should be set as True and the RelayCommand that you implement can take RoutedEventArgs or objects as template. If you are using object as the parameter type just cast it to the appropriate event type.
The command will look something like this,
OpenCommand = new RelayCommand<object>(OnOpenClicked, (o) => { return true; });
The command method will look something like this,
private void OnOpenClicked(object parameter)
{
Logger.Info(parameter?.GetType().Name);
}
The 'parameter' will be the Routed event object.
And the log incase you are curious,
2020-12-15 11:40:36.3600|INFO|MyApplication.ViewModels.MainWindowViewModel|RoutedEventArgs
As you can see the TypeName logged is RoutedEventArgs
RelayCommand impelmentation can be found here.
PS : You can bind to any event of any control. Like Closing event of Window and you will get the corresponding events.
Your code isn't working, because the hidden attibute is not supported in versions of IE before v11
If you need to support IE before version 11, add a CSS style to hide when the hidden attribute is present:
*[hidden] { display: none; }
I tried to use the suggestions above and in the process improved upon the solutions in this thread.
Let us say you use a base class (ObservableObject in this case) that implements the PropertyChanged Event, you would do something like this. I will probably write a blog post one day in my blog sqljana.wordpress.com
Please do substitute the values for the first three variables:
--These three things have to be substituted (when called from Powershell, they are replaced before execution)
DECLARE @Schema VARCHAR(MAX) = N'&Schema'
DECLARE @TableName VARCHAR(MAX) = N'&TableName'
DECLARE @Namespace VARCHAR(MAX) = N'&Namespace'
DECLARE @CRLF VARCHAR(2) = CHAR(13) + CHAR(10);
DECLARE @result VARCHAR(max) = ' '
DECLARE @PrivateProp VARCHAR(100) = @CRLF +
CHAR(9) + CHAR(9) + 'private <ColumnType> _<ColumnName>;';
DECLARE @PublicProp VARCHAR(255) = @CRLF +
CHAR(9) + CHAR(9) + 'public <ColumnType> <ColumnName> ' + @CRLF +
CHAR(9) + CHAR(9) + '{ ' + @CRLF +
CHAR(9) + CHAR(9) + ' get { return _<ColumnName>; } ' + @CRLF +
CHAR(9) + CHAR(9) + ' set ' + @CRLF +
CHAR(9) + CHAR(9) + ' { ' + @CRLF +
CHAR(9) + CHAR(9) + ' _<ColumnName> = value;' + @CRLF +
CHAR(9) + CHAR(9) + ' base.RaisePropertyChanged();' + @CRLF +
CHAR(9) + CHAR(9) + ' } ' + @CRLF +
CHAR(9) + CHAR(9) + '}' + @CRLF;
DECLARE @RPCProc VARCHAR(MAX) = @CRLF +
CHAR(9) + CHAR(9) + 'public event PropertyChangedEventHandler PropertyChanged; ' + @CRLF +
CHAR(9) + CHAR(9) + 'private void RaisePropertyChanged( ' + @CRLF +
CHAR(9) + CHAR(9) + ' [CallerMemberName] string caller = "" ) ' + @CRLF +
CHAR(9) + CHAR(9) + '{ ' + @CRLF +
CHAR(9) + CHAR(9) + ' if (PropertyChanged != null) ' + @CRLF +
CHAR(9) + CHAR(9) + ' { ' + @CRLF +
CHAR(9) + CHAR(9) + ' PropertyChanged( this, new PropertyChangedEventArgs( caller ) ); ' + @CRLF +
CHAR(9) + CHAR(9) + ' } ' + @CRLF +
CHAR(9) + CHAR(9) + '}';
DECLARE @PropChanged VARCHAR(200) = @CRLF +
CHAR(9) + CHAR(9) + 'protected override void AfterPropertyChanged(string propertyName) ' + @CRLF +
CHAR(9) + CHAR(9) + '{ ' + @CRLF +
CHAR(9) + CHAR(9) + ' System.Diagnostics.Debug.WriteLine("' + @TableName + ' property changed: " + propertyName); ' + @CRLF +
CHAR(9) + CHAR(9) + '}';
SET @result = 'using System;' + @CRLF + @CRLF +
'using MyCompany.Business;' + @CRLF + @CRLF +
'namespace ' + @Namespace + @CRLF + '{' + @CRLF +
' public class ' + @TableName + ' : ObservableObject' + @CRLF +
' {' + @CRLF +
' #region Instance Properties' + @CRLF
SELECT @result = @result
+
REPLACE(
REPLACE(@PrivateProp
, '<ColumnName>', ColumnName)
, '<ColumnType>', ColumnType)
+
REPLACE(
REPLACE(@PublicProp
, '<ColumnName>', ColumnName)
, '<ColumnType>', ColumnType)
FROM
(
SELECT c.COLUMN_NAME AS ColumnName
, CASE c.DATA_TYPE
WHEN 'bigint' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int64?' ELSE 'Int64' END
WHEN 'binary' THEN 'Byte[]'
WHEN 'bit' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Boolean?' ELSE 'Boolean' END
WHEN 'char' THEN 'String'
WHEN 'date' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'datetime' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'datetime2' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'datetimeoffset' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTimeOffset?' ELSE 'DateTimeOffset' END
WHEN 'decimal' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'float' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Single?' ELSE 'Single' END
WHEN 'image' THEN 'Byte[]'
WHEN 'int' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int32?' ELSE 'Int32' END
WHEN 'money' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'nchar' THEN 'String'
WHEN 'ntext' THEN 'String'
WHEN 'numeric' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'nvarchar' THEN 'String'
WHEN 'real' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Double?' ELSE 'Double' END
WHEN 'smalldatetime' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'smallint' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int16?' ELSE 'Int16'END
WHEN 'smallmoney' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'text' THEN 'String'
WHEN 'time' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'TimeSpan?' ELSE 'TimeSpan' END
WHEN 'timestamp' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'tinyint' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Byte?' ELSE 'Byte' END
WHEN 'uniqueidentifier' THEN 'Guid'
WHEN 'varbinary' THEN 'Byte[]'
WHEN 'varchar' THEN 'String'
ELSE 'Object'
END AS ColumnType
, c.ORDINAL_POSITION
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.TABLE_NAME = @TableName
AND ISNULL(@Schema, c.TABLE_SCHEMA) = c.TABLE_SCHEMA
) t
ORDER BY t.ORDINAL_POSITION
SELECT @result = @result + @CRLF +
CHAR(9) + '#endregion Instance Properties' + @CRLF +
--CHAR(9) + @RPCProc + @CRLF +
CHAR(9) + @PropChanged + @CRLF +
CHAR(9) + '}' + @CRLF +
@CRLF + '}'
--SELECT @result
PRINT @result
The base class is based on Josh Smith's article here From http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/
I did rename the class to be called ObservableObject and also took advantage of a c# 5 feature using the CallerMemberName attribute
//From http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/
//
//Jana's change: Used c# 5 feature to bypass passing in the property name using [CallerMemberName]
// protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace MyCompany.Business
{
/// <summary>
/// Implements the INotifyPropertyChanged interface and
/// exposes a RaisePropertyChanged method for derived
/// classes to raise the PropertyChange event. The event
/// arguments created by this class are cached to prevent
/// managed heap fragmentation.
/// </summary>
[Serializable]
public abstract class ObservableObject : INotifyPropertyChanged
{
#region Data
private static readonly Dictionary<string, PropertyChangedEventArgs> eventArgCache;
private const string ERROR_MSG = "{0} is not a public property of {1}";
#endregion // Data
#region Constructors
static ObservableObject()
{
eventArgCache = new Dictionary<string, PropertyChangedEventArgs>();
}
protected ObservableObject()
{
}
#endregion // Constructors
#region Public Members
/// <summary>
/// Raised when a public property of this object is set.
/// </summary>
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Returns an instance of PropertyChangedEventArgs for
/// the specified property name.
/// </summary>
/// <param name="propertyName">
/// The name of the property to create event args for.
/// </param>
public static PropertyChangedEventArgs
GetPropertyChangedEventArgs(string propertyName)
{
if (String.IsNullOrEmpty(propertyName))
throw new ArgumentException(
"propertyName cannot be null or empty.");
PropertyChangedEventArgs args;
// Get the event args from the cache, creating them
// and adding to the cache if necessary.
lock (typeof(ObservableObject))
{
bool isCached = eventArgCache.ContainsKey(propertyName);
if (!isCached)
{
eventArgCache.Add(
propertyName,
new PropertyChangedEventArgs(propertyName));
}
args = eventArgCache[propertyName];
}
return args;
}
#endregion // Public Members
#region Protected Members
/// <summary>
/// Derived classes can override this method to
/// execute logic after a property is set. The
/// base implementation does nothing.
/// </summary>
/// <param name="propertyName">
/// The property which was changed.
/// </param>
protected virtual void AfterPropertyChanged(string propertyName)
{
}
/// <summary>
/// Attempts to raise the PropertyChanged event, and
/// invokes the virtual AfterPropertyChanged method,
/// regardless of whether the event was raised or not.
/// </summary>
/// <param name="propertyName">
/// The property which was changed.
/// </param>
protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
{
this.VerifyProperty(propertyName);
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
// Get the cached event args.
PropertyChangedEventArgs args =
GetPropertyChangedEventArgs(propertyName);
// Raise the PropertyChanged event.
handler(this, args);
}
this.AfterPropertyChanged(propertyName);
}
#endregion // Protected Members
#region Private Helpers
[Conditional("DEBUG")]
private void VerifyProperty(string propertyName)
{
Type type = this.GetType();
// Look for a public property with the specified name.
PropertyInfo propInfo = type.GetProperty(propertyName);
if (propInfo == null)
{
// The property could not be found,
// so alert the developer of the problem.
string msg = string.Format(
ERROR_MSG,
propertyName,
type.FullName);
Debug.Fail(msg);
}
}
#endregion // Private Helpers
}
}
Here is the part that you guys are going to like some more. I built a Powershell script to generate for all the tables in a SQL database. It is based on a Powershell guru named Chad Miller's Invoke-SQLCmd2 cmdlet which can be downloaded from here: http://gallery.technet.microsoft.com/ScriptCenter/7985b7ef-ed89-4dfd-b02a-433cc4e30894/
Once you have that cmdlet, the Powershell script to generate for all tables becomes simple (do substitute the variables with your specific values).
. C:\MyScripts\Invoke-Sqlcmd2.ps1
$serverInstance = "MySQLInstance"
$databaseName = "MyDb"
$generatorSQLFile = "C:\MyScripts\ModelGen.sql"
$tableListSQL = "SELECT name FROM $databaseName.sys.tables"
$outputFolder = "C:\MyScripts\Output\"
$namespace = "MyCompany.Business"
$placeHolderSchema = "&Schema"
$placeHolderTableName = "&TableName"
$placeHolderNamespace = "&Namespace"
#Get the list of tables in the database to generate c# models for
$tables = Invoke-Sqlcmd2 -ServerInstance $serverInstance -Database $databaseName -Query $tableListSQL -As DataRow -Verbose
foreach ($table in $tables)
{
$table1 = $table[0]
$outputFile = "$outputFolder\$table1.cs"
#Replace variables with values (returns an array that we convert to a string to use as query)
$generatorSQLFileWSubstitutions = (Get-Content $generatorSQLFile).
Replace($placeHolderSchema,"dbo").
Replace($placeHolderTableName, $table1).
Replace($placeHolderNamespace, $namespace) | Out-String
"Ouputing for $table1 to $outputFile"
#The command generates .cs file content for model using "PRINT" statements which then gets written to verbose output (stream 4)
# ...capture the verbose output and redirect to a file
(Invoke-Sqlcmd2 -ServerInstance $serverInstance -Database $databaseName -Query $generatorSQLFileWSubstitutions -Verbose) 4> $outputFile
}
Use the .val() method.
Also I think you meant to use $("#txtEmail")
as $("txtEmail")
returns elements of type <txtEmail>
which you probably don't have.
See here at the jQuery documentation.
Also jQuery val() method.
Using a return
will stop the function and return undefined
, or the value that you specify with the return command.
function myfunction(){
if(a=="stop"){
//return undefined;
return; /** Or return "Hello" or any other value */
}
}
To dynamically construct the returnUrl in any View, try this:
@{
var formCollection =
new FormCollection
{
new FormCollection(Request.Form),
new FormCollection(Request.QueryString)
};
var parameters = new RouteValueDictionary();
formCollection.AllKeys
.Select(k => new KeyValuePair<string, string>(k, formCollection[k])).ToList()
.ForEach(p => parameters.Add(p.Key, p.Value));
}
<!-- Option #1 -->
@Html.ActionLink("Option #1", "Action", "Controller", parameters, null)
<!-- Option #2 -->
<a href="/Controller/Action/@[email protected](ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), parameters)">Option #2</a>
<!-- Option #3 -->
<a href="@Url.Action("Action", "Controller", new { object.ID, returnUrl = Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), parameters) }, null)">Option #3</a>
This also works in Layout Pages, Partial Views and Html Helpers
Related: MVC3 Dynamic Return URL (Same but from within any Controller/Action)
The dependencies syntax is located at the Dependency Version Requirement Specification documentation. Here it is is for completeness:
Dependencies'
version
element define version requirements, used to compute effective dependency version. Version requirements have the following syntax:
1.0
: "Soft" requirement on 1.0 (just a recommendation, if it matches all other ranges for the dependency)[1.0]
: "Hard" requirement on 1.0(,1.0]
: x <= 1.0[1.2,1.3]
: 1.2 <= x <= 1.3[1.0,2.0)
: 1.0 <= x < 2.0[1.5,)
: x >= 1.5(,1.0],[1.2,)
: x <= 1.0 or x >= 1.2; multiple sets are comma-separated(,1.1),(1.1,)
: this excludes 1.1 (for example if it is known not to work in combination with this library)
In your case, you could do something like <version>[1.2.3,)</version>
Leaving out the parenthesis and simply calling 'setParameter' now works with at least Hibernate.
String jpql = "from A where name in :names";
Query q = em.createQuery(jpql);
q.setParameter("names", l);
With the images located in /screen-shots
directory. The outer <div>
allows the images to be positioned. Padding is achieved using <img width="desired-padding" height="0">
.
<div align="center">
<img width="45%" src="screen-shots/about.PNG" alt="About screen" title="About screen"</img>
<img height="0" width="8px">
<img width="45%" src="screen-shots/list.PNG" alt="List screen" title="List screen"></img>
</div>
The auto-completion with Jupyter Notebook is so weak, even with hinterland extension. Thanks for the idea of deep-learning-based code auto-completion. I developed a Jupyter Notebook Extension based on TabNine which provides code auto-completion based on Deep Learning. Here's the Github link of my work: jupyter-tabnine.
It's available on pypi index now. Simply issue following commands, then enjoy it:)
pip3 install jupyter-tabnine
jupyter nbextension install --py jupyter_tabnine
jupyter nbextension enable --py jupyter_tabnine
jupyter serverextension enable --py jupyter_tabnine
Instead of creating strange things, you can just filter()
and then map()
your result.
This is much more readable and sure. Streams will make it in only one loop.
No. Any valid string is a valid key. It can even have "
as long as you escape it:
{"The \"meaning\" of life":42}
There is perhaps a chance you'll encounter difficulties loading such values into some languages, which try to associate keys with object field names. I don't know of any such cases, however.
If you need time stamp as a string.
time_t result = time(NULL);
NSString *timeStampString = [@(result) stringValue];
I always prefer to use mixins for small CSS classes like fade in / out incase you want to use them in more than one class.
@mixin fade-in {
opacity: 1;
animation-name: fadeInOpacity;
animation-iteration-count: 1;
animation-timing-function: ease-in;
animation-duration: 2s;
}
@keyframes fadeInOpacity {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
and if you don't want to use mixins, you can create a normal class .fade-in.
We can Increasing the maximum limit using .htaccess
file.
php_value session.gc_maxlifetime 10800
php_value max_input_time 10800
php_value max_execution_time 10800
php_value upload_max_filesize 110M
php_value post_max_size 120M
If sometimes other way are not working, this way is working perfect.
This is an old question, but all the answers I've found on SO, including more recent ones, are answered similarly to this one. However, in .Net 4.5 / MVC 4 you can add email address validation to a form by adding the [EmailAddress] annotation from System.ComponentModel.DataAnnotations, so I was wondering why I couldn't just use the built-in functionality from .Net in general.
This seems to work, and seems to me to be fairly elegant:
using System.ComponentModel.DataAnnotations;
class ValidateSomeEmails
{
static void Main(string[] args)
{
var foo = new EmailAddressAttribute();
bool bar;
bar = foo.IsValid("[email protected]"); //true
bar = foo.IsValid("[email protected]"); //true
bar = foo.IsValid("[email protected]"); //true
bar = foo.IsValid("[email protected]"); //true
bar = foo.IsValid("fdsa"); //false
bar = foo.IsValid("fdsa@"); //false
bar = foo.IsValid("fdsa@fdsa"); //false
bar = foo.IsValid("fdsa@fdsa."); //false
//one-liner
if (new EmailAddressAttribute().IsValid("[email protected]"))
bar = true;
}
}
Use time
.
Not the Bash builtin time
, but the one you can find with which time
, for example /usr/bin/time
.
Here's what it covers, on a simple ls
:
$ /usr/bin/time --verbose ls
(...)
Command being timed: "ls"
User time (seconds): 0.00
System time (seconds): 0.00
Percent of CPU this job got: 0%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 2372
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 1
Minor (reclaiming a frame) page faults: 121
Voluntary context switches: 2
Involuntary context switches: 9
Swaps: 0
File system inputs: 256
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
tooltips can be used as alerts. These can be timed to appear and disappear.
CSS can be used to create tooltips and menus. More info on this can be found in 'Javascript for Dummies'. Sorry about the label of this book... Not infuring anything.
Reading other peoples answers here, I realized the answer to my own thoughts/questions. SetTimeOut could be applied to tooltips. Javascript could trigger them.
The real reason you want to use NVARCHAR is when you have different languages in the same column, you need to address the columns in T-SQL without decoding, you want to be able to see the data "natively" in SSMS, or you want to standardize on Unicode.
If you treat the database as dumb storage, it is perfectly possible to store wide strings and different (even variable-length) encodings in VARCHAR (for instance UTF-8). The problem comes when you are attempting to encode and decode, especially if the code page is different for different rows. It also means that the SQL Server will not be able to deal with the data easily for purposes of querying within T-SQL on (potentially variably) encoded columns.
Using NVARCHAR avoids all this.
I would recommend NVARCHAR for any column which will have user-entered data in it which is relatively unconstrained.
I would recommend VARCHAR for any column which is a natural key (like a vehicle license plate, SSN, serial number, service tag, order number, airport callsign, etc) which is typically defined and constrained by a standard or legislation or convention. Also VARCHAR for user-entered, and very constrained (like a phone number) or a code (ACTIVE/CLOSED, Y/N, M/F, M/S/D/W, etc). There is absolutely no reason to use NVARCHAR for those.
So for a simple rule:
VARCHAR when guaranteed to be constrained NVARCHAR otherwise
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
SEQUENCES like it works on firebird:
-- =======================================================
CREATE TABLE SEQUENCES
(
NM_SEQUENCE VARCHAR(32) NOT NULL UNIQUE,
VR_SEQUENCE BIGINT NOT NULL
);
-- =======================================================
-- Creates a sequence sSeqName and set its initial value.
-- =======================================================
DROP PROCEDURE IF EXISTS CreateSequence;
DELIMITER :)
CREATE PROCEDURE CreateSequence( sSeqName VARCHAR(32), iSeqValue BIGINT )
BEGIN
IF NOT EXISTS ( SELECT * FROM SEQUENCES WHERE (NM_SEQUENCE = sSeqName) ) THEN
INSERT INTO SEQUENCES (NM_SEQUENCE, VR_SEQUENCE)
VALUES (sSeqName , iSeqValue );
END IF;
END :)
DELIMITER ;
-- CALL CreateSequence( 'MySequence', 0 );
-- =======================================================================
-- Increments the sequence value of sSeqName by iIncrement and returns it.
-- If iIncrement is zero, returns the current value of sSeqName.
-- =======================================================================
DROP FUNCTION IF EXISTS GetSequenceVal;
DELIMITER :)
CREATE FUNCTION GetSequenceVal( sSeqName VARCHAR(32), iIncrement INTEGER )
RETURNS BIGINT -- iIncrement can be negative
BEGIN
DECLARE iSeqValue BIGINT;
SELECT VR_SEQUENCE FROM SEQUENCES
WHERE ( NM_SEQUENCE = sSeqName )
INTO @iSeqValue;
IF ( iIncrement <> 0 ) THEN
SET @iSeqValue = @iSeqValue + iIncrement;
UPDATE SEQUENCES SET VR_SEQUENCE = @iSeqValue
WHERE ( NM_SEQUENCE = sSeqName );
END IF;
RETURN @iSeqValue;
END :)
DELIMITER ;
-- SELECT GetSequenceVal('MySequence', 1); -- Adds 1 to MySequence value and returns it.
-- ===================================================================
Let me emphasise that Docker doesn't even allow mixed characters.
Good:
docker build -t myfirstechoimage:0.1 .
Bad:
docker build -t myFirstEchoImage:0.1 .
List<string> empnames = emplist.Select(e => e.Ename).ToList();
This is an example of Projection in Linq. Followed by a ToList
to resolve the IEnumerable<string>
into a List<string>
.
Alternatively in Linq syntax (head compiled):
var empnamesEnum = from emp in emplist
select emp.Ename;
List<string> empnames = empnamesEnum.ToList();
Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).
For example, you can project an enumerable of Employee
to an enumerable of Tuple<int, string>
like so:
var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));
UISegmentedControl.appearance().setTitleTextAttributes(NSDictionary(objects: [UIFont.systemFont(ofSize: 16.0)],
forKeys: [kCTFontAttributeName as! NSCopying]) as? [AnyHashable : Any],
for: UIControlState.normal)
Full Screen Custom Alert Dialog Class in Kotlin
Create XML file, same as you would an activity
Create AlertDialog custom class
class Your_Class(context:Context) : AlertDialog(context){
init {
requestWindowFeature(Window.FEATURE_NO_TITLE)
setCancelable(false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.your_Layout)
val window = this.window
window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT)
//continue custom code here
//call dismiss() to close
}
}
Call the dialog within the activity
val dialog = Your_Class(this)
//can set some dialog options here
dialog.show()
Note**: If you do not want your dialog to be full screen, delete the following lines
val window = this.window
window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT)
Then edit the layout_width & layout_height of your top layout within your XML file to be either wrap_content or a fixed DP value.
I generally do not recommend using fixed DP as you would likely want your app to be adaptable to multiple screen sizes, however if you keep your size values small enough you should be fine
GCC works fine. Note that MSVC is not necessarily a valid solution because it does not support C99.
It's not possible to change user within a shell script. Workarounds using sudo described in other answers are probably your best bet.
If you're mad enough to run perl scripts as root, you can do this with the $< $( $> $)
variables which hold real/effective uid/gid, e.g.:
#!/usr/bin/perl -w
$user = shift;
if (!$<) {
$> = getpwnam $user;
$) = getgrnam $user;
} else {
die 'must be root to change uid';
}
system('whoami');
I tried this it works
open
vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php
and change this
$conf[CURLOPT_SSL_VERIFYHOST] = 2;
`enter code here`$conf[CURLOPT_SSL_VERIFYPEER] = true;
to this
$conf[CURLOPT_SSL_VERIFYHOST] = 0;
$conf[CURLOPT_SSL_VERIFYPEER] = FALSE;
First you need to define a LocationListener
to handle location changes.
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
//your code here
}
};
Then get the LocationManager
and ask for location updates
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListener);
}
And finally make sure that you have added the permission on the Manifest,
For using only network based location use this one
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
For GPS based location, this one
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
use -fno-objc-arc for each file in build phases
No Problem You can use onClick()
function easily without using any other interference of language,
<?php
echo '<br><Button onclick="document.getElementById(';?>'modal-wrapper2'<?php echo ').style.display=';?>'block'<?php echo '" name="comment" style="width:100px; color: white;background-color: black;border-radius: 10px; padding: 4px;">Show</button>';
?>
You can specify the remote’s URL by applying the UNC path to the file protocol. This requires you to use four slashes:
git clone file:////<host>/<share>/<path>
For example, if your main machine has the IP 192.168.10.51 and the computer name main
, and it has a share named code
which itself is a git repository, then both of the following commands should work equally:
git clone file:////main/code
git clone file:////192.168.10.51/code
If the Git repository is in a subdirectory, simply append the path:
git clone file:////main/code/project-repository
git clone file:////192.168.10.51/code/project-repository
I know this is an old question but it's ranking high on search engines in regards to this issue.
properties in the FileList object cannot be deleted but at least on Firefox they can be changed. My workaround this issue was to add a property IsValid=true
to those files that passed check and IsValid=false
to those that didn't.
then I just loop through the list to make sure that only the properties with IsValid=true
are added to FormData.
You can use continue
if condition:
continue
else:
#do something
zerkms told you the difference. If you like you can "convert" a string to an array of strings with length of 1.
If you want to send the string as a argument for example you can do like this:
var myString = "Test";
MethodThatRequiresStringArrayAsParameter( new[]{myString} );
I honestly can't see any other reason of doing the conversion than to satisty a method argument, but if it's another reason you will have to provide some information as to what you are trying to accomplish since there is probably a better solution.
not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
The native lib is expected in one of the following locations
/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib
and not in
tomcat/lib
The files in tomcat/lib
are all jar
file and are added by tomcat to the classpath
so that they are available to your application.
The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar
, for linux it could be a .so
file, for windows it could be a .dll
file.
Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.
Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.
org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms
EDIT
The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.
If you are troubling with running your servlet then after the run on sever
command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.
It should be something like that
http://localhost:8080/<your-context-name>/<your-servlet-name>
EDIT 2
Try to call your servlet using the following url
http://localhost:8080/com.filecounter/FileCounter
Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF
.
It is better to configure your servlets there using servlet-name
servlet-class
and url-mapping
. It could look like that:
<servlet>
<description></description>
<display-name>File counter - My first servlet</display-name>
<servlet-name>file_counter</servlet-name>
<servlet-class>com.filecounter.FileCounter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>file_counter</servlet-name>
<url-pattern>/FileFounter</url-pattern>
</servlet-mapping>
In eclipse dynamic web project the default context name is the same as your project name.
http://localhost:8080/<your-context-name>/FileCounter
will work too.
Its simple
$(function() {
$("#datePicker").datetimepicker({
defaultDate:'now'
});
});
This will set today as default
Managed to get the input field value by doing something like this:
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
username : ''
}
this.updateInput = this.updateInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
updateInput(event){
this.setState({username : event.target.value})
}
handleSubmit(){
console.log('Your input value is: ' + this.state.username)
//Send state to the server code
}
render(){
return (
<div>
<input type="text" onChange={this.updateInput}></input>
<input type="submit" onClick={this.handleSubmit} ></input>
</div>
);
}
}
//output
//Your input value is: x
<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
Password
<input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>
look into this
If you're using CloudFlare, you can just create a Page Rule to always use HTTPS: This will redirect every http:// request to https://
In addition to that, you would also have to add something like this to your \app\Providers\AppServiceProvider.php boot() function:
if (env('APP_ENV') === 'production' || env('APP_ENV') === 'dev') {
\URL::forceScheme('https');
}
This would ensure that every link / path in your app is using https:// instead of http://.
??!
is a trigraph that translates to |
. So it says:
!ErrorHasOccured() || HandleError();
which, due to short circuiting, is equivalent to:
if (ErrorHasOccured())
HandleError();
Guru of the Week (deals with C++ but relevant here), where I picked this up.
Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.
From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):
The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.
Because in Python 3, print statement
has been replaced with a print() function
, with keyword arguments to replace most of the special syntax of the old print statement. So you have to write it as
print("Hello World")
But if you write this in a program and someone using Python 2.x tries to run it, they will get an error. To avoid this, it is a good practice to import print function:
from __future__ import print_function
Now your code works on both 2.x & 3.x.
Check out below examples also to get familiar with print() function.
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not the same as print(x, y)!
Source: What’s New In Python 3.0?
Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent. That event listener analyzes bubbled events to find a match on child elements.
JavaScript Example :
Let's say that we have a parent UL element with several child elements:
<ul id="parent-list">
<li id="post-1">Item 1</li>
<li id="post-2">Item 2</li>
<li id="post-3">Item 3</li>
<li id="post-4">Item 4</li>
<li id="post-5">Item 5</li>
<li id="post-6">Item 6</li>
</ul>
Let's also say that something needs to happen when each child element is clicked. You could add a separate event listener to each individual LI element, but what if LI elements are frequently added and removed from the list? Adding and removing event listeners would be a nightmare, especially if addition and removal code is in different places within your app. The better solution is to add an event listener to the parent UL element. But if you add the event listener to the parent, how will you know which element was clicked?
Simple: when the event bubbles up to the UL element, you check the event object's target property to gain a reference to the actual clicked node. Here's a very basic JavaScript snippet which illustrates event delegation:
// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a list item
if(e.target && e.target.nodeName == "LI") {
// List item found! Output the ID!
console.log("List item ", e.target.id.replace("post-"), " was clicked!");
}
});
Start by adding a click event listener to the parent element. When the event listener is triggered, check the event element to ensure it's the type of element to react to. If it is an LI element, boom: we have what we need! If it's not an element that we want, the event can be ignored. This example is pretty simple -- UL and LI is a straight-forward comparison. Let's try something more difficult. Let's have a parent DIV with many children but all we care about is an A tag with the classA CSS class:
// Get the parent DIV, add click listener...
document.getElementById("myDiv").addEventListener("click",function(e) {
// e.target was the clicked element
if(e.target && e.target.nodeName == "A") {
// Get the CSS classes
var classes = e.target.className.split(" ");
// Search for the CSS class!
if(classes) {
// For every CSS class the element has...
for(var x = 0; x < classes.length; x++) {
// If it has the CSS class we want...
if(classes[x] == "classA") {
// Bingo!
console.log("Anchor element clicked!");
// Now do something here....
}
}
}
}
});
In my case below code
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="10dp" android:bottom="-10dp"
>
<shape android:shape="rectangle">
<solid android:color="@color/maincolor" />
<corners
android:topLeftRadius="10dp"
android:topRightRadius="10dp"
android:bottomLeftRadius="0dp"
android:bottomRightRadius="0dp"
/>
</shape>
</item>
</layer-list>
In Java 8:
static <E> E getRandomSetElement(Set<E> set) {
return set.stream().skip(new Random().nextInt(set.size())).findFirst().orElse(null);
}
This solution matches the process name more strictly:
ps -Ac -o pid,comm | awk '/^ *[0-9]+ Dropbox$/ {print $1}'
This solution has the following advantages:
tail -f ~/Dropbox
~/Dropbox/foo.sh
~/DropboxUID.sh
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
Log.v("", is3g + " ConnectivityManager Test " + isWifi);
if (!is3g && !isWifi) {
Toast.makeText(
getApplicationContext(),
"Please make sure, your network connection is ON ",
Toast.LENGTH_LONG).show();
}
else {
// Put your function() to go further;
}
I know it is quite old, but testing in the browser:
$0.value=null; // when $0 is the file upload element we talking about
erased the value and allow me to rechoose THE SAME FILE as before (means it worked!)
Tested in Chrome 81, FF 76, Safari (on iPad mini), 360 browser, Baidu browser, QQ browser, android browser.
As per my point of view that files selected can be more than 1, you'd better not set the value to a string - the final value sits in $0.files which may be more than 1. The browser need to parse the selected values from "value", so it is an active property. Set it to null, as per my understanding, will cause the browser to parse it to [] empty list in $0.files (this is what happened...)
Another approach here:
.checkbox-wrapper {
white-space: nowrap
}
.checkbox {
vertical-align: top;
display:inline-block
}
.checkbox-label {
white-space: normal
display:inline-block
}
<div class="text-left checkbox-wrapper">
<input type="checkbox" id="terms" class="checkbox">
<label class="checkbox-label" for="terms">I accept whatever you want!</label>
</div>
Here is HTML5-only solution (if you want minlength 5, maxlength 10 character validation)
http://jsfiddle.net/xhqsB/102/
<form>
<input pattern=".{5,10}">
<input type="submit" value="Check"></input>
</form>
Let's us consider you have string like
example : "name:lucy,age:21,gender:female"
function getJsonData(query){_x000D_
let arrayOfKeyValues = query.split(',');_x000D_
let modifiedArray = new Array();_x000D_
console.log(arrayOfKeyValues);_x000D_
for(let i=0;i< arrayOfKeyValues.length;i++){_x000D_
let arrayValues = arrayOfKeyValues[i].split(':');_x000D_
let arrayString ='"'+arrayValues[0]+'"'+':'+'"'+arrayValues[1]+'"';_x000D_
modifiedArray.push(arrayString);_x000D_
}_x000D_
let jsonDataString = '{'+modifiedArray.toString()+'}';_x000D_
let jsonData = JSON.parse(jsonDataString);_x000D_
console.log(jsonData);_x000D_
console.log(typeof jsonData);_x000D_
return jsonData;_x000D_
}_x000D_
_x000D_
let query = "name:lucy,age:21,gender:female";_x000D_
let response = getJsonData(query);_x000D_
console.log(response);
_x000D_
`
In my case, while playing video, I needed to call a function everytime currentTime
of video updates. So I used timeupdate
event of video and I came to know that it was fired at least 4 times a second (depends on the browser you use, see this). So I changed it to call a function every second like this:
var currentIntTime = 0;
var someFunction = function() {
currentIntTime++;
// Do something here
}
vidEl.on('timeupdate', function(){
if(parseInt(vidEl.currentTime) > currentIntTime) {
someFunction();
}
});
This reduces calls to someFunc
by at least 1/3
and it may help your browser to behave normally. It did for me !!!
You will need to get a DateTime
object from your TimeSpan
and then you can format it easily.
One possible solution is adding the timespan to any date with zero time value.
var timespan = new TimeSpan(3, 0, 0);
var output = new DateTime().Add(timespan).ToString("hh:mm tt");
The output value will be "03:00 AM"
(for english locale).
std::atomic
exists because many ISAs have direct hardware support for it
What the C++ standard says about std::atomic
has been analyzed in other answers.
So now let's see what std::atomic
compiles to to get a different kind of insight.
The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and std::atomic
basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.
This support allows for faster alternatives to more general methods such as std::mutex
, which can make more complex multi-instruction sections atomic, at the cost of being slower than std::atomic
because std::mutex
it makes futex
system calls in Linux, which is way slower than the userland instructions emitted by std::atomic
, see also: Does std::mutex create a fence?
Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.
main.cpp
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
size_t niters;
#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif
void threadMain() {
for (size_t i = 0; i < niters; ++i) {
#if LOCK
__asm__ __volatile__ (
"lock incq %0;"
: "+m" (global),
"+g" (i) // to prevent loop unrolling
:
:
);
#else
__asm__ __volatile__ (
""
: "+g" (i) // to prevent he loop from being optimized to a single add
: "g" (global)
:
);
global++;
#endif
}
}
int main(int argc, char **argv) {
size_t nthreads;
if (argc > 1) {
nthreads = std::stoull(argv[1], NULL, 0);
} else {
nthreads = 2;
}
if (argc > 2) {
niters = std::stoull(argv[2], NULL, 0);
} else {
niters = 10;
}
std::vector<std::thread> threads(nthreads);
for (size_t i = 0; i < nthreads; ++i)
threads[i] = std::thread(threadMain);
for (size_t i = 0; i < nthreads; ++i)
threads[i].join();
uint64_t expect = nthreads * niters;
std::cout << "expect " << expect << std::endl;
std::cout << "global " << global << std::endl;
}
Compile, run and disassemble:
comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out $common
g++ -o main_std_atomic.out -DSTD_ATOMIC $common
g++ -o main_lock.out -DLOCK $common
./main_fail.out 4 100000
./main_std_atomic.out 4 100000
./main_lock.out 4 100000
gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out
Extremely likely "wrong" race condition output for main_fail.out
:
expect 400000
global 100000
and deterministic "right" output of the others:
expect 400000
global 400000
Disassembly of main_fail.out
:
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: mov 0x29b5(%rip),%rcx # 0x5140 <niters>
0x000000000000278b <+11>: test %rcx,%rcx
0x000000000000278e <+14>: je 0x27b4 <threadMain()+52>
0x0000000000002790 <+16>: mov 0x29a1(%rip),%rdx # 0x5138 <global>
0x0000000000002797 <+23>: xor %eax,%eax
0x0000000000002799 <+25>: nopl 0x0(%rax)
0x00000000000027a0 <+32>: add $0x1,%rax
0x00000000000027a4 <+36>: add $0x1,%rdx
0x00000000000027a8 <+40>: cmp %rcx,%rax
0x00000000000027ab <+43>: jb 0x27a0 <threadMain()+32>
0x00000000000027ad <+45>: mov %rdx,0x2984(%rip) # 0x5138 <global>
0x00000000000027b4 <+52>: retq
Disassembly of main_std_atomic.out
:
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: cmpq $0x0,0x29b4(%rip) # 0x5140 <niters>
0x000000000000278c <+12>: je 0x27a6 <threadMain()+38>
0x000000000000278e <+14>: xor %eax,%eax
0x0000000000002790 <+16>: lock addq $0x1,0x299f(%rip) # 0x5138 <global>
0x0000000000002799 <+25>: add $0x1,%rax
0x000000000000279d <+29>: cmp %rax,0x299c(%rip) # 0x5140 <niters>
0x00000000000027a4 <+36>: ja 0x2790 <threadMain()+16>
0x00000000000027a6 <+38>: retq
Disassembly of main_lock.out
:
Dump of assembler code for function threadMain():
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: cmpq $0x0,0x29b4(%rip) # 0x5140 <niters>
0x000000000000278c <+12>: je 0x27a5 <threadMain()+37>
0x000000000000278e <+14>: xor %eax,%eax
0x0000000000002790 <+16>: lock incq 0x29a0(%rip) # 0x5138 <global>
0x0000000000002798 <+24>: add $0x1,%rax
0x000000000000279c <+28>: cmp %rax,0x299d(%rip) # 0x5140 <niters>
0x00000000000027a3 <+35>: ja 0x2790 <threadMain()+16>
0x00000000000027a5 <+37>: retq
Conclusions:
the non-atomic version saves the global to a register, and increments the register.
Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of 100000
.
std::atomic
compiles to lock addq
. The LOCK prefix makes the following inc
fetch, modify and update memory atomically.
our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic
, except that our inc
is used instead of add
. Not sure why GCC chose add
, considering that our INC generated a decoding 1 byte smaller.
ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?
Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.
Why not just use .show()/.hide()
instead?
$("#menu").hover(function(){
$('.flyout').show();
},function(){
$('.flyout').hide();
});
I would rather write a little JavaScript than make the CSS less manageable.
First, only apply the CSS animation on a data attribute change:
.progbar[data-animation="barshine"] {
animation: barshine 1s linear;
}
Then add javascript to toggle the animation at half the delay amount.
var progbar = document.querySelector('.progbar');
var on = false;
setInterval(function () {
progbar.setAttribute('data-animation', (on) ? 'barshine' : '');
on = !on;
}, 3000);
Or if you don't want the animation to run when the tab is hidden:
var progbar = document.querySelector('.progbar');
var on = false;
var update = function () {
progbar.setAttribute('data-animation', (on) ? 'barshine' : '');
on = !on;
setTimer();
};
var setTimer = function () {
setTimeout(function () {
requestAnimationFrame(update);
}, 3000);
};
setTimer();
This fixed the problem by having it as the first two lines of the script:
!pip install opencv-python
!apt update && apt install -y libsm6 libxext6
!apt-get install -y libxrender-dev
JObject implements IDictionary, so you can use it that way. For ex,
var cycleJson = JObject.Parse(@"{""name"":""john""}");
//add surname
cycleJson["surname"] = "doe";
//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });
So the final json will be
{
"name": "john",
"surname": "doe",
"complexObj": {
"id": 1,
"name": "test"
}
}
You can also use dynamic
keyword
dynamic cycleJson = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });
Set KeyboardType Property :- Number Pad TextField Delegate please write below code
func textField(_ textField: UITextField, shouldChangeCharactersIn
range: NSRange, replacementString string: String) -> Bool {
if textField.text?.count == 0 && string == "0" {
return false
}
return string == string.filter("0123456789".contains)
}
Number should not start from 0 and entered number +ve.
You use jQuery.noConflict();
So $
is undefined.
You can read more about it here docs
Try to modify your code in this way (add $
sign to ready function):
jQuery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
});
You may consider writing a generic escape function:
def mk_esc(esc_chars):
return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
>>> esc = mk_esc('&#')
>>> print esc('Learn & be #1')
Learn \& be \#1
This way you can make your function configurable with a list of character that should be escaped.
Lets say you have Class A as superclass and Class B subclass of A.
public class A {
public void printFromA(){
System.out.println("Inside A");
}
}
public class B extends A {
public void printFromB(){
System.out.println("Inside B");
}
}
public class MainClass {
public static void main(String []args){
A a = new B();
a.printFromA(); //this can be called without typecasting
((B)a).printFromB(); //the method printFromB needs to be typecast
}
}
There are two important concepts in multithreading environment:
The volatile
keyword eradicates visibility problems, but it does not deal with atomicity. volatile
will prevent the compiler from reordering instructions which involve a write and a subsequent read of a volatile variable; e.g. k++
.
Here, k++
is not a single machine instruction, but three:
So, even if you declare a variable as volatile
, this will not make this operation atomic; this means another thread can see a intermediate result which is a stale or unwanted value for the other thread.
On the other hand, AtomicInteger
, AtomicReference
are based on the Compare and swap instruction. CAS has three operands: a memory location V
on which to operate, the expected old value A
, and the new value B
. CAS
atomically updates V
to the new value B
, but only if the value in V
matches the expected old value A
; otherwise, it does nothing. In either case, it returns the value currently in V
. The compareAndSet()
methods of AtomicInteger
and AtomicReference
take advantage of this functionality, if it is supported by the underlying processor; if it is not, then the JVM implements it via spin lock.
If you are using RESTful resources you can do the following:
redirect_to action_name_resource_path(resource_object, param_1: 'value_1', param_2: 'value_2')
or
#You can also use the object_id instead of the object
redirect_to action_name_resource_path(resource_object_id, param_1: 'value_1', param_2: 'value_2')
or
#if its a collection action like index, you can omit the id as follows
redirect_to action_name_resource_path(param_1: 'value_1', param_2: 'value_2')
#An example with nested resource is as follows:
redirect_to edit_user_project_path(@user, @project, param_1: 'value_1', param_2: 'value_2')
Thanks for your great question, this has caught me out a few times. When using dataURI HTML source, I find that I have to define a complete HTML document.
See below a modified example.
var html = '<html><head></head><body>Foo</body></html>';
var iframe = document.createElement('iframe');
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
take note of the html content wrapped with <html>
tags and the iframe.src
string.
The iframe element needs to be added to the DOM tree to be parsed.
document.body.appendChild(iframe);
You will not be able to inspect the iframe.contentDocument
unless you disable-web-security
on your browser.
You'll get a message
DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://localhost:7357" from accessing a cross-origin frame.
How about your own adapter/wrapper ?
//adapter.js
var adapter = (function() {
return {
post: function (url, params) {
adapter.ajax(url, "post", params);
},
get: function (url, params) {
adapter.ajax(url, "get", params);
},
put: function (url, params) {
adapter.ajax(url, "put", params);
},
delete: function (url, params) {
adapter.ajax(url, "delete", params);
},
ajax: function (url, type, params) {
var ajaxOptions = {
type: type.toUpperCase(),
url: url,
success: function (data, status) {
var msgType = "";
// checkStatus here if you haven't include data.success = true in your
// response object
if ((params.checkStatus && status) ||
(data.success && data.success == true)) {
msgType = "success";
params.onSuccess && params.onSuccess(data);
} else {
msgType = "danger";
params.onError && params.onError(data);
}
},
error: function (xhr) {
params.onXHRError && params.onXHRError();
//api.showNotificationWindow(xhr.statusText, "danger");
}
};
if (params.data) ajaxOptions.data = params.data;
if (api.isJSON(params.data)) {
ajaxOptions.contentType = "application/json; charset=utf-8";
ajaxOptions.dataType = "json";
}
$.ajax($.extend(ajaxOptions, params.options));
}
})();
//api.js
var api = {
return {
isJSON: function (json) {
try {
var o = JSON.parse(json);
if (o && typeof o === "object" && o !== null) return true;
} catch (e) {}
return false;
}
}
})();
And extremely simple usage:
adapter.post("where/to/go", {
data: JSON.stringify(params),
onSuccess: function (data) {
//on success response...
}
//, onError: function(data) { //on error response... }
//, onXHRError: function(xhr) { //on XHR error response... }
});
The answer has already been found although I would also like to share my answer:
int main(void)
{
using namespace std;
short tempC;
cout << "Please enter a Celsius value: ";
cin >> tempC;
double tempF = convert(tempC);
cout << tempC << " degrees Celsius is " << tempF << " degrees Fahrenheit." << endl;
cin.get();
cin.get();
return 0;
}
int convert(short nT)
{
return nT * 1.8 + 32;
}
This is a more proper way to do this; however, it is slightly more complex then what you were going for.
Simple way Object [] - can be use as an? dimention tuple
As the error says, you need to make sure that your sql server is running and listening on port 1433. If server is running then you need to check whether there is some firewall rule rejecting the connection on port 1433.
Here are the commands that can be useful to troubleshoot:
netstat -a
to check whether sql server is listening on the desired porttelnet
on the host and portNot a direct answer to your question.. But following is the only syntax that used to work for me -
data: '{"winNumber": "' + win + '"}',
And the parameter-name match with the argument of the server method
Manifold provides Java with C#-style extension methods and several other features. Unlike other tools, Manifold has no limitations and does not suffer from issues with generics, lambdas, IDE etc. Manifold provides several other features such as F#-style custom types, TypeScript-style structural interfaces, and Javascript-style expando types.
Additionally, IntelliJ provides comprehensive support for Manifold via the Manifold plugin.
Manifold is an open source project available on github.