The most modern answer, taken from Valloric's comment above:
git mv old/submod new/submod
git status
.)git commit
and you're good to go!Done!
All the answers assume that the functions can be accessed through global scope (window). However, the OP did not make this assumption.
If the functions live in a local scope (aka closure) and are not referenced by some other local object, bad luck: You have to use eval()
AFAIK, see
dynamically call local function in javascript
It was suggested by Mark Mishyn to use slice but there is no reason to create array with make
and use in for
returned slice of it when array created via literal can be used and it's shorter
for i := range [5]int{} {
fmt.Println(i)
}
There is of course a lubridate
solution for this:
library(lubridate)
date <- "2009-10-01"
ymd(date) - 5
# [1] "2009-09-26"
is the same as
ymd(date) - days(5)
# [1] "2009-09-26"
Other time formats could be:
ymd(date) - months(5)
# [1] "2009-05-01"
ymd(date) - years(5)
# [1] "2004-10-01"
ymd(date) - years(1) - months(2) - days(3)
# [1] "2008-07-29"
Maybe a bit delayed, but technologies have evolved since so there is certainly new info around which draws fresh light on the matter...
As iOS has yet to open up an API for WiFi Direct and Multipeer Connectivity is iOS only, I believe the best way to approach this is to use BLE, which is supported by both platforms (some better than others).
On iOS a device can act both as a BLE Central and BLE Peripheral at the same time, on Android the situation is more complex as not all devices support the BLE Peripheral state. Also the Android BLE stack is very unstable (to date).
If your use case is feature driven, I would suggest to look at Frameworks and Libraries that can achieve cross platform communication for you, without you needing to build it up from scratch.
For example: http://p2pkit.io or google nearby
Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.
Maintain a list of nodes you can travel to, sorted by the distance from your start node. In the beginning only your start node will be in the list.
While you haven't reached your destination: Visit the node closest to the start node, this will be the first node in your sorted list. When you visit a node, add all its neighboring nodes to your list except the ones you have already visited. Repeat!
Apple states about NSSearchPathForDirectoriesInDomains(_:_:_:)
:
You should consider using the
FileManager
methodsurls(for:in:)
andurl(for:in:appropriateFor:create:)
which return URLs, which are the preferred format.
With Swift 5, FileManager
has a method called contentsOfDirectory(at:includingPropertiesForKeys:options:)
. contentsOfDirectory(at:includingPropertiesForKeys:options:)
has the following declaration:
Performs a shallow search of the specified directory and returns URLs for the contained items.
func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: FileManager.DirectoryEnumerationOptions = []) throws -> [URL]
Therefore, in order to retrieve the urls of the files contained in documents directory, you can use the following code snippet that uses FileManager
's urls(for:in:)
and contentsOfDirectory(at:includingPropertiesForKeys:options:)
methods:
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
// Print the urls of the files contained in the documents directory
print(directoryContents)
} catch {
print("Could not search for urls of files in documents directory: \(error)")
}
As an example, the UIViewController
implementation below shows how to save a file from app bundle to documents directory and how to get the urls of the files saved in documents directory:
import UIKit
class ViewController: UIViewController {
@IBAction func copyFile(_ sender: UIButton) {
// Get file url
guard let fileUrl = Bundle.main.url(forResource: "Movie", withExtension: "mov") else { return }
// Create a destination url in document directory for file
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let documentDirectoryFileUrl = documentsDirectory.appendingPathComponent("Movie.mov")
// Copy file to document directory
if !FileManager.default.fileExists(atPath: documentDirectoryFileUrl.path) {
do {
try FileManager.default.copyItem(at: fileUrl, to: documentDirectoryFileUrl)
print("Copy item succeeded")
} catch {
print("Could not copy file: \(error)")
}
}
}
@IBAction func displayUrls(_ sender: UIButton) {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
// Print the urls of the files contained in the documents directory
print(directoryContents) // may print [] or [file:///private/var/mobile/Containers/Data/Application/.../Documents/Movie.mov]
} catch {
print("Could not search for urls of files in documents directory: \(error)")
}
}
}
An expression like this:
[a-zA-Z]*[0-9\+\*][a-zA-Z0-9\+\*]*
should work just fine (obviously insert any additional special characters you want to allow or use ^ operator to match anything except letters/numbers); no need to use complicated lookarounds. This approach makes sense if you only want to allow a certain subset of special characters that you know are "safe", and disallow all others.
If you want to include all special characters except certain ones which you know are "unsafe", then it makes sense to use something like:
\w[^\\]*[^a-zA-Z\\][^\\]*
In this case, you are explicitly disallowing backslashes in your password and allowing any combination with at least one non-alphabetic character otherwise.
The expression above will match any string containing letters and at least one number or +,*. As for the "length of 8" requirement, theres really no reason to check that using regex.
This is not an appropriate use of regular expressions. You'd be better off using
[0-9]{2}/[0-9]{2}/[0-9]{4}
and then checking ranges in a higher-level language.
What is wrong with List<T>.Sort()
?
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort#overloads
i guess you are using Me version, i suggest to add this block of function manually, in your code (JSONArray.java) :
public Object remove(int index) {
Object o = this.opt(index);
this.myArrayList.removeElementAt(index);
return o;
}
In java version they use ArrayList, in ME Version they use Vector.
You can use, contentEquals() function. It may help you..
Apart form these two methods from answer above.
onBackPressed() (API Level 5, Android 2.0)
onKeyDown() (API Level 1, Android 1.0)
You can also override the dispatchKeyEvent()
(API Level 1, Android 1.0) like this,
dispatchKeyEvent()
(API Level 1, Android 1.0)
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// TODO Auto-generated method stub
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.dispatchKeyEvent(event);
}
If you want to remove the column completely (i.e. not just the button) from the table then use a suitable event handler, e.g. for the OnDataBound
event, and then hide the appropriate column on the target GridView
. Pick an event that will only fire once for this control, i.e. not OnRowDataBound
.
<asp:GridView ID="grdUsers" runat="server" DataSourceID="dsProjectUsers" OnDataBound="grdUsers_DataBound">
<Columns>
<asp:TemplateField HeaderText="Admin Actions">
<ItemTemplate><asp:Button ID="btnEdit" runat="server" text="Edit" /></ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="Telephone" HeaderText="Telephone" />
</Columns>
</asp:GridView>
protected void grdUsers_DataBound(object sender, EventArgs e)
{
try
{
// in this case hiding the first col if not admin
if (!User.IsInRole(Constants.Role_Name_Admin))
grdUsers.Columns[0].Visible = false;
}
catch (Exception ex)
{
// deal with ex
}
}
private String getCurrentStackTraceString() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
return Arrays.stream(stackTrace).map(StackTraceElement::toString)
.collect(Collectors.joining("\n"));
}
A Swift3 version:
extension UIView {
func startRotate() {
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = NSNumber(value: M_PI * 2)
rotation.duration = 2
rotation.isCumulative = true
rotation.repeatCount = FLT_MAX
self.layer.add(rotation, forKey: "rotationAnimation")
}
func stopRotate() {
self.layer.removeAnimation(forKey: "rotationAnimation")
}
}
And remember to call startRotate
in viewWillAppear
not in viewDidLoad
.
Today we use Bearer token
more often that Basic Authentication
but if you want to have Basic Authentication
first to get Bearer token then there is a couple ways:
const request = new XMLHttpRequest();
request.open('GET', url, false, username,password)
request.onreadystatechange = function() {
// D some business logics here if you receive return
if(request.readyState === 4 && request.status === 200) {
console.log(request.responseText);
}
}
request.send()
Full syntax is here
Second Approach using Ajax:
$.ajax
({
type: "GET",
url: "abc.xyz",
dataType: 'json',
async: false,
username: "username",
password: "password",
data: '{ "key":"sample" }',
success: function (){
alert('Thanks for your up vote!');
}
});
Hopefully, this provides you a hint where to start API calls with JS. In Frameworks like Angular, React, etc there are more powerful ways to make API call with Basic Authentication
or Oauth Authentication
. Just explore it.
answer
shouldn't be a pointer, the intent is obviously to hold a character. scanf
takes the address of this character, so it should be called as
char answer;
scanf(" %c", &answer);
Next, your "or" statement is formed incorrectly.
if (answer == 'Y' || answer == 'y')
What you wrote originally asks to compare answer
with the result of 'Y' || 'y'
, which I'm guessing isn't quite what you wanted to do.
I've just had a similar problem, and had to use the <div>
inside the <td>
at first (John MacIntyre's solution didn't work for me for various reasons).
Note though that <td><div>...</div></td>
isn't valid placement for a div so instead I'm using a <span>
with display:block;
set. It validates fine now and works.
For Eclipse in Macbook it is just 2 click process:
Basically the difference between them are performance characteristics and blocking behavior.
Taking the easiest first, ArrayBlockingQueue
is a queue of a fixed size. So if you set the size at 10, and attempt to insert an 11th element, the insert statement will block until another thread removes an element. The fairness issue is what happens if multiple threads try to insert and remove at the same time (in other words during the period when the Queue was blocked). A fairness algorithm ensures that the first thread that asks is the first thread that gets. Otherwise, a given thread may wait longer than other threads, causing unpredictable behavior (sometimes one thread will just take several seconds because other threads that started later got processed first). The trade-off is that it takes overhead to manage the fairness, slowing down the throughput.
The most important difference between LinkedBlockingQueue
and ConcurrentLinkedQueue
is that if you request an element from a LinkedBlockingQueue
and the queue is empty, your thread will wait until there is something there. A ConcurrentLinkedQueue
will return right away with the behavior of an empty queue.
Which one depends on if you need the blocking. Where you have many producers and one consumer, it sounds like it. On the other hand, where you have many consumers and only one producer, you may not need the blocking behavior, and may be happy to just have the consumers check if the queue is empty and move on if it is.
You can use String.Remove
to delete from a specified position to the end of the string.
myString = myString.Remove(myString.Length - 3);
there is a simple procedure to do it go to controlpanel->system and security ->system->advanced system settings->advanced->environment variables
then add new path enter this in your variable path and values
Make sure, under Run > Debug Configurations, that 'Stop in main' is selected, if applicable to your situation.
Navigate to your www directory (if you are using wamp server) htdocs (if on XAMPP). Open your admin.php and search on project contents/ or just go directly to line number 339 and change the link, inserting 'local host to the link .
That should work ,,
Try this...
var start = new Date(document.getElementById('Stardate').value);
var y = start.getFullYear();
eq
matcher if you don't use other matchers..verify(mock)
. You are now initiating verification on the result of the method call, without verifying anything (not making a method call). Hence all tests are passing.You code should look like:
Mockito.verify(mock).mymethod(obj);
Mockito.verify(mock).mymethod(null);
Mockito.verify(mock).mymethod("something_else");
You can do this without nohup:
ssh user@host 'myprogram >out.log 2>err.log &'
Click the line number, and then copy and paste the link from the address bar. To select a range, click the number, and then shift click the later number.
Alternatively, the links are a relatively simple format, just append #L<number>
to the end for that specific line number, using the link to the file. Here's a link to the third line of the git
repository's README
:
I have just made a solution for it. I made a library for this to do that in a reusable way that's why you don't need to recode in your XML. Here is documentation on how to use it in Java and Kotlin. First, initialize it from an activity from where you want to show the overlay-
AppWaterMarkBuilder.doConfigure()
.setAppCompatActivity(MainActivity.this)
.setWatermarkProperty(R.layout.layout_water_mark)
.showWatermarkAfterConfig();
Then you can hide and show it from anywhere in your app -
/* For hiding the watermark*/
AppWaterMarkBuilder.hideWatermark()
/* For showing the watermark*/
AppWaterMarkBuilder.showWatermark()
Gif preview -
The trim() method removes whitespace from both sides of a string.
To remove all the spaces from the string use .replace(/\s/g, "")
this.maintabinfo = this.inner_view_data.replace(/\s/g, "").toLowerCase();
The difference between Control.Invoke()
and Control.BeginInvoke()
is,
BeginInvoke()
will schedule the asynchronous action on the GUI thread. When the asynchronous action is scheduled, your code continues. Some time later (you don't know exactly when) your asynchronous action will be executedInvoke()
will execute your asynchronous action (on the GUI thread) and wait until your action has completed.A logical conclusion is that a delegate you pass to Invoke()
can have out-parameters or a return-value, while a delegate you pass to BeginInvoke()
cannot (you have to use EndInvoke to retrieve the results).
ORDER BY column OFFSET 0 ROWS
Surprisingly makes it work, what a strange feature.
A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:
;WITH cte AS (
SELECT .....long select statement here....
)
SELECT * FROM
(
SELECT * FROM
( -- necessary to nest selects for union to work with where & order clauses
SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS
) first
UNION ALL
SELECT * FROM
(
SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS
) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example
So we get all results ordered by MainCol
But the results with MainCol = 1
get ordered by ColX
And the results with MainCol = 0
get ordered by ColY
Use attribute binding syntax instead
<ol class="viewer-nav"><li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value">{{ section.text }}</li>
</ol>
or
<ol class="viewer-nav"><li *ngFor="let section of sections"
attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>
</ol>
First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:
ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");
Then inject the mock into m_orderSvc and call your method.
m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
Finally, verify that the mock was called properly:
verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");
I'm disappointed at how long it took to work this out.
I want to see which values in my range are outside standard deviation.
=STDEV(L3:L32)*2
=$L$32
(whatever cell your stdev is in)I couldn't work out how to put the STDEv inline. I tried many things with unexpected results.
I got this error while executing a MySQL script in an Intellij console, because of adding brackets in the wrong place:
WRONG:
SELECT user.id
FROM user
WHERE id IN (:ids); # Do not put brackets around list argument
RIGHT:
SELECT user.id
FROM user
WHERE id IN :ids; # No brackets is correct
I'd rather use more convenient itemSelect
event. With this event you can use org.primefaces.event.SelectEvent
objects in your listener.
<p:selectOneMenu ...>
<p:ajax event="itemSelect"
update="messages"
listener="#{beanMB.onItemSelectedListener}"/>
</p:selectOneMenu>
With such listener:
public void onItemSelectedListener(SelectEvent event){
MyItem selectedItem = (MyItem) event.getObject();
//do something with selected value
}
You can add your styles in the required page after the external style sheet so they'll cascade and overwrite the first set of rules.
<link rel="stylesheet" href="allpages.css">
<style>
.flex-control-thumbs li {
width: auto;
float: none;
}
</style>
For people coming from the future, you can now do this purely in CSS.
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
margin: 5rem;
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
width: 120px;
bottom: 100%;
left: 50%;
margin-left: -60px;
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
}
_x000D_
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
_x000D_
Personally, I do not accept a whitespace ($STR3) as being 'not empty'.
When a variable that only contains whitespaces is passed onto a parameter, it will often error that the parameters value may not be '$null', instead of saying it may not be a whitespace, some remove commands might remove a root folder instead of a subfolder if the subfolder name is a "white space", all the reason not to accept a string containing whitespaces in many cases.
I find this is the best way to accomplish it:
$STR1 = $null
IF ([string]::IsNullOrWhitespace($STR1)){'empty'} else {'not empty'}
Empty
$STR2 = ""
IF ([string]::IsNullOrWhitespace($STR2)){'empty'} else {'not empty'}
Empty
$STR3 = " "
IF ([string]::IsNullOrWhitespace($STR3)){'empty !! :-)'} else {'not Empty :-('}
Empty!! :-)
$STR4 = "Nico"
IF ([string]::IsNullOrWhitespace($STR4)){'empty'} else {'not empty'}
Not empty
.my_btn{
font-family:Arial;
font-size:10pt;
font-weight:normal;
height:30px;
line-height:30px;
width:98px;
border:0px;
background-image:url('../Images/menu_image.png');
cursor:pointer;
}
<asp:Button ID="clickme" runat="server" Text="Click" CssClass="my_btn" />
Yes, it's possible to use inline if-expressions:
{{ 'Update' if files else 'Continue' }}
If you don't mind using an external library, Lodash has lots of wonderful utilities
var people = [
{
"f_name":"john",
"l_name":"doe",
"sequence":"0",
"title":"president",
"url":"google.com",
"color":"333333"
},
{
"f_name":"michael",
"l_name":"goodyear",
"sequence":"0",
"title":"general manager",
"url":"google.com",
"color":"333333"
}
];
var sorted = _.sortBy(people, "l_name")
You can also sort by multiple properties. Here's a plunk showing it in action
Not this exact problem, but this is the top result when googling for almost the exact same error:
If you see this problem calling a WCF Service hosted on the same machine, you may need to populate the BackConnectionHostNames
registry key
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0
MSV1_0
, point to New, and then click Multi-String Value
.BackConnectionHostNames
, and then press ENTER.BackConnectionHostNames
, and then click Modify.
In the Value data box, type the CNAME or the DNS alias, that is used for the local shares on the computer, and then click OK.
See Calling WCF service hosted in IIS on the same machine as client throws authentication error for details.
I used a BoxLayout
and set its second parameter as BoxLayout.Y_AXIS
and it worked for me:
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
First Question: Difference between parseInt and valueOf in java?
Second Question:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();
Third Question:
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(symbols);
df.parse(p);
@dhobbs's answer is great!
but simply change to easy get the level info
def print_list_dir(dir):
print("=" * 64)
print("[PRINT LIST DIR] %s" % dir)
print("=" * 64)
for root, dirs, files in os.walk(dir):
level = root.replace(dir, '').count(os.sep)
indent = '| ' * level
print('{}{} \\'.format(indent, os.path.basename(root)))
subindent = '| ' * (level + 1)
for f in files:
print('{}{}'.format(subindent, f))
print("=" * 64)
and the output like
================================================================
[PRINT LIST DIR] ./
================================================================
\
| os_name.py
| json_loads.py
| linspace_python.py
| list_file.py
| to_gson_format.py
| type_convert_test.py
| in_and_replace_test.py
| online_log.py
| padding_and_clipping.py
| str_tuple.py
| set_test.py
| script_name.py
| word_count.py
| get14.py
| np_test2.py
================================================================
you can get the level by |
count!
$('#next').click( function(){
$('#colored_background option:selected').next('option').attr('selected', 'selected');
changeBackgroundColor();
});
Working at What is my favorite color?. Click on the arrows.
You don't have to delete the entire Cache folder. you lose all settings / preferences The workspace mappings are stored in a file called:
VersionControl.config under the users local settings/application data directory. located here in windows 7:
%LocalAppData%\Microsoft\Team Foundation\x.0\Cache\Volatile
where x= 3.0,4.0, 5.0,6.0 etc.
Inside this you will find guid named folders , open each of them, manually editing the forementioned file, to remove the workspace mapping(directory path will be present in mappedpaths attribute) from that local folder to the TFS server (which is no longer in usage).
"Better" is subjective.
querySelector
is the newer feature.
getElementById
is better supported than querySelector
.
querySelector
is better supported than getElementsByClassName
.
querySelector
lets you find elements with rules that can't be expressed with getElementById
and getElementsByClassName
You need to pick the appropriate tool for any given task.
(In the above, for querySelector
read querySelector
/ querySelectorAll
).
I don't know if there's a 'proper' way to do it, but your snippet is on the right track: just add import foo
to foo.py, do inspect.getmembers(foo)
, and it should work fine.
Use convert with style 101.
select convert(datetime, Remarks, 101)
If your column is really text
you need to convert to varchar before converting to datetime
select convert(datetime, convert(varchar(30), Remarks), 101)
The answer is in the documentation:
Real partial mocks (Since 1.8.0)
Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.
Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users. Read more about spying: here or in javadoc for spy(Object) method.
callRealMethod()
was introduced after spy()
, but spy() was left there of course, to ensure backward compatibility.
Otherwise, you're right: all the methods of a spy are real unless stubbed. All the methods of a mock are stubbed unless callRealMethod()
is called. In general, I would prefer using callRealMethod()
, because it doesn't force me to use the doXxx().when()
idiom instead of the traditional when().thenXxx()
I've faced same problem with my registry then i tried the solution listed below from a blog page. It works.
You can list your catalogs by calling this url:
http://YourPrivateRegistyIP:5000/v2/_catalog
Response will be in the following format:
{
"repositories": [
<name>,
...
]
}
You can list tags of your catalog by calling this url:
http://YourPrivateRegistyIP:5000/v2/<name>/tags/list
Response will be in the following format:
{
"name": <name>,
"tags": [
<tag>,
...
]
}
You can run this command in docker registry container:
curl -v --silent -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X GET http://localhost:5000/v2/<name>/manifests/<tag> 2>&1 | grep Docker-Content-Digest | awk '{print ($3)}'
Response will be in the following format:
sha256:6de813fb93debd551ea6781e90b02f1f93efab9d882a6cd06bbd96a07188b073
Run the command given below with manifest value:
curl -v --silent -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X DELETE http://127.0.0.1:5000/v2/<name>/manifests/sha256:6de813fb93debd551ea6781e90b02f1f93efab9d882a6cd06bbd96a07188b073
Run this command in your docker registy container:
bin/registry garbage-collect /etc/docker/registry/config.yml
Here is my config.yml
root@c695814325f4:/etc# cat /etc/docker/registry/config.yml
version: 0.1
log:
fields:
service: registry
storage:
cache:
blobdescriptor: inmemory
filesystem:
rootdirectory: /var/lib/registry
delete:
enabled: true
http:
addr: :5000
headers:
X-Content-Type-Options: [nosniff]
health:
storagedriver:
enabled: true
interval: 10s
threshold: 3
You may have a table called 'test'
COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER
To quote a quote:
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).
.data()
- jQuery Documentiation
Note that this (Frankly odd) limitation is only withheld to the use of .data()
.
The solution? Use .attr
instead.
Of course, several of you may feel uncomfortable with not using it's dedicated method. Consider the following scenario:
Common sense - Why would they change an already established attribute like that? Just imagine class
begin renamed to group and id
to identifier. The Internet would break.
And even then, Javascript itself has the ability to fix this - And of course, despite it's infamous incompatibility with HTML, REGEX (And a variety of similar methods) could rapidly rename your attributes to this new-mythical 'standard'.
TL;DR
alert($(targetField).attr("data-helptext"));
This is very tricky in Python.
I'll first comment on why you're having that problem and then I will mention two possible solutions.
You must take this paragraph from the Python documentation into consideration:
Note that relative imports are based on the name of the current module. Since the name of the main module is always "main", modules intended for use as the main module of a Python application must always use absolute imports.
And also the following from PEP 328:
Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
Relative imports work from the filename (__name__
attribute), which can take two values:
package.test_A.test
Here Python knows the parent directories: before test
comes test_A
and then package
.
So you can use the dot notation for relative import.# package.test_A/test.py
from ..A import foo
You can then have like a root file in the root directory which calls test.py
:
# root.py
from package.test_A import test
test.py
) directly, it becomes the entry point to the program , so __name__
== __main__
. The filename has no indication of the directory structure, so Python doesn't know how to go up in the directory. For Python, test.py
becomes the top-level script, there is nothing above it. That's why you cannot use relative import.A) One way to solve this is to have a root file (in the root directory) which calls the modules/packages, like this:
root.py
imports test.py
. (entry point, __name__ == __main__
).test.py
(relative) imports foo.py
.foo.py
says the module has been imported.The output is:
package.A.foo has been imported
Module's name is: package.test_A.test
B) If you want to execute the code as a module and not as a top-level script, you can try this from the command line:
python -m package.test_A.test
Any suggestions are welcomed.
You should also check: Relative imports for the billionth time , specially BrenBarn's answer.
The most upvoted answer is not implementing a real slide in/out (or down/up), as:
translateY(-100%)
and then suddenly disappears, causing another glitch on the elements below it.You can implement a slide in and slide out like so:
my-component.ts
import { animate, style, transition, trigger } from '@angular/animations';
@Component({
...
animations: [
trigger('slideDownUp', [
transition(':enter', [style({ height: 0 }), animate(500)]),
transition(':leave', [animate(500, style({ height: 0 }))]),
]),
],
})
my-component.html
<div @slideDownUp *ngIf="isShowing" class="box">
I am the content of the div!
</div>
my-component.scss
.box {
overflow: hidden;
}
When you go to "Application Settings -> Add Domain" It will ask to select login account, probably you are already on gmail account so it will show gmail account as well, but you should use Google Apps account where you have mapped your custom domain.
In C A ternary operator " ? : " is available to construct conditional expressions of the form
exp1 ? exp2:exp3
where exp1,exp2 and exp3 are expressions
for Example
a=20;
b=25;
x=(a>b)?a:b;
in the above example x value will be assigned to b;
This can be written using if..else statement as follows
if (a>b)
x=a;
else
x=b;
**Hence there is no difference between these two. This for the programmer to write easily, but for compiler both are same.*
it is now simply:
let serialQueue = DispatchQueue(label: "my serial queue")
the default is serial, to get concurrent, you use the optional attributes argument .concurrent
You can also find the use of lambda expressions in writing generic codes to act on your methods.
For example: Generic function to calculate the time taken by a method call. (i.e. Action
in here)
public static long Measure(Action action)
{
Stopwatch sw = new Stopwatch();
sw.Start();
action();
sw.Stop();
return sw.ElapsedMilliseconds;
}
And you can call the above method using the lambda expression as follows,
var timeTaken = Measure(() => yourMethod(param));
Expression allows you to get return value from your method and out param as well
var timeTaken = Measure(() => returnValue = yourMethod(param, out outParam));
As of .NET 5, the implementation has changed. HttpClient
still throws a TaskCanceledException
, but now wraps a TimeoutException
as InnerException
. So you can easily check whether a request was canceled or timed out (code sample copied from linked blog post):
try
{
using var response = await _client.GetAsync("http://localhost:5001/sleepFor?seconds=100");
}
// Filter by InnerException.
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
{
// Handle timeout.
Console.WriteLine("Timed out: "+ ex.Message);
}
catch (TaskCanceledException ex)
{
// Handle cancellation.
Console.WriteLine("Canceled: " + ex.Message);
}
SQL Server Express doesn't include SQL Server Agent, so it's not possible to just create SQL Agent jobs.
What you can do is:
You can create jobs "manually" by creating batch files and SQL script files, and running them via Windows Task Scheduler.
For example, you can backup your database with two files like this:
backup.bat:
sqlcmd -i backup.sql
backup.sql:
backup database TeamCity to disk = 'c:\backups\MyBackup.bak'
Just put both files into the same folder and exeute the batch file via Windows Task Scheduler.
The first file is just a Windows batch file which calls the sqlcmd utility and passes a SQL script file.
The SQL script file contains T-SQL. In my example, it's just one line to backup a database, but you can put any T-SQL inside. For example, you could do some UPDATE
queries instead.
If the jobs you want to create are for backups, index maintenance or integrity checks, you could also use the excellent Maintenance Solution by Ola Hallengren.
It consists of a bunch of stored procedures (and SQL Agent jobs for non-Express editions of SQL Server), and in the FAQ there’s a section about how to run the jobs on SQL Server Express:
How do I get started with the SQL Server Maintenance Solution on SQL Server Express?
SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.
SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.
Download MaintenanceSolution.sql.
Execute MaintenanceSolution.sql. This script creates the stored procedures that you need.
Create cmd files to execute the stored procedures; for example:
sqlcmd -E -S .\SQLEXPRESS -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @Directory = N'C:\Backup', @BackupType = 'FULL'" -b -o C:\Log\DatabaseBackup.txtIn Windows Scheduled Tasks, create tasks to call the cmd files.
Schedule the tasks.
Start the tasks and verify that they are completing successfully.
var text = 'price[5][68]';
var regex = /price\[(\d+)\]\[(\d+)\]/gi;
match = regex.exec(text);
match[1] and match[2] will contain the numbers you're looking for.
Turn the string into array, cut a character at specified index and turn back to string
let str = 'Hello World'.split('')
str.splice(3, 1)
str = str.join('')
// str = 'Helo World'.
In c# if you make you comboBox configuration style DropDownList
or DropDown
then use both of them in this method to clear.
ComboBox1.SelectedIndex = -1;
Correct way to remove install plug-in from Eclipse/STS :
Go to install folder of eclipse ----> plugin --> select required plugin and remove it.
Ex-
Step 1.
E:\springsource\sts-3.4.0.RELEASE\plugins
Step 2.
select and remove related plugins jars.
For Debian EC2 instances, the user is admin
.
OCR Says:
N lml_?e <loJ+_e__}
.lnt Mk.,n ( ln+ _rSC Lhc_yh )
h_S_
_l
s_l . co__ <, " H llo uo/_d ! '` << s l? . ena_ .
TP__rn _ |
_|
Which is pretty damn good, to be fair.
Not an answer Or Why 'tricky' is bad:
>> a = Array(1)
>> a = Split(Join(a, "||") & "||2", "||")
>> WScript.Echo a(0) + a(1)
>>
12
Use different methods to load the form and save/process form.
Example.
Login.php
Load login form at Login/index
Validate login at Login/validate
Redirect the user to User/dashboard
Redirect the user to login/index
Either I don't understand your question, or Enumerable#find is the thing you were looking for.
Using java.time
framework built into Java 8.
import java.time.LocalTime;
import java.time.LocalDateTime;
LocalDateTime now = LocalDateTime.now(); // 2015-11-19T19:42:19.224
// start of a day
now.with(LocalTime.MIN); // 2015-11-19T00:00
now.with(LocalTime.MIDNIGHT); // 2015-11-19T00:00
// end of a day
now.with(LocalTime.MAX); // 2015-11-19T23:59:59.999999999
I would have expected your syntax to work too. The problem arises because when you create new columns with the column-list syntax (df[[new1, new2]] = ...
), pandas requires that the right hand side be a DataFrame (note that it doesn't actually matter if the columns of the DataFrame have the same names as the columns you are creating).
Your syntax works fine for assigning scalar values to existing columns, and pandas is also happy to assign scalar values to a new column using the single-column syntax (df[new1] = ...
). So the solution is either to convert this into several single-column assignments, or create a suitable DataFrame for the right-hand side.
Here are several approaches that will work:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
Then one of the following:
df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]
DataFrame
conveniently expands a single row to match the index, so you can do this:df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)
df = pd.concat(
[
df,
pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
)
], axis=1
)
join
instead of concat
(may be less efficient):df = df.join(pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
))
df = df.join(pd.DataFrame(
{
'column_new_1': np.nan,
'column_new_2': 'dogs',
'column_new_3': 3
}, index=df.index
))
.assign()
with multiple column arguments.I like this variant on @zero's answer a lot, but like the previous one, the new columns will always be sorted alphabetically, at least with early versions of Python:
df = df.assign(column_new_1=np.nan, column_new_2='dogs', column_new_3=3)
new_cols = ['column_new_1', 'column_new_2', 'column_new_3']
new_vals = [np.nan, 'dogs', 3]
df = df.reindex(columns=df.columns.tolist() + new_cols) # add empty cols
df[new_cols] = new_vals # multi-column assignment works for existing cols
df['column_new_1'] = np.nan
df['column_new_2'] = 'dogs'
df['column_new_3'] = 3
Note: many of these options have already been covered in other answers: Add multiple columns to DataFrame and set them equal to an existing column, Is it possible to add several columns at once to a pandas DataFrame?, Add multiple empty columns to pandas DataFrame
According to @Abhishek Singh's you need to understand the problem:
What is the line which gives exception ?? The reason for this is because the element to which you have referred is removed from the DOM structure
and you can not refer to it anymore (imagine what element's ID has changed).
Follow the code:
class TogglingPage {
@FindBy(...)
private WebElement btnTurnOff;
@FindBy(...)
private WebElement btnTurnOn;
TogglingPage turnOff() {
this.btnTurnOff.isDisplayed();
this.btnTurnOff.click(); // when clicked, button should swap into btnTurnOn
this.btnTurnOn.isDisplayed();
this.btnTurnOn.click(); // when clicked, button should swap into btnTurnOff
this.btnTurnOff.isDisplayed(); // throws an exception
return new TogglingPage();
}
}
Now, let us wonder why?
btnTurnOff
was found by a driver - okbtnTurnOff
was replaced by btnTurnOn
- okbtnTurnOn
was found by a driver. - okbtnTurnOn
was replaced by btnTurnOff
- okthis.btnTurnOff.isDisplayed();
on the element which does not exist anymore in Selenium sense - you can see it, it works perfectly, but it is a different instance of the same button. Possible fix:
TogglingPage turnOff() {
this.btnTurnOff.isDisplayed();
this.btnTurnOff.click();
TogglingPage newPage = new TogglingPage();
newPage.btnTurnOn.isDisplayed();
newPage.btnTurnOn.click();
TogglingPage newerPage = new TogglingPage();
newerPage.btnTurnOff.isDisplayed(); // ok
return newerPage;
}
You can just use the Select()
extension method:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());
Or in LINQ syntax:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
var strings = from i in integers
select i.ToString();
SET @uids := "";
UPDATE myf___ingtable
SET id = id
WHERE id < 5
AND ( SELECT @uids := CONCAT_WS(',', CAST(id AS CHAR CHARACTER SET utf8), @uids) );
SELECT @uids;
I had to CAST the id (dunno why)... or I cannot get the @uids content (it was a blob) Btw many thanks for Pomyk answer!
Check your Keychain - look in Login and System keychains for expired certificates or error messages.
I found certs with "this certificate has an invalid user" error messages, and an expired Apple Worldwide Developer Relations Certificate.
Delete them and install the new AWDRC certificate from https://developer.apple.com/certificationauthority/AppleWWDRCA.cer
Then follow the accepted answer to get Xcode to use the new certificates.
Git stash clear will clear complete stash,
cmd: git stash clear
If you want to delete a particular stash with a stash index, you can use the drop.
cmd: git stash drop 4
(4 is stash id or stash index)
Don't forget to check if the conversion was successful!
bool ok;
auto str= tr("1337");
str.toDouble(&ok); // returns 1337.0, ok set to true
auto strr= tr("LEET");
strr.toDouble(&ok); // returns 0.0, ok set to false
You can use this:
addedDate = datetime.now().replace(microsecond=0)
In C++ copying the object means cloning. There is no any special cloning in the language.
As the standard suggests, after copying you should have 2 identical copies of the same object.
There are 2 types of copying: copy constructor when you create object on a non initialized space and copy operator where you need to release the old state of the object (that is expected to be valid) before setting the new state.
I found this library to work when MarcJ's solution didn't:
https://github.com/sdecima/javascript-detect-element-resize
It's very lightweight and detects even natural resizes via CSS or simply the HTML loading/rendering.
Code sample (taken from the link):
<script type="text/javascript" src="detect-element-resize.js"></script>
<script type="text/javascript">
var resizeElement = document.getElementById('resizeElement'),
resizeCallback = function() {
/* do something */
};
addResizeListener(resizeElement, resizeCallback);
removeResizeListener(resizeElement, resizeCallback);
</script>
List<T>
has a FindAll
method that will do the filtering for you and return a subset of the list.
MSDN has a great code example here: http://msdn.microsoft.com/en-us/library/aa701359(VS.80).aspx
EDIT: I wrote this before I had a good understanding of LINQ and the Where()
method. If I were to write this today i would probably use the method Jorge mentions above. The FindAll
method still works if you're stuck in a .NET 2.0 environment though.
It's probably not what you want, but a tool like re2c can compile POSIX(-ish) regular expressions to ANSI C. It's written as a replacement for lex
, but this approach allows you to sacrifice flexibility and legibility for the last bit of speed, if you really need it.
In a nutshell what it does is refer to the id
of the input, that's all:
<label for="the-id-of-the-input">Input here:</label>
<input type="text" name="the-name-of-input" id="the-id-of-the-input">
You can transfer array from javascript to PHP...
Javascript... ArraySender.html
<script language="javascript">
//its your javascript, your array can be multidimensional or associative
plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info';
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3';
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4';
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5';
function convertJsArr2Php(JsArr){
var Php = '';
if (Array.isArray(JsArr)){
Php += 'array(';
for (var i in JsArr){
Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
Php += ', ';
}
}
Php += ')';
return Php;
}
else{
return '\'' + JsArr + '\'';
}
}
function ajaxPost(str, plArrayC){
var xmlhttp;
if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("POST",str,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('Array=' + plArrayC);
}
ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>
and PHP Code... ArrayReader.php
<?php
eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);
?>
It worked for me now, I have change the setting of my google account as below:
System.out.println("Start");
final String username = "[email protected]";
final String password = "************";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Transport transport=session.getTransport();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));//formBean.getString("fromEmail")
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]"));
message.setSubject("subject");//formBean.getString(
message.setText("mailBody");
transport.connect();
transport.send(message, InternetAddress.parse("[email protected]"));//(message);
System.out.println("Done");
} catch (MessagingException e) {
System.out.println("e="+e);
e.printStackTrace();
throw new RuntimeException(e);
}
Though I have enabled SSL and TSL while running program in this link of same post. I spend a lot of time but than I realized and found this link. And done 2 following steps and setting control in google. :
Disable the 2-step verification (password and OTP)
Enabling to allow to access less secure app(Allow less secure apps: ON.)
Now I am able to send mail using above program.
Assuming that you meant to write
char *functionname(char *string[256])
Here you are declaring a function that takes an array of 256 pointers to char
as argument and returns a pointer to char. Here, on the other hand,
char functionname(char string[256])
You are declaring a function that takes an array of 256 char
s as argument and returns a char
.
In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.
For those of us trying to figure out how to hash our own classes whilst still using the standard template, there is a simple solution:
In your class you need to define an equality operator overload ==
. If you don't know how to do this, GeeksforGeeks has a great tutorial https://www.geeksforgeeks.org/operator-overloading-c/
Under the standard namespace, declare a template struct called hash with your classname as the type (see below). I found a great blogpost that also shows an example of calculating hashes using XOR and bitshifting, but that's outside the scope of this question, but it also includes detailed instructions on how to accomplish using hash functions as well https://prateekvjoshi.com/2014/06/05/using-hash-function-in-c-for-user-defined-classes/
namespace std {
template<>
struct hash<my_type> {
size_t operator()(const my_type& k) {
// Do your hash function here
...
}
};
}
std::map
or std::unordered_map
just like you would normally do and use my_type
as the key, the standard library will automatically use the hash function you defined before (in step 2) to hash your keys.#include <unordered_map>
int main() {
std::unordered_map<my_type, other_type> my_map;
}
but.onclick = callJavascriptFunction;
no double quotes no parentheses.
There are many good answers here but you should avoid at all cost to pass untrusted variables to subprocess using shell=True
as this is a security risk. The variables can escape to the shell and run arbitrary commands! If you just can't avoid it at least use python3's shlex.quote()
to escape the string (if you have multiple space-separated arguments, quote each split instead of the full string).
shell=False
is always the default where you pass an argument array.
Now the safe solutions...
Change your own process's environment - the new environment will apply to python itself and all subprocesses.
os.environ['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)
Make a copy of the environment and pass is to the childen. You have total control over the children environment and won't affect python's own environment.
myenv = os.environ.copy()
myenv['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command, env=myenv)
Unix only: Execute env
to set the environment variable. More cumbersome if you have many variables to modify and not portabe, but like #2 you retain full control over python and children environments.
command = ['env', 'LD_LIBRARY_PATH=my_path', 'sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)
Of course if var1
contain multiple space-separated argument they will now be passed as a single argument with spaces. To retain original behavior with shell=True
you must compose a command array that contain the splitted string:
command = ['sqsub', '-np'] + var1.split() + ['/homedir/anotherdir/executable']
Place your text file in the /assets
directory under the Android project. Use AssetManager
class to access it.
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
Or you can also put the file in the /res/raw
directory, where the file will be indexed and is accessible by an id in the R file:
InputStream is = context.getResources().openRawResource(R.raw.test);
In Cygwin, this looks like it works for me:
find -type f -name "<FILENAME_GLOB>" | while read <VAR>; do (file -i "$<VAR>"); done
Example:
find -type f -name "*.txt" | while read file; do (file -i "$file"); done
You could pipe that to awk and create an iconv command to convert everything to utf8, from any source encoding supported by iconv.
Example:
find -type f -name "*.txt" | while read file; do (file -i "$file"); done | awk -F[:=] '{print "iconv -f "$3" -t utf8 \""$1"\" > \""$1"_utf8\""}' | bash
try this
getData(){
if(window.innerWidth <= 768) {
alert('mobile view')
return;
}
//else function will work
let body= {
"key" : 'keyValue'
}
this.dataService.getData(body).subscribe(
(data: any) => {
this.myData = data
}
)
}
Me too I encountered this issue.
The only alternative is to define a width (or max-width) in the child elements. IE 11 is a bit stupid, and me I just spent 20 minutes to realize this solution.
.parent {
display: flex;
flex-direction: column;
width: 800px;
border: 1px solid red;
align-items: center;
}
.child {
border: 1px solid blue;
max-width: 800px;
@media (max-width:960px){ // <--- Here we go. The text won't wrap ? we will make it break !
max-width: 600px;
}
@media (max-width:600px){
max-width: 400px;
}
@media (max-width:400px){
max-width: 150px;
}
}
<div class="parent">
<div class="child">
Lorem Ipsum is simply dummy text of the printing and typesetting industry
</div>
<div class="child">
Lorem Ipsum is simply dummy text of the printing and typesetting industry
</div>
</div>
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
This is just an extension to this answer.
using System;
using System.Threading;
using System.Threading.Tasks;
public class SemaphoreLocker
{
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
public async Task LockAsync(Func<Task> worker)
{
await _semaphore.WaitAsync();
try
{
await worker();
}
finally
{
_semaphore.Release();
}
}
// overloading variant for non-void methods with return type (generic T)
public async Task<T> LockAsync<T>(Func<Task<T>> worker)
{
await _semaphore.WaitAsync();
T result = default;
try
{
result = await worker();
}
finally
{
_semaphore.Release();
}
return result;
}
}
Usage:
public class Test
{
private static readonly SemaphoreLocker _locker = new SemaphoreLocker();
public async Task DoTest()
{
await _locker.LockAsync(async () =>
{
// [async] calls can be used within this block
// to handle a resource by one thread.
});
// OR
var result = await _locker.LockAsync(async () =>
{
// [async] calls can be used within this block
// to handle a resource by one thread.
}
}
}
If you want to check for any key at any depth on an object and account for falsey values consider this line for a utility function:
var keyExistsOn = (o, k) => k.split(".").reduce((a, c) => a.hasOwnProperty(c) ? a[c] || 1 : false, Object.assign({}, o)) === false ? false : true;
Results
var obj = {
test: "",
locals: {
test: "",
test2: false,
test3: NaN,
test4: 0,
test5: undefined,
auth: {
user: "hw"
}
}
}
keyExistsOn(obj, "")
> false
keyExistsOn(obj, "locals.test")
> true
keyExistsOn(obj, "locals.test2")
> true
keyExistsOn(obj, "locals.test3")
> true
keyExistsOn(obj, "locals.test4")
> true
keyExistsOn(obj, "locals.test5")
> true
keyExistsOn(obj, "sdsdf")
false
keyExistsOn(obj, "sdsdf.rtsd")
false
keyExistsOn(obj, "sdsdf.234d")
false
keyExistsOn(obj, "2134.sdsdf.234d")
false
keyExistsOn(obj, "locals")
true
keyExistsOn(obj, "locals.")
false
keyExistsOn(obj, "locals.auth")
true
keyExistsOn(obj, "locals.autht")
false
keyExistsOn(obj, "locals.auth.")
false
keyExistsOn(obj, "locals.auth.user")
true
keyExistsOn(obj, "locals.auth.userr")
false
keyExistsOn(obj, "locals.auth.user.")
false
keyExistsOn(obj, "locals.auth.user")
true
Also see this NPM package: https://www.npmjs.com/package/has-deep-value
One option is to use regular expressions:
if (str.match("^Hello")) {
// do this if begins with Hello
}
if (str.match("World$")) {
// do this if ends in world
}
Itertools repeat combined with list extend.
from itertools import repeat
l = []
l.extend(repeat(x, 100))
Correct me if I am wrong, but getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with. If you use instanceof in that situation you can NOT know that because:
class A { }
class B extends A { }
Object oA = new A();
Object oB = new B();
oA instanceof A => true
oA instanceof B => false
oB instanceof A => true // <================ HERE
oB instanceof B => true
oA.getClass().equals(A.class) => true
oA.getClass().equals(B.class) => false
oB.getClass().equals(A.class) => false // <===============HERE
oB.getClass().equals(B.class) => true
Using Java 7:
Paths.get(string).toUri().toURL();
However, you probably want to get a URI
. Eg, a URI
begins with file:///
but a URL with file:/
(at least, that's what toString
produces).
Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z]
or [0-9-]
), OR escape it (e.g. [a-z\-0-9]
) in order to add "hyphen" to your class.
It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.
(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]
) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)
Great question!
Alternatively instead of turning 'no-console' off, you can allow. In the .eslintrc.js file put
rules: {
"no-console": [
"warn",
{ "allow": ["clear", "info", "error", "dir", "trace", "log"] }
]
}
This will allow you to do console.log
and console.clear
etc without throwing errors.
Git GUI has a PUSH button - pardon the pun, and the dialog box it opens has a checkbox for tags.
I pushed a branch from the command line, without tags, and then tried again pushing the branch using the --follow-tags
option descibed above. The option is described as following annotated tags. My tags were simple tags.
I'd fixed something, tagged the commit with the fix in, (so colleagues can cherry pick the fix,) then changed the software version number and tagged the release I created (so colleagues can clone that release).
Git returned saying everything was up-to-date. It did not send the tags! Perhaps because the tags weren't annotated. Perhaps because there was nothing new on the branch.
When I did a similar push with Git GUI, the tags were sent.
For the time being, I am going to be pushing my changes to my remotes with Git GUI and not with the command line and --follow-tags
.
mActionBarDrawerToggle = mNavigationDrawerFragment.getActionBarDrawerToggle();
mActionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// event when click home button
}
});
in mycase this code work perfect
Though a very old question, but I am still posting an answer to it so that it may help some one. If you are using any layout inside the list view then use ...
android:descendantFocusability="blocksDescendants"
... on the first parent layout inside the list. This works as magic the click will not be consumed by any element inside the list but will directly go to the list item.
both for
and class
are reserved words in JavaScript this is why when it comes to HTML attributes in JSX you need to use something else, React team decided to use htmlFor
and className
respectively
I shared my experience of using two LEFT JOINS in a single SQL query.
I have 3 tables:
Table 1) Patient consists columns PatientID, PatientName
Table 2) Appointment consists columns AppointmentID, AppointmentDateTime, PatientID, DoctorID
Table 3) Doctor consists columns DoctorID, DoctorName
Query:
SELECT Patient.patientname, AppointmentDateTime, Doctor.doctorname
FROM Appointment
LEFT JOIN Doctor ON Appointment.doctorid = Doctor.doctorId //have doctorId column common
LEFT JOIN Patient ON Appointment.PatientId = Patient.PatientId //have patientid column common
WHERE Doctor.Doctorname LIKE 'varun%' // setting doctor name by using LIKE
AND Appointment.AppointmentDateTime BETWEEN '1/16/2001' AND '9/9/2014' //comparison b/w dates
ORDER BY AppointmentDateTime ASC; // getting data as ascending order
I wrote the solution to get date format like "mm/dd/yy" (under my name "VARUN TEJ REDDY")
Download the developer edition. There you can choose Express as license when installing.
Try adding this code to your config. I had a similar issue once, and this workaround did the trick.
app.config(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}]);
Another suggestion is to do that way:
string = "abcd\n"
print(string.replace("\n","\\n"))
But be aware that the print function actually print to the terminal the "\n", your terminal interpret that as a newline, that's it. So, my solution just change the newline in \ + n
You can simply use __qualname__
which stands for qualified name of a function or class
Example:
>>> class C:
... class D:
... def meth(self):
... pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'
documentation link qualname
grep
patterns are matched against individual lines so there is no way for a pattern to match a newline found in the input.
However you can find empty lines like this:
grep '^$' file
grep '^[[:space:]]*$' file # include white spaces
If you check which string would come first in a lexicon, you've done a lexicographical comparison of the strings!
Some links:
Stolen from the latter link:
A string s precedes a string t in lexicographic order if
- s is a prefix of t, or
- if c and d are respectively the first character of s and t in which s and t differ, then c precedes d in character order.
Note: For the characters that are alphabetical letters, the character order coincides with the alphabetical order. Digits precede letters, and uppercase letters precede lowercase ones.
Example:
- house precedes household
- Household precedes house
- composer precedes computer
- H2O precedes HOTEL
So, this is an awfully old question which already has an accepted answer, but I believe that this answer would have been chosen had it been posted four years ago.
I solved this purely with CSS, and with NO EXTRA DOM ELEMENTS! This means that the two colors are purely that, just background colors of ONE ELEMENT, not the background color of two.
I used a gradient and, because I set the color stops so closely together, it looks as if the colors are distinct and that they do not blend.
Here is the gradient in native syntax:
background: repeating-linear-gradient(#74ABDD, #74ABDD 49.9%, #498DCB 50.1%, #498DCB 100%);
Color #74ABDD
starts at 0%
and is still #74ABDD
at 49.9%
.
Then, I force the gradient to shift to my next color within 0.2%
of the elements height, creating what appears to be a very solid line between the two colors.
Here is the outcome:
Have fun!
The configurations below worked for me:
spring.jpa.properties.javax.persistence.schema-generation.database.action=create
spring.jpa.properties.javax.persistence.schema-generation.create-database-schemas=true
spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
spring.jpa.properties.javax.persistence.schema-generation.drop-source=metadata
spring.jpa.properties.javax.persistence.schema-generation.connection=jdbc:mysql://localhost:3306/your_database
I believe you could do it like this :
var fd = new FormData();
fd.append( 'file', input.files[0] );
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Notes:
Setting processData
to false
lets you prevent jQuery from automatically transforming the data into a query string. See the docs for more info.
Setting the contentType
to false
is imperative, since otherwise jQuery will set it incorrectly.
A php port of Neil Frasers diff_match_patch (Apache 2.0 licensed)
real
gets the value ent.get()
which is just a string. It has no idea where it came from, and no way to affect the widget.
Instead of real.delete()
, call .delete()
on the entry widget itself:
def res(ent, real, secret):
if secret == eval(real):
showinfo(message='that is right!')
ent.delete(0, END)
def guess():
...
btn = Button(ge, text="Enter", command=lambda: res(ent, ent.get(), secret))
Simple and stupid
var date = new Date();
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),
date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return new Date(now_utc);
A minor but notable advantage of a list over a tuple is that lists tend to be slightly more portable. Standard tools are less likely to support tuples. JSON, for example, does not have a tuple type. YAML does, but its syntax is ugly compared to its list syntax, which is quite nice.
In those cases, you may wish to use a tuple internally then convert to list as part of an export process. Alternately, you might want to use lists everywhere for consistency.
Do you mean you want the script's own path so you can reference a file next to the script? Try this:
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
Write-host "My directory is $dir"
You can get a lot of info from $MyInvocation and its properties.
If you want to reference a file in the current working directory, you can use Resolve-Path or Get-ChildItem:
$filepath = Resolve-Path "somefile.txt"
EDIT (based on comment from OP):
# temporarily change to the correct folder
Push-Location $folder
# do stuff, call ant, etc
# now back to previous directory
Pop-Location
There's probably other ways of achieving something similar using Invoke-Command as well.
I had this problem after upgrading to macOS Catalina.
The issue is resolved as follows:
whereis git 2. Add the location of git in settings file with your location:
settings.json
"git.path": "/usr/bin/git", Depending on your platform, the user settings file (settings.json) is located here:
Windows %APPDATA%\Code\User\settings.json
macOS $HOME/Library/Application Support/Code/User/settings.json
Linux $HOME/.config/Code/User/settings.json
Combining other answers, why not use the ms timestamp with a random value appended; repeat until no conflict, which in practice will be almost never.
For example: File-ccyymmdd-hhmmss-mmm-rrrrrr.txt
Try this HTML
<a href="#" data-toggle="popover" data-popover-target="#popover-content-1">Do Popover 1</a>
<a href="#" data-toggle="popover" data-popover-target="#popover-content-2">Do Popover</a>
<div id="popover-content-1" style="display: none">Content 1</div>
<div id="popover-content-2" style="display: none">Content 2</div>
jQuery:
$(function() {
$('[data-toggle="popover"]').each(function(i, obj) {
var popover_target = $(this).data('popover-target');
$(this).popover({
html: true,
trigger: 'focus',
placement: 'right',
content: function(obj) {
return $(popover_target).html();
}
});
});
});
for a lightweight list that does not copy the entries, you may use sth like this:
List<Object> mergedList = new ConcatList<>(list1, list2);
here the implementation:
public class ConcatList<E> extends AbstractList<E> {
private final List<E> list1;
private final List<E> list2;
public ConcatList(final List<E> list1, final List<E> list2) {
this.list1 = list1;
this.list2 = list2;
}
@Override
public E get(final int index) {
return getList(index).get(getListIndex(index));
}
@Override
public E set(final int index, final E element) {
return getList(index).set(getListIndex(index), element);
}
@Override
public void add(final int index, final E element) {
getList(index).add(getListIndex(index), element);
}
@Override
public E remove(final int index) {
return getList(index).remove(getListIndex(index));
}
@Override
public int size() {
return list1.size() + list2.size();
}
@Override
public void clear() {
list1.clear();
list2.clear();
}
private int getListIndex(final int index) {
final int size1 = list1.size();
return index >= size1 ? index - size1 : index;
}
private List<E> getList(final int index) {
return index >= list1.size() ? list2 : list1;
}
}
Scanner scanner = new Scanner(System.in);
String part = scanner.nextLine();
String line = scanner.nextLine();
String temp = "\\b" + part +"|"+ part + "\\b";
Pattern pattern = Pattern.compile(temp.toLowerCase());
Matcher matcher = pattern.matcher(line.toLowerCase());
System.out.println(matcher.find() ? "YES":"NO");
If you need to determine if any of the words of this text start or end with the sequence. you can use this regex \bsubstring|substring\b anythingsubstring substringanything anythingsubstringanything
could be a shorthand for React.Fragment
This must work!
client (angular):
$scope.saveForm = function () {
var formData = new FormData();
var file = $scope.myFile;
var json = $scope.myJson;
formData.append("file", file);
formData.append("ad",JSON.stringify(json));//important: convert to JSON!
var req = {
url: '/upload',
method: 'POST',
headers: {'Content-Type': undefined},
data: formData,
transformRequest: function (data, headersGetterFunction) {
return data;
}
};
Backend-Spring Boot:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
Advertisement storeAd(@RequestPart("ad") String adString, @RequestPart("file") MultipartFile file) throws IOException {
Advertisement jsonAd = new ObjectMapper().readValue(adString, Advertisement.class);
//do whatever you want with your file and jsonAd
I have met the same issue today. After trying various method, I realize that just put the code of sizing inside $(window).load(function() {})
instead of document.ready
would solve part of issue (if you are not ajaxing the page).
I use a simple script when starting jmeter with my own java versin
setlocal
set JAVA_HOME="c:\java8"
set PATH=%JAVA_HOME%\bin;%PATH%;
java -version
to have a java "portable" you can use this method here:
If you pass the -v
flag to the ansible-playbook command, then ansible will show the output on your terminal.
For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.
I also had the same issue. I fixed this by installing the .NET framework version 4.5.
I recently had to build a fall back system which included any number of fallback images. Here's how I did it using a simple JavaScript function.
HTML
<img src="some_image.tiff"
onerror="fallBackImg(this);"
data-fallIndex="1"
data-fallback1="some_image.png"
data-fallback2="some_image.jpg">
JavaScript
function fallBackImg(elem){
elem.onerror = null;
let index = +elem.dataset.fallIndex;
elem.src = elem.dataset[`fallback${index}`];
index++;
elem.dataset.fallbackindex = index;
}
I feel like it's a pretty lightweight way of handling many fallback images.
function my_simple_crypt( $string, $action = 'e' ) {
// you may change these values to your own
$secret_key = 'my_simple_secret_key';
$secret_iv = 'my_simple_secret_iv';
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hash( 'sha256', $secret_key );
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
if( $action == 'e' ) {
$output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
}
else if( $action == 'd' ){
$output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
}
return $output;
}
Arrays.sort(numArray);
return (numArray[size/2] + numArray[(size-1)/2]) / 2;
Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:
echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"
<input type = "checkbox" name = "checkbox1" /> <label> Check to say hi.</label>
From the Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection fc)
{
var s = fc["checkbox1"];
if (s == "on")
{
string x = "Hi";
}
}
I have solved this problem, please just make few changes
1- all controller class name should start with capital letter. i mean first letter of class should be capital . eg we have controler with class name Pages
so it should be Pages not pages
2- save the controller class Pages as Pages.php
not pages.php
so first letter must be capital
same for model, model class first letter should be capital and also save model class as Pages_model.php
not page_model.php
hope this will solve ur problem
I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer
Assuming you're fine with taking all of the changes in master, what you want is:
git checkout <my branch>
to switch the working tree to your branch; then:
git merge master
to merge all the changes in master with yours.
This really needs to be added to the documentation, which is why I filed an issue about it a few months ago...
You need some 32-bit binaries, and you have a 64-bit OS version (apparently). Try:
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6
That worked for me on Ubuntu 14.10.
UPDATE 2017-12-16: The details will vary by Linux distro and version. So for example, this answer covers newer Ubuntu versions.
It probably aimed to select all the informations in your table. If you use this kind of query (for example in PHP) :
mysql_query("SELECT * FROM newsletter WHERE email = '$email'");
The email ' OR 1=1/* will give this kind of query :
mysql_query("SELECT * FROM newsletter WHERE email = '' OR 1=1/*");
So it selects all the rows (because 1=1 is always true and the rest of the query is 'commented'). But it was not successful
Step 1 : Now under your app folder
you should see libs
, if you don't see it, then create it .
Step 2 : Drag & Drop the .jar file here
, you may be get a prompt "This file does not belong to the project"
, just click OK
Button .
Step 3 : Now you should see the jar file under libs folder, right click on the jar file and select "Add as library", Click OK for prompt "Create Library"
Step 4 : Now this jar has been added.
It looks like you have accidentally declared DataType
as an array rather than as a string.
Change line 3 to:
Dim DataType As String = myTableData.Rows(i).Item(1)
That should work.
public class Fibonaci{
static void fibonacci() {
int ptr1 = 1, ptr2 = 1, ptr3 = 0;
int temp = 0;
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
try {
System.out.println("The Number Value's fib you required ? ");
ptr3 = Integer.parseInt(Data.readLine());
System.out.print(ptr1 + " " + ptr2 + " ");
for (int i = 0; i < ptr3; i++) {
System.out.print(ptr1 + ptr2 + " ");
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp + ptr2;
}
} catch(IOException err) {
System.out.println("Error!" + err);
} catch(NumberFormatException err) {
System.out.println("Invald Input!");
}
}
public static void main(String[]args)throws Exception{
Fibonaci.fibonacci();
}
}
You can do like this.
:term
Added in Vim 8.1.
Keep in mind that whenever a terminal window is active, most keystrokes will simply be passed to the terminal instead of having their usual functions. Ctrl-W
and its subcommands are the main exception. To send a literal ^W
input to the terminal, press Ctrl-W
.
. You can also open the Vim :
command line by pressing Ctrl-W
:
. The other Ctrl-W
commands work as normal, so managing windows works the same no matter what type of window is currently selected.
Resolved promise:
return $q.when( someValue ); // angularjs 1.2+
return $q.resolve( someValue ); // angularjs 1.4+, alias to `when` to match ES6
Rejected promise:
return $q.reject( someValue );
settings.json
:{}
icon at the top right corner to open the settings.json
:
Add excluded folders to files.exclude
. Also check out search.exclude
and files.watcherExclude
as they might be useful too. This snippet contains their explanations and defaults:
{
// Configure glob patterns for excluding files and folders.
// For example, the files explorer decides which files and folders to show
// or hide based on this setting.
// Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options).
"files.exclude": {
"**/.git": true,
"**/.svn": true,
"**/.hg": true,
"**/CVS": true,
"**/.DS_Store": true
},
// Configure glob patterns for excluding files and folders in searches.
// Inherits all glob patterns from the `files.exclude` setting.
// Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options).
"search.exclude": {
"**/node_modules": true,
"**/bower_components": true
},
// Configure glob patterns of file paths to exclude from file watching.
// Patterns must match on absolute paths
// (i.e. prefix with ** or the full path to match properly).
// Changing this setting requires a restart.
// When you experience Code consuming lots of cpu time on startup,
// you can exclude large folders to reduce the initial load.
"files.watcherExclude": {
"**/.git/objects/**": true,
"**/.git/subtree-cache/**": true,
"**/node_modules/*/**": true
}
}
For more details on the other settings, see the official settings.json
reference.
From: http://www.csharp-examples.net/string-format-datetime/
string.Format("{0:t tt}", datetime); // -> "P PM" or "A AM"
For me, it was vertical-align: baseline
vs vertical-align: top
that was causing the top offset.
Try to set vertical-align: top
Ya session storage and local storage are same in behaviour except one that is local storage will store the data until and unless the user delete the cache and cookies and session storage data will retain in the system until we close the session i,e until we close the session storage created window.
keytool
is part of the standard java distribution.
In a windows 64-bit machine, you would normally find the jdk at
C:\Program Files\Java\jdk1.8.0_121\bin
It is used for managing keys and certificates you can sign things with, in your case, probably a jar file.
If you provide more details of what you need to do, we could probably give you a more specific answer.
you have to use bash instead or rewrite your script using standard sh
sh -c 'test "$choose" = "y" -o "$choose" = "Y"'
Use JSTL tag libraries in JSP. That will work perfectly.
My five cents:
Both direction array of integers function.
When range(0, 5) become [0, 1, 2, 3, 4, 5]
.
And range(5, 0) become [5, 4, 3, 2, 1, 0]
.
Based on this answer.
function range(start, end) {
const isReverse = (start > end);
const targetLength = isReverse ? (start - end) + 1 : (end - start ) + 1;
const arr = new Array(targetLength);
const b = Array.apply(null, arr);
const result = b.map((discard, n) => {
return (isReverse) ? n + end : n + start;
});
return (isReverse) ? result.reverse() : result;
}
P.S. For use in real life you should also check args for isFinite()
and isNaN()
.
B2 container position relative
Top position B2 + of remaining height
Height of B2 + height B1 or remaining height
For the first rule,
Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.
For the second,
Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.
For the third,
Same as the second, except your formula is =".8*" rather than .9.
My approach:
define a default constraint on the ModDate
column with a value of GETDATE()
- this handles the INSERT
case
have a AFTER UPDATE
trigger to update the ModDate
column
Something like:
CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
UPDATE dbo.TimeEntry
SET ModDate = GETDATE()
WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
The sshpass utility is meant for exactly this. First, install sshpass by typing this command:
sudo apt-get install sshpass
Then prepend your ssh/scp command with
sshpass -p '<password>' <ssh/scp command>
This program is easiest to install when using Linux.
User should consider using SSH's more secure public key authentication (with the ssh
command) instead.
Considering you're on a feature branch and you want to check which files have changed compared to master... just this:
git diff --name-only master
When using Class based views, another option is to use the dispatch method. https://docs.djangoproject.com/en/2.2/ref/class-based-views/base/
Example Code:
Settings.py
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'
urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
urlpatterns = [
path('', HomeView.as_view(), name='home'),
path('login/', auth_views.LoginView.as_view(),name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
views.py
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views.generic import View
from django.shortcuts import redirect
@method_decorator([login_required], name='dispatch')
class HomeView(View):
model = models.User
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return redirect('login')
elif some-logic:
return redirect('some-page') #needs defined as valid url
return super(HomeView, self).dispatch(request, *args, **kwargs)
$(selector).change()
Longer slower alternative, better for abstraction.
$(selector).trigger("change")
You want the openssl-devel
package.
At least I think it's -devel
on Ubuntu. Might be -dev
. It's one of the two.
public Form1()
{
InitializeComponent();
//this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
}
itoa
is not a standard C function. You can implement your own. It appeared in the first edition of Kernighan and Ritchie's The C Programming Language, on page 60. The second edition of The C Programming Language ("K&R2") contains the following implementation of itoa
, on page 64. The book notes several issues with this implementation, including the fact that it does not correctly handle the most negative number
/* itoa: convert n to characters in s */
void itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
The function reverse
used above is implemented two pages earlier:
#include <string.h>
/* reverse: reverse string s in place */
void reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
I did this by installing Cygwin64 from this link https://www.cygwin.com/ Then - View Full, Search gcc and scroll down to find pkg-config. Click on icon to select latest version. This worked for me well.
I am not 100% sure what the conditions are for this, but for me the above didn't work directly, thought it got close. I think it was because I needed "id" for my view by in the model it was called "ObjectID".
I had a model with a variety of pieces of information. I just needed the id.
Before the above I created a new System.Web.Routing.RouteValueDictionary object and added the needed id.
(System.Web.Routing.)RouteValueDictionary RouteInfo = new RouteValueDictionary();
RouteInfo.Add("id", ObjectID);
return RedirectToAction("details", RouteInfo);
(Note: the MVC project in question I didn't create, so I don't know where all the right "fiddly" bits are.)
Some time ago I wrote simple Webcam Capture API which can be used for that. The project is available on Github.
Example code:
Webcam webcam = Webcam.getDefault();
webcam.open();
try {
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
} catch (IOException e) {
e.printStackTrace();
} finally {
webcam.close();
}
In my case, I have Eclipse Maven project. I had the same issue and I posted detailed explanation of the issue and answer here Eclipse Maven - Code Completion fails "This compilation unit is not on the build path of a Java project" and "Failed to Download Index" Error
//module dependent on ngRoute
var app=angular.module("myApp",['ngRoute']);
//spa-Route Config file
app.config(function($routeProvider,$locationProvider){
$locationProvider.hashPrefix('');
$routeProvider
.when('/',{template:'HOME'})
.when('/about/:paramOne/:paramTwo',{template:'ABOUT',controller:'aboutCtrl'})
.otherwise({template:'Not Found'});
}
//aboutUs controller
app.controller('aboutCtrl',function($routeParams){
$scope.paramOnePrint=$routeParams.paramOne;
$scope.paramTwoPrint=$routeParams.paramTwo;
});
in index.html
<a ng-href="#/about/firstParam/secondParam">About</a>
firstParam and secondParam can be anything according to your needs.
Hope not to be late. It is accomplished using only one line!
-webkit-transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
-moz-transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
-o-transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
That works on Chrome. You have to separate the CSS properties with a comma.
Here is a working example: http://jsfiddle.net/H2jet/
For me the solution was cleaning and rebuilding the Test Project
Build > Clean
Build > Build
I haven't read that in the answers above, that's why I add it :)
What worked for me: I finally noticed the Build Executor Status window on the left on the main Jenkins dashboard. I run a dev/test instance on my local system with 2 executors. Both were currently occupied with builds that were not running. Upon cancelling these to jobs, my third (pending) job was able to run.
If you don't use html helpers you may use simple ternary expression like this:
<input name="Field"
value="@Model.Field" tabindex="0"
@(Model.IsDisabledField ? "disabled=\"disabled\"" : "")>
You tagged your question [C] and [C++] at the same time. The results will be consistent between the languages, but the structure of the the answer is different for each of these languages.
In C language your examples has no relation to bool
whatsoever (that applies to C99 as well). In C language relational operators do not produce bool
results. Both 4 > 5
and 4 < 5
are expressions that produce results of type int
with values 0
or 1
. So, there's no "bool to int conversion" of any kind taking place in your examples in C.
In C++ relational operators do indeed produce bool
results. bool
values are convertible to int
type, with true
converting to 1
and false
converting to 0
. This is guaranteed by the language.
P.S. C language also has a dedicated boolean type _Bool
(macro-aliased as bool
), and its integral conversion rules are essentially the same as in C++. But nevertheless this is not relevant to your specific examples in C. Once again, relational operators in C always produce int
(not bool
) results regardless of the version of the language specification.
Add the following to your build.gradle
apply plugin: 'eclipse'
and browse to the project directory
gradle eclipse
Once done, you could import the project from eclipse as simple Java Project.
You need a semicolon after font-family: Arial, Helvetica, sans-serif
. This will make your updated code the following:
<!DOCTYPE>
<html>
<head>
<title>DIV Font</title>
<style>
.my_text
{
font-family: Arial, Helvetica, sans-serif;
font-size: 40px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="my_text">some text</div>
</body>
</html>
Here is a shorter, but complete code.
If you need a dialog with only one button:
await showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Message'),
content: Text(
'Your file is saved.'),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(); // dismisses only the dialog and returns nothing
},
child: new Text('OK'),
),
],
),
);
If you need a dialog with Yes/No buttons:
onPressed: () async {
bool result = await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Confirmation'),
content: Text('Do you want to save?'),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(false); // dismisses only the dialog and returns false
},
child: Text('No'),
),
FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(true); // dismisses only the dialog and returns true
},
child: Text('Yes'),
),
],
);
},
);
if (result) {
if (missingvalue) {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text('Missing Value'),
));
} else {
saveObject();
Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
} else {
Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
}
What about using PRIOR,
so
SELECT id, parent_id, PRIOR name
FROM tbl
START WITH id = 1
CONNECT BY PRIOR id = parent_id`
or if you want to get the root name
SELECT id, parent_id, CONNECT_BY_ROOT name
FROM tbl
START WITH id = 1
CONNECT BY PRIOR id = parent_id
Type
C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld" --console
to start the sql server and then test the client connection.
list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append
Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]
Time complexity, append O(1), insert O(n)
You should delete old child items thisParent.ChildItems
one by one manually. Entity Framework doesn't do that for you. It finally cannot decide what you want to do with the old child items - if you want to throw them away or if you want to keep and assign them to other parent entities. You must tell Entity Framework your decision. But one of these two decisions you HAVE to make since the child entities cannot live alone without a reference to any parent in the database (due to the foreign key constraint). That's basically what the exception says.
Edit
What I would do if child items could be added, updated and deleted:
public void UpdateEntity(ParentItem parent)
{
// Load original parent including the child item collection
var originalParent = _dbContext.ParentItems
.Where(p => p.ID == parent.ID)
.Include(p => p.ChildItems)
.SingleOrDefault();
// We assume that the parent is still in the DB and don't check for null
// Update scalar properties of parent,
// can be omitted if we don't expect changes of the scalar properties
var parentEntry = _dbContext.Entry(originalParent);
parentEntry.CurrentValues.SetValues(parent);
foreach (var childItem in parent.ChildItems)
{
var originalChildItem = originalParent.ChildItems
.Where(c => c.ID == childItem.ID && c.ID != 0)
.SingleOrDefault();
// Is original child item with same ID in DB?
if (originalChildItem != null)
{
// Yes -> Update scalar properties of child item
var childEntry = _dbContext.Entry(originalChildItem);
childEntry.CurrentValues.SetValues(childItem);
}
else
{
// No -> It's a new child item -> Insert
childItem.ID = 0;
originalParent.ChildItems.Add(childItem);
}
}
// Don't consider the child items we have just added above.
// (We need to make a copy of the list by using .ToList() because
// _dbContext.ChildItems.Remove in this loop does not only delete
// from the context but also from the child collection. Without making
// the copy we would modify the collection we are just interating
// through - which is forbidden and would lead to an exception.)
foreach (var originalChildItem in
originalParent.ChildItems.Where(c => c.ID != 0).ToList())
{
// Are there child items in the DB which are NOT in the
// new child item collection anymore?
if (!parent.ChildItems.Any(c => c.ID == originalChildItem.ID))
// Yes -> It's a deleted child item -> Delete
_dbContext.ChildItems.Remove(originalChildItem);
}
_dbContext.SaveChanges();
}
Note: This is not tested. It's assuming that the child item collection is of type ICollection
. (I usually have IList
and then the code looks a bit different.) I've also stripped away all repository abstractions to keep it simple.
I don't know if that is a good solution, but I believe that some kind of hard work along these lines must be done to take care of all kinds of changes in the navigation collection. I would also be happy to see an easier way of doing it.
You may have to concatenate the % signs with your parameter, e.g.:
LIKE '%' || @query || '%'
Edit: Actually, that may not make any sense at all. I think I may have misunderstood your problem.
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.standard.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
--launcher.appendVmargs
**-vm
C:/Program Files (x86)/Java/jdk1.7.0_45/bin/javaw.exe** =>false
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms40m
-Xmx512m
-vm
C:\Program Files (x86)\Java\jdk1.7.0_45\bin\javaw.exe
Can you pick the appropriate char set in the Constructor:
new InputStreamReader(new FileInputStream(in), "ISO8859_1");
Just use the location.host property
switch (location.host) {
case "xxx.local":
settings = ...
break;
case "xxx.dev.yyy.com":
settings = ...
break;
}
Another one liner without a function:
(for e in "${array[@]}"; do [[ "$e" == "searched_item" ]] && exit 0; done) && echo "found" || echo "not found"
Thanks @Qwerty for the heads up regarding spaces!
corresponding function:
find_in_array() {
local word=$1
shift
for e in "$@"; do [[ "$e" == "$word" ]] && return 0; done
return 1
}
example:
some_words=( these are some words )
find_in_array word "${some_words[@]}" || echo "expected missing! since words != word"
Try to edit your project build.gradle file and set the android build gradle plugin to classpath 'com.android.tools.build:gradle:3.2.1'
within the dependency section.
Feel free to use my library, available here.
It let's you create header View
for any RecyclerView
that uses LinearLayoutManager
or GridLayoutManager
with just a simple method call.
list(set(listone) | set(listtwo))
The above code, does not preserve order, removes duplicate from each list (but not from the concatenated list)