Getting this error, I changed the
c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD
for both code project and associated Google Test project. This solved the issue.
Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.
If you are trying to open a file in the same directory it would be:
./PROGRAM TRYING TO OPEN
./FILE NAME/PROGRAM TRYING TO OPEN (or this)
Or, if trying to backtrack from the same directory it would be:
../PROGRAM TRYING TO OPEN
../FILE NAME/PROGRAM TRYING TO OPEN (or this)
Else, if you need a straight one from start, it would be:
(DIRECTORY TYPE)\Users\%username%\(FILE DIRECTORY)
(ex) C:\Users\ajste\Desktop\Henlo.cmd
I had the same problem. Following change made it work -
android:layout_width="wrap_content"
The ellipsis, maxLines, or layout_weight - all didn't make any difference. Note - The parent width is also set as wrap_content.
i would recommend Modern UI for WPF .
It has a very active maintainer it is awesome and free!
I'm currently porting some projects to MUI, first (and meanwhile second) impression is just wow!
To see MUI in action you could download XAML Spy which is based on MUI.
EDIT: Using Modern UI for WPF a few months and i'm loving it!
Craigslist does have a "bulk posting interface" which allows for multiple posts to happen at once through HTTPS POST. See:
You have to create a derived table for the distinct columns and then query the count from that table:
SELECT COUNT(*)
FROM (SELECT DISTINCT column1,column2
FROM tablename
WHERE condition ) as dt
Here dt
is a derived table.
A supplementarily handy (but trivial) tip for installing older version of packages from source.
First, if you call "install.packages", it always installs the latest package from repo. If you want to install the older version of packages, say for compatibility, you can call install.packages("url_to_source", repo=NULL, type="source"). For example:
install.packages("http://cran.r-project.org/src/contrib/Archive/RNetLogo/RNetLogo_0.9-6.tar.gz", repo=NULL, type="source")
Without manually downloading packages to the local disk and switching to the command line or installing from local disk, I found it is very convenient and simplify the call (one-step).
Plus: you can use this trick with devtools library's dev_mode, in order to manage different versions of packages:
Reference: doc devtools
Rather than setting a flag, it could be more elegant to use JavaScript's Array.prototype.find
to find the matching item in the array. The loop will end as soon as a truthy value is returned from the callback, and the array value during that iteration will be the .find
call's return value:
function findXX(word) {
return someArray.find((item, i) => {
$('body').append('-> '+i+'<br />');
return item === word;
});
}
const someArray = new Array();
someArray[0] = 't5';
someArray[1] = 'z12';
someArray[2] = 'b88';
someArray[3] = 's55';
someArray[4] = 'e51';
someArray[5] = 'o322';
someArray[6] = 'i22';
someArray[7] = 'k954';
var test = findXX('o322');
console.log('found word:', test);
function findXX(word) {
return someArray.find((item, i) => {
$('body').append('-> ' + i + '<br />');
return item === word;
});
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Most easy and clean solution to avoid this is adding onclick="return false;"
to a
tag.
<ul class="nav nav-tabs">
<li class="active">
<a href="#home" onclick="return false;">Home</a>
</li>
<li>
<a href="#ApprovalDetails" onclick="return false;">Approval Details</a>
</li>
</ul>
"cursor:no-drop;"
just makes cursor look disabled, but is clickable, Url gets appending with href target for ex page.apsx#Home
"disabled"
class to <li>
AND removing href
There may be different reason for reported issue, few days back also face this issue 'duplicate jar', after upgrading studio. From all stackoverflow I tried all the suggestion but nothing worked for me.
But this is for sure some duplicate jar is there, For me it was present in one library libs folder as well as project libs folder. So I removed from project libs folder as it was not required here. So be careful while updating the studio, and try to understand all the gradle error.
Assume you have class (A) that aggregates two other (B) (C), and you need to store instances of (A) inside hashtable. Default implementation only allows distinguishing of instances, but not by (B) and (C). So two instances of A could be equal, but default wouldn't allow you to compare them in correct way.
Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.
Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.
The answer to my question is at Ansible: best practice for maintaining list of sudoers.
The Ansible playbook code fragment looks like this from my problem:
- name: Make sure we have a 'wheel' group
group:
name: wheel
state: present
- name: Allow 'wheel' group to have passwordless sudo
lineinfile:
dest: /etc/sudoers
state: present
regexp: '^%wheel'
line: '%wheel ALL=(ALL) NOPASSWD: ALL'
validate: 'visudo -cf %s'
- name: Add sudoers users to wheel group
user:
name=deployer
groups=wheel
append=yes
state=present
createhome=yes
- name: Set up authorized keys for the deployer user
authorized_key: user=deployer key="{{item}}"
with_file:
- /home/railsdev/.ssh/id_rsa.pub
And the best part is that the solution is idempotent. It doesn't add the line
%wheel ALL=(ALL) NOPASSWD: ALL
to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.
I was also having this issue of "You have mail" coming up every time I started Terminal.
What I discovered is this.
Something I'd installed (not entirely sure what, but possibly a script or something associated with an Alfred Workflow [at a guess]) made a change to the OS X system to start presenting Terminal bash notifications. Prior to that, it appears Wordpress had attempted to use the Local Mail system to send a message. The message bounced, due to it having an invalid Recipient address. The bounced message then ended up in the local system mail inbox. So Terminal (bash) was then notifying me that "You have mail".
You can access the mail by simply using the command
mail
This launches you into Mail, and it will right away show you a list of messages that are stored there. If you want to see the content of the first message, use
t
This will show you the content of the first message, in full. You'll need to scroll down through the message to view it all, by hitting the down-arrow
key.
If you want to jump to the end of the message, use the
spacebar
If you want to abort viewing the message, use
q
To view the next message in the queue use
n
... assuming there's more than one message.
NOTE: You need to use these commands at the mail ?
command prompt. They won't work whilst you are in the process of viewing a message. Hitting n
whilst viewing a message will just cause an error message related to regular expressions. So, if in the midst of viewing a message, hit q
to quit from that, or hit spacebar
to jump to the end of the message, and then at the ?
prompt, hit n
.
Viewing the content of the messages in this way may help you identify what attempted to send the message(s).
You can also view a specific message by just inputting its number at the ?
prompt. 3
, for instance, will show you the content of the third message (if there are that many in there).
Use the d
command (at the ?
command prompt )
d [message number]
To delete each message when you are done looking at them. For example, d 2
will delete message number 2. Or you can delete a list of messages, such as d 1 2 5 7
. Or you can delete a range of messages with (for example), d 3-10
.
You can find the message numbers in the list of messages mail shows you.
To delete all the messages, from the mail prompt (?
) use the command d *
.
As per a comment on this post, you will need to use q
to quit mail, which also saves any changes.
If you'd like to see the mail all in one output, use this command at the bash prompt (i.e. not from within mail, but from your regular command prompt):
cat /var/mail/<username>
And, if you wish to delete the emails all in one hit, use this command
sudo rm /var/mail/<username>
In my particular case, there were a number of messages. It looks like the one was a returned message that bounced. It was sent by a local Wordpress installation. It was a notification for when user "Admin" (me) changed its password. Two additional messages where there. Both seemed to be to the same incident.
What I don't know, and can't answer for you either, is WHY I only recently started seeing this mail notification each time I open Terminal. The mails were generated a couple of months ago, and yet I only noticed this "you have mail" appearing in the last few weeks. I suspect it's the result of something a workflow I installed in Alfred, and that workflow using Terminal bash to provide notifications... or something along those lines.
If you have no interest in determining the source of the messages, and just wish to get rid of them, it may be easier to do so without using the mail
command (which can be somewhat fiddly). As pointed out by a few other people, you can use this command instead:
sudo rm /var/mail/YOURUSERNAME
private DataTable CreateDataTable(IList<T> item)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
}
foreach (T entity in item)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
Well, you're going to want document.location
. Do some sort of string manipulation on it (unless jQuery has a way to avoid that work for you) and then
$(body).addClass(foo);
I know this isn't the complete answer, but I assume you can work the rest out :)
You can set default behavior of modal popup by using of below line of code:
$.fn.modal.prototype.constructor.Constructor.DEFAULTS.backdrop = 'static';
To debug, check server logs if possible. Firefox returns CORS errors in console for a whole range of reasons.
One of the reasons is also uMatrix (and I guess NoScript and similar too) plugin.
I found a simple way
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
Think of this, it kills the process:
System.Diagnostics.Process[] process=System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process p in process)
{
if (!string.IsNullOrEmpty(p.ProcessName))
{
try
{
p.Kill();
}
catch { }
}
}
Also, did you try just close it normally?
myWorkbook.SaveAs(@"C:/pape.xltx", missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
excelBook.Close(null, null, null); // close your workbook
excelApp.Quit(); // exit excel application
excel = null; // set to NULL
you are trying to open a socket to a file on the remote host which is not correct. you could make a socket connection (TCP/UDP) to a port number on a remote host. so your code should be like this:
fsockopen('www.mysite.com', 80);
if you are trying to create a file pointer resource to a remote file, you may use the fopen() function. but to do this, you need to specify the application protocol as well.
PHP provides default stream wrappers for URL file opens. based on the schema of the URL the appropriate stream wrapper will be called internally. the URL you are trying to open does not have a valid schema for this solution. make sure there is a schema like "http://" or "ftp://" in it.
so the code would be like this:
$fp = fopen('http://www.mysite.com/path/file.txt');
Besides I don't think the HTTP stream wrapper (that handles actions on file resources on URLs with http schema) supports writing of data. you can use fread() to read contents of a the URL through HTTP, but I'm not sure about writing.
EDIT: from comments and other answers I figured out you would want to send a HTTP request to the specified URL. the methods described in this answer are for when you want to receive data from the remote URL. if you want to send data, you can use http_request() to do this.
In WSDL definition, bindings contain operations, here comes style for each operation.
Document : In WSDL file, it specifies types details either having inline Or imports XSD document, which describes the structure(i.e. schema) of the complex data types being exchanged by those service methods which makes loosely coupled. Document style is default.
In WSDL types element looks as follows:
<types>
<xsd:schema>
<xsd:import schemaLocation="http://localhost:9999/ws/hello?xsd=1" namespace="http://ws.peter.com/"/>
</xsd:schema>
</types>
The schema is importing from external reference.
RPC :In WSDL file, it does not creates types schema, within message elements it defines name and type attributes which makes tightly coupled.
<types/>
<message name="getHelloWorldAsString">
<part name="arg0" type="xsd:string"/>
</message>
<message name="getHelloWorldAsStringResponse">
<part name="return" type="xsd:string"/>
</message>
RPC : No types in WSDL
Document: Types section would be available in WSDL
Have you tried DevDefined.OAuth?
I have used it to secure my WebApi with 2-Legged OAuth. I have also successfully tested it with PHP clients.
It's quite easy to add support for OAuth using this library. Here's how you can implement the provider for ASP.NET MVC Web API:
1) Get the source code of DevDefined.OAuth: https://github.com/bittercoder/DevDefined.OAuth - the newest version allows for OAuthContextBuilder
extensibility.
2) Build the library and reference it in your Web API project.
3) Create a custom context builder to support building a context from HttpRequestMessage
:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Web;
using DevDefined.OAuth.Framework;
public class WebApiOAuthContextBuilder : OAuthContextBuilder
{
public WebApiOAuthContextBuilder()
: base(UriAdjuster)
{
}
public IOAuthContext FromHttpRequest(HttpRequestMessage request)
{
var context = new OAuthContext
{
RawUri = this.CleanUri(request.RequestUri),
Cookies = this.CollectCookies(request),
Headers = ExtractHeaders(request),
RequestMethod = request.Method.ToString(),
QueryParameters = request.GetQueryNameValuePairs()
.ToNameValueCollection(),
};
if (request.Content != null)
{
var contentResult = request.Content.ReadAsByteArrayAsync();
context.RawContent = contentResult.Result;
try
{
// the following line can result in a NullReferenceException
var contentType =
request.Content.Headers.ContentType.MediaType;
context.RawContentType = contentType;
if (contentType.ToLower()
.Contains("application/x-www-form-urlencoded"))
{
var stringContentResult = request.Content
.ReadAsStringAsync();
context.FormEncodedParameters =
HttpUtility.ParseQueryString(stringContentResult.Result);
}
}
catch (NullReferenceException)
{
}
}
this.ParseAuthorizationHeader(context.Headers, context);
return context;
}
protected static NameValueCollection ExtractHeaders(
HttpRequestMessage request)
{
var result = new NameValueCollection();
foreach (var header in request.Headers)
{
var values = header.Value.ToArray();
var value = string.Empty;
if (values.Length > 0)
{
value = values[0];
}
result.Add(header.Key, value);
}
return result;
}
protected NameValueCollection CollectCookies(
HttpRequestMessage request)
{
IEnumerable<string> values;
if (!request.Headers.TryGetValues("Set-Cookie", out values))
{
return new NameValueCollection();
}
var header = values.FirstOrDefault();
return this.CollectCookiesFromHeaderString(header);
}
/// <summary>
/// Adjust the URI to match the RFC specification (no query string!!).
/// </summary>
/// <param name="uri">
/// The original URI.
/// </param>
/// <returns>
/// The adjusted URI.
/// </returns>
private static Uri UriAdjuster(Uri uri)
{
return
new Uri(
string.Format(
"{0}://{1}{2}{3}",
uri.Scheme,
uri.Host,
uri.IsDefaultPort ?
string.Empty :
string.Format(":{0}", uri.Port),
uri.AbsolutePath));
}
}
4) Use this tutorial for creating an OAuth provider: http://code.google.com/p/devdefined-tools/wiki/OAuthProvider. In the last step (Accessing Protected Resource Example) you can use this code in your AuthorizationFilterAttribute
attribute:
public override void OnAuthorization(HttpActionContext actionContext)
{
// the only change I made is use the custom context builder from step 3:
OAuthContext context =
new WebApiOAuthContextBuilder().FromHttpRequest(actionContext.Request);
try
{
provider.AccessProtectedResourceRequest(context);
// do nothing here
}
catch (OAuthException authEx)
{
// the OAuthException's Report property is of the type "OAuthProblemReport", it's ToString()
// implementation is overloaded to return a problem report string as per
// the error reporting OAuth extension: http://wiki.oauth.net/ProblemReporting
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
RequestMessage = request, ReasonPhrase = authEx.Report.ToString()
};
}
}
I have implemented my own provider so I haven't tested the above code (except of course the WebApiOAuthContextBuilder
which I'm using in my provider) but it should work fine.
for Swift 3.1 or later
firstly add protocol UITextFieldDelegate
like:-
class PinCodeViewController: UIViewController, UITextFieldDelegate {
.....
.....
.....
}
after that create your UITextField and set delegate
Complete Exp: -
import UIKit
class PinCodeViewController: UIViewController, UITextFieldDelegate {
let pinCodetextField: UITextField = {
let tf = UITextField()
tf.placeholder = "please enter your pincode"
tf.font = UIFont.systemFont(ofSize: 15)
tf.borderStyle = UITextBorderStyle.roundedRect
tf.autocorrectionType = UITextAutocorrectionType.no
tf.keyboardType = UIKeyboardType.numberPad
tf.clearButtonMode = UITextFieldViewMode.whileEditing;
tf.contentVerticalAlignment = UIControlContentVerticalAlignment.center
return tf
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(pinCodetextField)
//----- setup your textfield anchor or position where you want to show it-----
// after that
pinCodetextField.delegate = self // setting the delegate
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return !(textField.text?.characters.count == 6 && string != "")
} // this is return the maximum characters in textfield
}
Trailing whitespace:
It is extra spaces (and tabs) at the end of line
^^^^^ here
Strip them:
#!/usr/bin/env python2
"""\
strip trailing whitespace from file
usage: stripspace.py <file>
"""
import sys
if len(sys.argv[1:]) != 1:
sys.exit(__doc__)
content = ''
outsize = 0
inp = outp = sys.argv[1]
with open(inp, 'rb') as infile:
content = infile.read()
with open(outp, 'wb') as output:
for line in content.splitlines():
newline = line.rstrip(" \t")
outsize += len(newline) + 1
output.write(newline + '\n')
print("Done. Stripped %s bytes." % (len(content)-outsize))
Add more columns when you have variable loops that repeat at different rates. I'm not sure explicitly what you're trying to do, but I think I've done something that could apply.
Creating a single loop in Excel is prettty simple. It actually does the work for you. Try this on a new workbook
A3 will automatically be "=A2+1" as you drag down. The first steps don't have to be that explicit. Excel will automatically recognize the pattern and count if you just put "2" in A2, but if we want B1-B5 to be "100" and B5-B10 to be "200" (counting up the same way) you can see why knowing how to do it explicitly matters. In this scenario, You just enter:
B7 will automatically be "=B2+100" etc. as you drag down, so basically it increases every 5 rows infinitely. To make a loop of numbers 1-5 in column A:
So, now we have column A repeating numbers 1-5 while column B is increasing by 100 every 5 cells.You could make column B repeat, for instance, the numbers 100-900 in using the same method as you did with column A as a way to produce, for instance, each possible combination with multiple variables. Drag down the columns and they'll do it infinitely. I'm not explicitly addressing the scenario given, but if you follow the steps and understand them, the concept should give you an answer to the problem that involves adding more columns and concactinating or using them as your variables.
Update for Swift 3:
// Create the AlertController and add its actions like button in ActionSheet
let actionSheetController = UIAlertController(title: "Please select", message: "Option to select", preferredStyle: .actionSheet)
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
let saveActionButton = UIAlertAction(title: "Save", style: .default) { action -> Void in
print("Save")
}
actionSheetController.addAction(saveActionButton)
let deleteActionButton = UIAlertAction(title: "Delete", style: .default) { action -> Void in
print("Delete")
}
actionSheetController.addAction(deleteActionButton)
self.present(actionSheetController, animated: true, completion: nil)
A slight change in the execute query will solve the problem:
DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId int
exec ('SELECT TOP 1 **''@siteId''** = Id FROM ' + @dbName + '..myTbl')
select @siteId
Interfaces where a fetature added to java to allow multiple inheritance. The developers of Java though/realized that having multiple inheritance was a "dangerous" feature, that is why the came up with the idea of an interface.
multiple inheritance is dangerous because you might have a class like the following:
class Box{
public int getSize(){
return 0;
}
public int getArea(){
return 1;
}
}
class Triangle{
public int getSize(){
return 1;
}
public int getArea(){
return 0;
}
}
class FunckyFigure extends Box, Triable{
// we do not implement the methods we will used the inherited ones
}
Which would be the method that should be called when we use
FunckyFigure.GetArea();
All the problems are solved with interfaces, because you do know you can extend the interfaces and that they wont have classing methods... ofcourse the compiler is nice and tells you if you did not implemented a methods, but I like to think that is a side effect of a more interesting idea.
Please refer to this updated answer: https://stackoverflow.com/a/46830425/4031815
I'm not aware of any current technique to avoid the flicker as the font loads, however you can minimize it by sending proper cache headers for your font and making sure that that request goes through as quickly as possible.
The files in your working copy might look exactly the same after, but they are still very different actions -- the repository is in a completely different state, and you will have different options available to you after reverting than "updating" to an old revision.
Briefly, "update to" only affects your working copy, but "reverse merge and commit" will affect the repository.
If you "update" to an old revision, then the repository has not changed: in your example, the HEAD revision is still 100. You don't have to commit anything, since you are just messing around with your working copy. If you make modifications to your working copy and try to commit, you will be told that your working copy is out-of-date, and you will need to update before you can commit. If someone else working on the same repository performs an "update", or if you check out a second working copy, it will be r100.
However, if you "reverse merge" to an old revision, then your working copy is still based on the HEAD (assuming you are up-to-date) -- but you are creating a new revision to supersede the unwanted changes. You have to commit these changes, since you are changing the repository. Once done, any updates or new working copies based on the HEAD will show r101, with the contents you just committed.
//get main activity
final Activity main_activity=getActivity();
//list view click listener
final ListView listView = (ListView) inflatedView.findViewById(R.id.listView_id);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String stringText;
//in normal case
stringText= ((TextView)view).getText().toString();
//in case if listview has separate item layout
TextView textview=(TextView)view.findViewById(R.id.textview_id_of_listview_Item);
stringText=textview.getText().toString();
//show selected
Toast.makeText(main_activity, stringText, Toast.LENGTH_LONG).show();
}
});
//populate listview
According to the Javascript standard, String.replace
isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.
You can always just set the string to the modified value:
variableABC = variableABC.replace('B', 'D')
Edit: The code given above is to only replace the first occurrence.
To replace all occurrences, you could do:
variableABC = variableABC.replace(/B/g, "D");
To replace all occurrences and ignore casing
variableABC = variableABC.replace(/B/gi, "D");
You will either have to specify a DEFAULT, or add the column with NULLs allowed, update all the values, and then change the column to NOT NULL.
ALTER TABLE <YourTable>
ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>
Also make sure the aspx page has AutoEventWireup="true"
and not AutoEventWireup="false"
Using the wildcard * selector in CSS to override inheritance for all attributes of an element (by setting these back to their initial state).
An example of its use:
li * {
display: initial;
}
It's hard to say without looking at at code. Make sure your function doesn't return more than one object and that you capture any results made from other calls. What do you get for:
@($returnURL).count
Anyway, two suggestions:
Cast the object to string:
...
return [string]$rs
Or just enclose it in double quotes, same as above but shorter to type:
...
return "$rs"
Its all about Method Overloading.
There are individual methods for each data type in println() method
If you pass object :
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
If you pass Primitive type:
corresponding primitive type method calls
if you pass String :
corresponding println(String x) method calls
Simple and Best
echo date('Y-m-d H:i:s')."\n";
echo "<br>";
echo date('Y-m-d H:i:s', mktime(date('H'),date('i'),date('s'), date('m'),date('d')+30,date('Y')))."\n";
Try this
Reason of the error: Package name left blank while creating a class. This make use of default package. Thus causes this error.
Quick fix:
helloWorld
inside the src
folder.helloWorld.java
file in that package. Just drag and drop on
the package. Error should disappear.Explanation:
Latest version of Eclipse required java11 or above. The module
feature is introduced in java9 and onward. It was proposed in 2005 for Java7 but later suspended. Java is object oriented based. And module is the moduler approach which can be seen in language like C. It was harder to implement it, due to which it took long time for the release. Source: Understanding Java 9 Modules
When you create a new project in Eclipse then by default module feature is selected. And in Eclipse-2020-09-R, a pop-up appears which ask for creation of module-info.java
file. If you select don't create
then module-info.java
will not create and your project will free from this issue.
Best practice is while crating project, after giving project name. Click on next
button instead of finish
. On next page at the bottom it ask for creation of module-info.java
file. Select or deselect as per need.
If selected: (by default) click on finish
button and give name for module. Now while creating a class don't forget to give package name. Whenever you create a class just give package name. Any name, just don't left it blank.
If deselect: No issue
I find this more elegant than the two top answers:
from urllib.parse import urlencode, urlparse, parse_qs
def merge_url_query_params(url: str, additional_params: dict) -> str:
url_components = urlparse(url)
original_params = parse_qs(url_components.query)
# Before Python 3.5 you could update original_params with
# additional_params, but here all the variables are immutable.
merged_params = {**original_params, **additional_params}
updated_query = urlencode(merged_params, doseq=True)
# _replace() is how you can create a new NamedTuple with a changed field
return url_components._replace(query=updated_query).geturl()
assert merge_url_query_params(
'http://example.com/search?q=question',
{'lang':'en','tag':'python'},
) == 'http://example.com/search?q=question&lang=en&tag=python'
The most important things I dislike in the top answers (they are nevertheless good):
query
is in the URL componentsParseResult
What's bad about my response is the magically looking dict
merge using unpacking, but I prefer that to updating an already existing dictionary because of my prejudice against mutability.
You absolutely need to make a new tuple -- then you can rebind the name (or whatever reference[s]) from the old tuple to the new one. The +=
operator can help (if there was only one reference to the old tuple), e.g.:
thetup += ('1200.00',)
does the appending and rebinding in one fell swoop.
+1 means 2 days ago. It's rounded.
SELECT to_char(Closing_Date,'MM'),
Category,
COUNT(Status) TotalCount
FROM MyTable
WHERE Closing_Date >= '2012-02-01'
AND Closing_Date <= '2012-12-31'
AND Defect_Status1 IS NOT NULL
GROUP BY Category;
I just went through the character map to get these. They are all in Calibri.
Number Name HTML Code Appearance ------ -------------------- --------- ---------- U+2000 En Quad   " " U+2001 Em Quad   " " U+2002 En Space   " " U+2003 Em Space   " " U+2004 Three-Per-Em Space   " " U+2005 Four-Per-Em Space   " " U+2006 Six-Per-Em Space   " " U+2007 Figure Space   " " U+2008 Punctuation Space   " " U+2009 Thin Space   " " U+200A Hair Space   " " U+200B Zero-Width Space ​ "" U+200C Zero Width Non-Joiner ‌ "" U+200D Zero Width Joiner ‍ "" U+200E Left-To-Right Mark ‎ "" U+200F Right-To-Left Mark ‏ "" U+202F Narrow No-Break Space   " "
You can pass a callback function as parameter when you call navigate like this:
const DEMO_TOKEN = await AsyncStorage.getItem('id_token');
if (DEMO_TOKEN === null) {
this.props.navigation.navigate('Login', {
onGoBack: () => this.refresh(),
});
return -3;
} else {
this.doSomething();
}
And define your callback function:
refresh() {
this.doSomething();
}
Then in the login/registration view, before goBack, you can do this:
await AsyncStorage.setItem('id_token', myId);
this.props.navigation.state.params.onGoBack();
this.props.navigation.goBack();
Update for React Navigation v5:
await AsyncStorage.setItem('id_token', myId);
this.props.route.params.onGoBack();
this.props.navigation.goBack();
You are using .net 4? - Maybe on the clients there is only the ".net framework 4 client profile" installed. Try to install full package!! Download here
You can do this by setting a style in your paragraph tag. For example if you wanted to change the font size to 28px.
<p style="font-size: 28px;"> Hello, World! </p>
You can also set the color by setting:
<p style="color: blue;"> Hello, World! </p>
However, if you want to preview font sizes and colors (which I recommend doing) before you add them to your website and use them. I recommend testing them out beforehand so you pick a good font size and color that contrasts well with the background. I recommend using this site if you wish to do so, couldn't find anything else: http://fontpreview.herokuapp.com/
Replace the desired hyphen with an underscore; it will automatically be rendered as a hyphen:
@Html.ActionLink("Edit", "edit", "markets",
new { id = 1 },
new {@class="ui-btn-right", data_icon="gear"})
becomes:
<form action="markets/Edit/1" class="ui-btn-right" data-icon="gear" .../>
Here is another way you can get to the root of your website without hard coding the url:
var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);
Note: Will only work if both your MVC website and WebApi are on the same URL
One way: (implementing 'considered equal' for http://tools.ietf.org/html/rfc6902#section-4.6)
This way allows associative arrays whose members are ordered differently - e.g. they'd be considered equal in every language but php :)
// recursive ksort
function rksort($a) {
if (!is_array($a)) {
return $a;
}
foreach (array_keys($a) as $key) {
$a[$key] = ksort($a[$key]);
}
// SORT_STRING seems required, as otherwise
// numeric indices (e.g. "0") aren't sorted.
ksort($a, SORT_STRING);
return $a;
}
// Per http://tools.ietf.org/html/rfc6902#section-4.6
function considered_equal($a1, $a2) {
return json_encode(rksort($a1)) === json_encode(rksort($a2));
}
First Add dependency to build.gradle:
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
While using Kotlin you can add Logging Interceptor like this :
companion object {
val okHttpClient = OkHttpClient().newBuilder()
.addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
})
.build()
fun getRetrofitInstance(): Retrofit {
val retrofit = Retrofit.Builder()
.client(okHttpClient)
.baseUrl(ScanNShopConstants.BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit
}
}
I suggest checking if the substring is a digit:
In [1]: [int(i) for i in '1 2 3a'.split() if i.isdigit()]
Out[1]: [1, 2]
Here is a simpler way to iterate and print values in vector.
for(int x: A) // for integer x in vector A
cout<< x <<" ";
In 2014 I still think my point holds:
IMHO, this discussion got blown out of proportion quite a bit. Quoting the aforementioned blog post:
Most JavaScript utility libraries, such as Underscore, Valentine, and wu, rely on the “native-first dual approach.” This approach prefers native implementations, falling back to vanilla JavaScript only if the native equivalent is not supported. But jsPerf revealed an interesting trend: the most efficient way to iterate over an array or array-like collection is to avoid the native implementations entirely, opting for simple loops instead.
As if "simple loops" and "vanilla Javascript" are more native than Array or Object method implementations. Jeez ...
It certainly would be nice to have a single source of truth, but there isn't. Even if you've been told otherwise, there is no Vanilla God, my dear. I'm sorry. The only assumption that really holds is that we are all writing JavaScript code that aims at performing well in all major browsers, knowing that all of them have different implementations of the same things. It's a bitch to cope with, to put it mildly. But that's the premise, whether you like it or not.
Maybe all of you are working on large scale projects that need twitterish performance so that you really see the difference between 850,000 (Underscore.js) vs. 2,500,000 (Lodash) iterations over a list per second right now!
I for one am not. I mean, I worked on projects where I had to address performance issues, but they were never solved or caused by neither Underscore.js nor Lodash. And unless I get hold of the real differences in implementation and performance (we're talking C++ right now) of, let’s say, a loop over an iterable (object or array, sparse or not!), I rather don't get bothered with any claims based on the results of a benchmark platform that is already opinionated.
It only needs one single update of, let’s say, Rhino to set its Array method implementations on fire in a fashion that not a single "medieval loop methods perform better and forever and whatnot" priest can argue his/her way around the simple fact that all of a sudden array methods in Firefox are much faster than his/her opinionated brainfuck. Man, you just can't cheat your runtime environment by cheating your runtime environment! Think about that when promoting ...
your utility belt
... next time.
So to keep it relevant:
Choose whatever approach fits your needs the most. As usual. I'd prefer fallbacks on actual implementations over opinionated runtime cheats anytime, but even that seems to be a matter of taste nowadays. Stick to quality resources like http://developer.mozilla.com and http://caniuse.com and you'll be just fine.
If you are here because of the Liquibase error saying:
Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short
and you are using
not {
indexExists()
}
precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342
We can try to execute an above check using bare sqlCheck
(Postgres):
SELECT COUNT(i.relname)
FROM
pg_class t,
pg_class i,
pg_index ix
WHERE
t.oid = ix.indrelid
and i.oid = ix.indexrelid
and t.relkind = 'r'
and t.relname = 'tableName'
and i.relname = 'indexName';
where tableName
- is an index table name and indexName
- is an index name
This is a solution without creating manually a file on disc :
MultipartFile fichier = new MockMultipartFile("fileThatDoesNotExists.txt",
"fileThatDoesNotExists.txt",
"text/plain",
"This is a dummy file content".getBytes(StandardCharsets.UTF_8));
PDOStatement::fetch returns a row from the result set. The parameter PDO::FETCH_ASSOC
tells PDO to return the result as an associative array.
The array keys will match your column names. If your table contains columns 'email' and 'password', the array will be structured like:
Array
(
[email] => '[email protected]'
[password] => 'yourpassword'
)
To read data from the 'email' column, do:
$user['email'];
and for 'password':
$user['password'];
You could do it with jsoup http://jsoup.org/
Whitelist whitelist = Whitelist.none();
String cleanStr = Jsoup.clean(yourText, whitelist);
You can use the following regex globally:
\[(.*?)\]
Explanation:
\[
: [
is a meta char and needs to be escaped if you want to match it literally.(.*?)
: match everything in a non-greedy way and capture it.\]
: ]
is a meta char and needs to be escaped if you want to match it literally.How OAuth 2.0 works in real life:
I was driving by Olaf's bakery on my way to work when I saw the most delicious donut in the window -- I mean, the thing was dripping chocolatey goodness. So I went inside and demanded "I must have that donut!". He said "sure that will be $30."
Yeah I know, $30 for one donut! It must be delicious! I reached for my wallet when suddenly I heard the chef yell "NO! No donut for you". I asked: why? He said he only accepts bank transfers.
Seriously? Yep, he was serious. I almost walked away right there, but then the donut called out to me: "Eat me, I'm delicious...". Who am I to disobey orders from a donut? I said ok.
He handed me a note with his name on it (the chef, not the donut): "Tell them Olaf sent you". His name was already on the note, so I don't know what the point of saying that was, but ok.
I drove an hour and a half to my bank. I handed the note to the teller; I told her Olaf sent me. She gave me one of those looks, the kind that says, "I can read".
She took my note, asked for my id, asked me how much money was ok to give him. I told her $30 dollars. She did some scribbling and handed me another note. This one had a bunch of numbers on it, I guessed that's how they keep track of the notes.
At that point I'm starving. I rushed out of there, an hour and a half later I was back, standing in front of Olaf with my note extended. He took it, looked it over and said, "I'll be back".
I thought he was getting my donut, but after 30 minutes I started to get suspicious. So I asked the guy behind the counter "Where's Olaf?". He said "He went to get money". "What do you mean?". "He take note to bank".
Huh... so Olaf took the note that the bank gave me and went back to the bank to get money out of my account. Since he had the note the bank gave me, the bank knew he was the guy I was talking about, and because I spoke with the bank they knew to only give him $30.
It must have taken me a long time to figure that out because by the time I looked up, Olaf was standing in front of me finally handing me my donut. Before I left I had to ask, "Olaf, did you always sell donuts this way?". "No, I used to do it different."
Huh. As I was walking back to my car my phone rang. I didn't bother answering, it was probably my job calling to fire me, my boss is such a ***. Besides, I was caught up thinking about the process I just went through.
I mean think about it: I was able to let Olaf take $30 out of my bank account without having to give him my account information. And I didn't have to worry that he would take out too much money because I already told the bank he was only allowed to take $30. And the bank knew he was the right guy because he had the note they gave me to give to Olaf.
Ok, sure I would rather hand him $30 from my pocket. But now that he had that note I could just tell the bank to let him take $30 every week, then I could just show up at the bakery and I didn't have to go to the bank anymore. I could even order the donut by phone if I wanted to.
Of course I'd never do that -- that donut was disgusting.
I wonder if this approach has broader applications. He mentioned this was his second approach, I could call it Olaf 2.0. Anyway I better get home, I gotta start looking for a new job. But not before I get one of those strawberry shakes from that new place across town, I need something to wash away the taste of that donut.
To avoid exceptions killing your app you should catch those exceptions and treat them the way you wish, defining the behavior for you app on those situations where the id is not found.
begin
current_user.comments.find(ids)
rescue
#do something in case of exception found
end
Here's more info on exceptions in ruby.
While passing string constants
to functions write it as:
void setpart(const char name[]);
setpart("Hello");
instead of const char name[]
, you could also write const char \*name
It worked for me to remove this error:
[Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]
I saw this and in CSS3 you can now place code in like this. Lets say I want it to cover the whole background I would do something like this. Then with hsla(0,0%,100%,0.70)
or rgba you use a white background with whatever percentage saturation or opacity to get the look you desire.
.body{
background-attachment: fixed;
background-image: url(../images/Store1.jpeg);
display: block;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 1;
background-color: hsla(0,0%,100%,0.70);
background-blend-mode: overlay;
background-repeat: no-repeat;
}
The problem was a missing dependency that wasn't on the server but was on my local machine. In our case, it was a Devart.Data.Linq dll.
To get to that answer, I turned on IIS tracing for 500 errors. That gave a little bit of information, but the really helpful thing was in the web.config setting the <system.web><customErrors mode="Off"/></system.web>
This pointed to a missing dynamically-loaded dependency. After adding this dependency and telling it to be copied locally, the server started working.
static void Main(string[] args)
{
HTTPGet req = new HTTPGet();
req.Request("http://checkip.dyndns.org");
string[] a = req.ResponseBody.Split(':');
string a2 = a[1].Substring(1);
string[] a3=a2.Split('<');
string a4 = a3[0];
Console.WriteLine(a4);
Console.ReadLine();
}
Do this small trick with Check IP DNS
Use HTTPGet
class i found on Goldb-Httpget C#
git branch
with no arguments displays the current branch marked with an asterisk in front of it:
user@host:~/gittest$ git branch
* master
someotherbranch
In order to not have to type this all the time, I can recommend git prompt:
https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh
In the AIX box how I can see that I am using master or inside a particular branch. What changes inside .git that drives which branch I am on?
Git stores the HEAD
in the file .git/HEAD
. If you're on the master
branch, it could look like this:
$ cat .git/HEAD
ref: refs/heads/master
I faced the same issue. I updated my Android studio and used API 25 target as Android 7.1.1 and X86 and everything worked fine. I use Google play services and firebase for my project
Add the following to your /etc/bashrc file. This script adds a resident "function" instead of an alias called "confirm".
function confirm( )
{
#alert the user what they are about to do.
echo "About to $@....";
#confirm with the user
read -r -p "Are you sure? [Y/n]" response
case "$response" in
[yY][eE][sS]|[yY])
#if yes, then execute the passed parameters
"$@"
;;
*)
#Otherwise exit...
echo "ciao..."
exit
;;
esac
}
<form action="myController/myAction" method="POST">
<input type="text" name="valueINeed" />
<input type="submit" value="View Report" />
</form>
controller:
[HttpPost]
public ActionResult myAction(string valueINeed)
{
//....
}
You can trigger Lambda functions directly from other Lambda functions directly in an asynchronous manner.
https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations
If you are only looking for images and multiple selection.
Look @ once https://stackoverflow.com/a/15029515/1136023
It's helpful for future.I personally feel great by using MultipleImagePick.
You almost never have to write your own loops in C++. Here, you can use std::find.
const int toFind = 42;
int* found = std::find (myArray, std::end (myArray), toFind);
if (found != std::end (myArray))
{
std::cout << "Found.\n"
}
else
{
std::cout << "Not found.\n";
}
std::end
requires C++11. Without it, you can find the number of elements in the array with:
const size_t numElements = sizeof (myArray) / sizeof (myArray[0]);
...and the end with:
int* end = myArray + numElements;
Upload files using AJAX in ASP.Net MVC
Things have changed since HTML5
JavaScript
document.getElementById('uploader').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/Upload');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
return false;
}
Controller
public JsonResult Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i]; //Uploaded file
//Use the following properties to get file's name, size and MIMEType
int fileSize = file.ContentLength;
string fileName = file.FileName;
string mimeType = file.ContentType;
System.IO.Stream fileContent = file.InputStream;
//To save file, use SaveAs method
file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root
}
return Json("Uploaded " + Request.Files.Count + " files");
}
EDIT : The HTML
<form id="uploader">
<input id="fileInput" type="file" multiple>
<input type="submit" value="Upload file" />
</form>
From Excel Macro Security - www.excelfunctions.net:
Macro Security in Excel 2007, 2010 & 2013:
.....
The different Excel file types provided by the latest versions of Excel make it clear when workbook contains macros, so this in itself is a useful security measure. However, Excel also has optional macro security settings, which are controlled via the options menu. These are :
'Disable all macros without notification'
This setting does not allow any macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.
'Disable all macros with notification'
This setting prevents macros from running. However, if there are macros in a workbook, a pop-up is displayed, to warn you that the macros exist and have been disabled.
'Disable all macros except digitally signed macros'
This setting only allow macros from trusted sources to run. All other macros do not run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.
'Enable all macros'
This setting allows all macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros and may not be aware of macros running while you have the file open.
If you trust the macros and are ok with enabling them, select this option:
'Enable all macros'
and this dialog box should not show up for macros.
As for the dialog for saving, after noting that this was running on Excel for Mac 2011, I came across the following question on SO, StackOverflow - Suppress dialog when using VBA to save a macro containing Excel file (.xlsm) as a non macro containing file (.xlsx). From it, removing the dialog does not seem to be possible, except for possibly by some Keyboard Input simulation. I would post another question to inquire about that. Sorry I could only get you halfway. The other option would be to use a Windows computer with Microsoft Excel, though I'm not sure if that is a option for you in this case.
Here is a way to transform a date string with a time of day to a date object. For example to convert "20/10/2020 18:11:25" ("DD/MM/YYYY HH:MI:SS" format) to a date object
function newUYDate(pDate) {
let dd = pDate.split("/")[0].padStart(2, "0");
let mm = pDate.split("/")[1].padStart(2, "0");
let yyyy = pDate.split("/")[2].split(" ")[0];
let hh = pDate.split("/")[2].split(" ")[1].split(":")[0].padStart(2, "0");
let mi = pDate.split("/")[2].split(" ")[1].split(":")[1].padStart(2, "0");
let secs = pDate.split("/")[2].split(" ")[1].split(":")[2].padStart(2, "0");
mm = (parseInt(mm) - 1).toString(); // January is 0
return new Date(yyyy, mm, dd, hh, mi, secs);
}
An important note is that using vendor SQL queries to retrieve the last inserted ID are safe to use without fearing about concurrent connections.
I always thought that you had to create a transaction in order to INSERT a line and then SELECT the last inserted ID in order to avoid retrieving an ID inserted by another client.
But these vendor specific queries always retrieve the last inserted ID for the current connection to the database. It means that the last inserted ID cannot be affected by other client insertions as long as they use their own database connection.
I've compared performance (space and time) for a number of ways to store numpy arrays. Few of them support multiple arrays per file, but perhaps it's useful anyway.
Npy and binary files are both really fast and small for dense data. If the data is sparse or very structured, you might want to use npz with compression, which'll save a lot of space but cost some load time.
If portability is an issue, binary is better than npy. If human readability is important, then you'll have to sacrifice a lot of performance, but it can be achieved fairly well using csv (which is also very portable of course).
More details and the code are available at the github repo.
Now, unless you're trying to write C++ code using Python syntax, what would you need overloading for?
I think it's exactly opposite. Overloading is only necessary to make strongly-typed languages act more like Python. In Python you have keyword argument, and you have *args
and **kwargs
.
See for example: What is a clean, Pythonic way to have multiple constructors in Python?
set TEXT_T="myfile.txt"
set /a c=1
FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
set /a c+=1
set OUTPUT_FILE_NAME=output_%c%.txt
echo Output file is %OUTPUT_FILE_NAME%
echo %%i, %c%
)
result = spark.createDataFrame([('SpeciesId','int'), ('SpeciesName','string')],["col_name", "data_type"]);
for f in result.collect():
print (f.col_name)
There is a c++ class called _bstr_t
. It has useful methods and a collection of overloaded operators.
For example, you can easily assign from a const wchar_t *
or a const char *
just doing _bstr_t bstr = L"My string";
Then you can convert it back doing const wchar_t * s = bstr.operator const wchar_t *();
. You can even convert it back to a regular char const char * c = bstr.operator char *();
You can then just use the const wchar_t *
or the const char *
to initialize a new std::wstring
oe std::string
.
select count(myCol)
from mytable
group by myCol
;
will group the 3 possible states of bool (false, true, 0) in three rows especially handy when grouping together with another column like day
One reason: the literal 0
has a bad tendency to acquire the type int
, e.g. in perfect argument forwarding or more in general as argument with templated type.
Another reason: readability and clarity of code.
I've been working on this problem for my own site and feel like I've come up with a pretty good solution
1) Assign time zones to all states with only one timezone (most states)
and then either
2a) use the js solution (Javascript/PHP and timezones) for the remaining states
or
2b) use a database like the one linked above by @Doug.
This way, you can find tz cheaply (and highly accurately!) for the majority of your users and then use one of the other, more expensive methods to get it for the rest of the states.
Not super elegant, but seemed better to me than using js or a database for each and every user.
In the command line type service apache2 status
then hit enter. The result should say:
Apache2 is running (pid xxxx)
Direct Mail is an OS X desktop app that can show you previews of what your email will look like in a variety of email clients:
http://directmailmac.com/mac-email-design/
Full Disclosure: I work for the developers of Direct Mail
according me, it is not possible
solution:
import .sql file on mysql server
after
import mysql.connector
import pandas as pd
and then you use .sql file by convert to dataframe
Add an observer for the contentSize property on the table view, and adjust the frame size accordingly
[your_tableview addObserver:self forKeyPath:@"contentSize" options:0 context:NULL];
then in the callback:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
CGRect frame = your_tableview.frame;
frame.size = your_tableview.contentSize;
your_tableview.frame = frame;
}
Hope this will help you.
There's no general way to tell if a file is encoded with a specific encoding. Remember that an encoding is nothing more but an "agreement" how the bits in a file should be mapped to characters.
If you don't know which of your files are actually already encoded in UTF-8 and which ones are encoded in windows-1252, you will have to inspect all files and find out yourself. In the worst case that could mean that you have to open every single one of them with either of the two encodings and see whether they "look" correct -- i.e., all characters are displayed correctly. Of course, you may use tool support in order to do that, for instance, if you know for sure that certain characters are contained in the files that have a different mapping in windows-1252 vs. UTF-8, you could grep for them after running the files through 'iconv' as mentioned by Seva Akekseyev.
Another lucky case for you would be, if you know that the files actually contain only characters that are encoded identically in both UTF-8 and windows-1252. In that case, of course, you're done already.
$ npm uninstall -g angular-cli
$ npm cache clean
$ npm install -g angular-cli
After checking the above answers, I came up with this and it worked perfectly without having to add an extra attribute to your markup
angular.module('app').directive('datepickerPopup', function(dateFilter) {
return {
restrict: 'EAC',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$parsers.push(function(viewValue) {
return dateFilter(viewValue, 'yyyy-MM-dd');
});
}
}
});
this, work for me :
with open('file.json', 'a') as outfile:
outfile.write(json.dumps(data))
outfile.write(",")
outfile.close()
I highly recommend the book "Pro Git" by Scott Chacon. Take time and really read it, while exploring an actual git repo as you do.
HEAD: the current commit your repo is on. Most of the time HEAD
points to the latest commit in your current branch, but that doesn't have to be the case. HEAD
really just means "what is my repo currently pointing at".
In the event that the commit HEAD
refers to is not the tip of any branch, this is called a "detached head".
master: the name of the default branch that git creates for you when first creating a repo. In most cases, "master" means "the main branch". Most shops have everyone pushing to master, and master is considered the definitive view of the repo. But it's also common for release branches to be made off of master for releasing. Your local repo has its own master branch, that almost always follows the master of a remote repo.
origin: the default name that git gives to your main remote repo. Your box has its own repo, and you most likely push out to some remote repo that you and all your coworkers push to. That remote repo is almost always called origin, but it doesn't have to be.
HEAD
is an official notion in git. HEAD
always has a well-defined meaning. master
and origin
are common names usually used in git, but they don't have to be.
This warning also could be raised due to
new HashMap() or new ArrayList() that is generic type has to be specific otherwise the compiler will generate warning.
Please make sure that if you code contains the following you have to change accordingly
new HashMap() => Map map = new HashMap() new HashMap() => Map map = new HashMap<>()
new ArrayList() => List map = new ArrayList() new ArrayList() => List map = new ArrayList<>()
For me on Eclipse Neon I followed Trismegistos answer here above , YET I also added an additional step:
Hit apply and OK.
Cheers,
Guy.
refresh the datagridview and refresh the datatable
dataGridView1.Refresh();
datatable.Clear();
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php
Simplify the accepted answer
Simplified example:
#include <iostream>
#include <iomanip>
int main()
{
double d = 122.345;
std::cout << std::fixed << std::setprecision(2) << d;
}
And you will get output
122.34
Reference:
If for some reason you really want to avoid creating your own Tuple class, or using on built into .NET 4.0, there is one other approach possible; you can combine the three key values together into a single value.
For example, if the three values are integer types together not taking more than 64 bits, you could combine them into a ulong
.
Worst-case you can always use a string, as long as you make sure the three components in it are delimited with some character or sequence that does not occur inside the components of the key, for example, with three numbers you could try:
string.Format("{0}#{1}#{2}", key1, key2, key3)
There is obviously some composition overhead in this approach, but depending on what you are using it for this may be trivial enough not to care about it.
if you know the file name, but don't know the file extention you can use this function:
public function showImage($name)
{
$types = [
'gif'=> 'image/gif',
'png'=> 'image/png',
'jpeg'=> 'image/jpeg',
'jpg'=> 'image/jpeg',
];
$root_path = '/var/www/my_app'; //use your framework to get this properly ..
foreach($types as $type=>$meta){
if(file_exists($root_path .'/uploads/'.$name .'.'. $type)){
header('Content-type: ' . $meta);
readfile($root_path .'/uploads/'.$name .'.'. $type);
return;
}
}
}
Note: the correct content-type for JPG files is image/jpeg
.
You can use the IGNORE
keyword too, example:
update IGNORE table set primary_field = 'value'...............
The usual method I have seen is X.Y.Z, which generally corresponds to major.minor.patch:
Other variations use build numbers as an additional identifier. So you may have a large number for X.Y.Z.build if you have many revisions that are tested between releases. I use a couple of packages that are identified by year/month or year/release. Thus, a release in the month of September of 2010 might be 2010.9 or 2010.3 for the 3rd release of this year.
There are many variants to versioning. It all boils down to personal preference.
For the "1.3v1.1", that may be two different internal products, something that would be a shared library / codebase that is rev'd differently from the main product; that may indicate version 1.3 for the main product, and version 1.1 of the internal library / package.
Your quotes are in the wrong spot. Here's a simple example:
<div style={{backgroundColor: "#FF0000"}}>red</div>
I solved this in an elegant way with RxAndroid. Receive an observer in the constructor of the DialogFragment and suscribe to observable and push the value when the callback being called. Then, in your Fragment create an inner class of the Observer, create an instance and pass it in the constructor of the DialogFragment. I used WeakReference in the observer to avoid memory leaks. Here is the code:
BaseDialogFragment.java
import java.lang.ref.WeakReference;
import io.reactivex.Observer;
public class BaseDialogFragment<O> extends DialogFragment {
protected WeakReference<Observer<O>> observerRef;
protected BaseDialogFragment(Observer<O> observer) {
this.observerRef = new WeakReference<>(observer);
}
protected Observer<O> getObserver() {
return observerRef.get();
}
}
DatePickerFragment.java
public class DatePickerFragment extends BaseDialogFragment<Integer>
implements DatePickerDialog.OnDateSetListener {
public DatePickerFragment(Observer<Integer> observer) {
super(observer);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
if (getObserver() != null) {
Observable.just(month).subscribe(getObserver());
}
}
}
MyFragment.java
//Show the dialog fragment when the button is clicked
@OnClick(R.id.btn_date)
void onDateClick() {
DialogFragment newFragment = new DatePickerFragment(new OnDateSelectedObserver());
newFragment.show(getFragmentManager(), "datePicker");
}
//Observer inner class
private class OnDateSelectedObserver implements Observer<Integer> {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer integer) {
//Here you invoke the logic
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
}
You can see the source code here: https://github.com/andresuarezz26/carpoolingapp
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java" The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input. Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
I also highly recommend using
int integer = 42;
String string = integer + "";
Simple and effective.
To count the number of values larger than x in any numpy array you can use:
n = len(matrix[matrix > x])
The boolean indexing returns an array that contains only the elements where the condition (matrix > x) is met. Then len() counts these values.
Um...
with open(os.path.join(src_dir, f)) as fin:
for line in fin:
Also, you never output to a new file.
Use this
<input type="checkbox" onclick="onClickHandler()" id="box" />
<script>
function onClickHandler(){
var chk=document.getElementById("box").value;
//use this value
}
</script>
I use SourceTree git client, and I see that their initial commit/push command is:
git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master
background-image: url(/images/poster.png);
background-position: center;
background-position-y: 50px;
background-repeat: no-repeat;
In a SSL handshake the purpose of trustStore is to verify credentials and the purpose of keyStore is to provide credential.
keyStore
keyStore in Java stores private key and certificates corresponding to their public keys and require if you are SSL Server or SSL requires client authentication.
TrustStore
TrustStore stores certificates from third party, your Java application communicate or certificates signed by CA(certificate authorities like Verisign, Thawte, Geotrust or GoDaddy) which can be used to identify third party.
TrustManager
TrustManager determines whether remote connection should be trusted or not i.e. whether remote party is who it claims to and KeyManager decides which authentication credentials should be sent to the remote host for authentication during SSL handshake.
If you are an SSL Server you will use private key during key exchange algorithm and send certificates corresponding to your public keys to client, this certificate is acquired from keyStore. On SSL client side, if its written in Java, it will use certificates stored in trustStore to verify identity of Server. SSL certificates are most commonly comes as .cer file which is added into keyStore or trustStore by using any key management utility e.g. keytool.
Source: http://javarevisited.blogspot.ch
An Alternative to using an API is to use HTML 5 location Navigator to query the browser about the User location. I was looking for a similar approach as in the subject question but I found that HTML 5 Navigator works better and cheaper for my situation. Please consider that your scinario might be different. To get the User position using Html5 is very easy:
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else
{
console.log("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
console.log("Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude);
}
Try it yourself on W3Schools Geolocation Tutorial
Follow these steps to create CSR (Code Signing Identity):
On your Mac, go to the folder 'Applications' ? 'Utilities' and open 'Keychain Access.'
Go to 'Keychain Access' ? Certificate Assistant ? Request a Certificate from a Certificate Authority. ?
Fill out the information in the Certificate Information window as specified below and click "Continue."
• In the User Email Address field, enter the email address to identify with this certificate
• In the Common Name field, enter your name
• In the Request group, click the "Saved to disk" option
?
Save the file to your hard drive.
Use this CSR (.certSigningRequest) file to create project/application certificates and profiles, in Apple developer account.
This works for me. Got solution from MYSQL webpage
In MySQL run below queries:
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'New_Password';
This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video controls >
<source src="sample.mp4" type="video/mp4">
<track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">
</video>
</body>
</html>
the video and subtitle files are stored in the same folder as default.htm
I have the very latest version of Chrome (just updated this morning)
When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!
(note that if I input localhost.. to IE11 the video plays!!!!
In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.
This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4
There are two ways to interpret the input data; either -128 is the lowest value, and 127 is the highest (i.e. true signed data), or 0 is the lowest value, 127 is somewhere in the middle, and the next "higher" number is -128, with -1 being the "highest" value (that is, the most significant bit already got misinterpreted as a sign bit in a two's complement notation.
Assuming you mean the latter, the formally correct way is
signed char in = ...
unsigned char out = (in < 0)?(in + 256):in;
which at least gcc properly recognizes as a no-op.
Now you can also use Talentsoft.Moq.SetupAsync package https://github.com/TalentSoft/Moq.SetupAsync
Which on the base on the answers found here and ideas proposed to Moq but still not yet implemented here: https://github.com/moq/moq4/issues/384, greatly simplify setup of async methods
Few examples found in previous responses done with SetupAsync extension:
mock.SetupAsync(arg=>arg.DoSomethingAsync());
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Callback(() => { <my code here> });
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Throws(new InvalidOperationException());
You can use all()
method instead of toArray()
method (see more: laravel documentation):
test::where('id' ,'>' ,0)->pluck('id')->all(); //returns array
If you need a string
, you can use without toArray()
attachment:
test::where('id' ,'>' ,0)->pluck('id'); //returns string
i prefer the most readable and extensible way using jquery.
Also, you can build fully dynamic content on the fly.
Since jquery version 1.4 you can pass attributes to elements which is,
imho, a killer feature.
Also the code can be kept cleaner.
$(function(){
var tablerows = new Array();
$.each(['result1', 'result2', 'result3'], function( index, value ) {
tablerows.push('<tr><td>' + value + '</td></tr>');
});
var table = $('<table/>', {
html: tablerows
});
var div = $('<div/>', {
id: 'here_table',
html: table
});
$('body').append(div);
});
Addon: passing more than one "html" tag you've to use array notation like: e.g.
var div = $('<div/>', {
id: 'here_table',
html: [ div1, div2, table ]
});
best Rgds.
Franz
I guess you mean this:
class Value:
def __init__(self, v=None):
self.v = v
v1 = Value(1)
v2 = Value(2)
d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1
d['b'].v == 2 # True
d['a']
and d['b']
to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or a dict
, list
, set
).d['a']
, d['b']
changes at same time because they both point to same object.As in:
In [3]: os.path.exists('/d/temp')
Out[3]: True
Probably toss in a os.path.isdir(...)
to be sure.
my solution is:
That all, hope it works for you
It's a consequence of the size of the exponent part of the type, as in IEEE 754 for example. You can examine the sizes with FLT_MAX, FLT_MIN, DBL_MAX, DBL_MIN in float.h.
# Here '1stDB' is the database name
spring.datasource.url=jdbc:mysql://localhost/A
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Here '2ndDB' is the database name
spring.second-datasourcee.url=jdbc:mysql://localhost/B
spring.second-datasource.username=root
spring.second-datasource.password=root
spring.second-datasource.driver-class-name=com.mysql.jdbc.Driver
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.second-datasource")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
In your RecyclerView adapter, you should have an ArrayList and also one method addItemsToList(items)
to add list items to the ArrayList. Then you can add list items by call adapter.addItemsToList(items)
dynamically. After all your list items added to the ArrayList then you can call adapter.notifyDataSetChanged()
to display your list.
You can use the notifyDataSetChanged
in the adapter for the RecyclerView
$ rails server -b $IP -p $PORT - that solved the same problem for me
If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr
function, like this
>>> chr(65)
'A'
similarly if you have 97,
>>> chr(97)
'a'
EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord
and the result has to be converted using unichr
instead of chr
.
>>> print unichr(ord(u'\u0B85'))
?
>>> print unichr(1 + ord(u'\u0B85'))
?
NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf
data = File.read("/path/to/file")
I had the same error recently, and all the solutions I've found did not work.
After some digging, I found that setting app.use(express.bodyParser({limit: '50mb'}));
did set the limit correctly.
When adding a console.log('Limit file size: '+limit);
in node_modules/express/node_modules/connect/lib/middleware/json.js:46
and restarting node, I get this output in the console:
Limit file size: 1048576
connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0
Limit file size: 52428800
Express server listening on port 3002
We can see that at first, when loading the connect
module, the limit is set to 1mb (1048576 bytes). Then when I set the limit, the console.log
is called again and this time the limit is 52428800 (50mb). However, I still get a 413 Request entity too large
.
Then I added console.log('Limit file size: '+limit);
in node_modules/express/node_modules/connect/node_modules/raw-body/index.js:10
and saw another line in the console when calling the route with a big request (before the error output) :
Limit file size: 1048576
This means that somehow, somewhere, connect
resets the limit parameter and ignores what we specified. I tried specifying the bodyParser
parameters in the route definition individually, but no luck either.
While I did not find any proper way to set it permanently, you can "patch" it in the module directly. If you are using Express 3.4.4, add this at line 46 of node_modules/express/node_modules/connect/lib/middleware/json.js
:
limit = 52428800; // for 50mb, this corresponds to the size in bytes
The line number might differ if you don't run the same version of Express. Please note that this is bad practice and it will be overwritten if you update your module.
So this temporary solution works for now, but as soon as a solution is found (or the module fixed, in case it's a module problem) you should update your code accordingly.
I have opened an issue on their GitHub about this problem.
[edit - found the solution]
After some research and testing, I found that when debugging, I added app.use(express.bodyParser({limit: '50mb'}));
, but after app.use(express.json());
. Express would then set the global limit to 1mb because the first parser he encountered when running the script was express.json()
. Moving bodyParser
above it did the trick.
That said, the bodyParser()
method will be deprecated in Connect 3.0 and should not be used. Instead, you should declare your parsers explicitly, like so :
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));
In case you need multipart (for file uploads) see this post.
[second edit]
Note that in Express 4, instead of express.json()
and express.urlencoded()
, you must require the body-parser module and use its json()
and urlencoded()
methods, like so:
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
If the extended
option is not explicitly defined for bodyParser.urlencoded()
, it will throw a warning (body-parser deprecated undefined extended: provide extended option
). This is because this option will be required in the next version and will not be optional anymore. For more info on the extended
option, you can refer to the readme of body-parser
.
[third edit]
It seems that in Express v4.16.0 onwards, we can go back to the initial way of doing this (thanks to @GBMan for the tip):
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));
Specific to Firefox, which does not go through Internet Options like IE, Chrome, and Edge do, you can use about:config
to modify preferences, find the preference network.proxy.no_proxies_on
and remove localhost
from it.
This was the default setting for Firefox Developer Edition 66.0b2 and worked with Fiddler 5.0.20182.28034.
(Other listed solutions do work, this solution allows you to not change the host you are navigating to.)
My solution:
jQuery('.foo').on('click',function(event){
if ( !jQuery(event.target).is('.foo *') ) {
// code goes here
}
});
SELECT A.identifier
, A.name
, TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL)) as MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A, table_b B
WHERE .identifier = B.identifier
HAVING MONTH_NO > UPD_DATE
Installing webpack with -g option installs webpack in a folder in
C:\Users\<.profileusername.>\AppData\Roaming\npm\node_modules
same with webpack-cli and webpack-dev-server
Outside the global node_modules a link is created for webpack to be run from commandline
C:\Users\<.profileusername.>\AppData\Roaming\npm
to make this work locally, I did the following
Problem with this approach is you'd have to maintain links for each project you have. Theres no other way since you are using the command line editor to run webpack command when installing with a -g option.
So if you had proj1, proj2 and proj3 all with their local node_modules and local webpack installed( not using -g when installing), then you'd have to create non-generic link names instead of just webpack.
example here would be to create webpack_proj1.cmd, webpack_proj2.cmd and webpack_proj3.cmd and in each cmd follow point 2 and 3 above
PS: dont forget to update your package.json with these changes or else you'll get errors as it won't find webpack command
Based on Brian Burns edited answer, I created a single class that is easier to call:
class Logger(object):
"""
Class to log output of the command line to a log file
Usage:
log = Logger('logfile.log')
print("inside file")
log.stop()
print("outside file")
log.start()
print("inside again")
log.stop()
"""
def __init__(self, filename):
self.filename = filename
class Transcript:
def __init__(self, filename):
self.terminal = sys.stdout
self.log = open(filename, "a")
def __getattr__(self, attr):
return getattr(self.terminal, attr)
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
def start(self):
sys.stdout = self.Transcript(self.filename)
def stop(self):
sys.stdout.log.close()
sys.stdout = sys.stdout.terminal
Button Code
<button id="submit" name="submit" type="submit" value="Submit">Submit</button>
Disable Button
if(When You Disable the button this Case){
$(':input[type="submit"]').prop('disabled', true);
}else{
$(':input[type="submit"]').prop('disabled', false);
}
Note: You Case may Be Multiple this time more condition may need
http://example.com/ may resolve to a different VirtualHost than https://example.com/ (which, as the Host header is not sent, responds to the default for that IP), so the two are treated as separate domains and thus subject to crossdomain JS restrictions.
JSON callbacks may let you avoid this.
By default, Tomcat container doesn’t contain any jstl library. To fix it, declares jstl.jar in your Maven pom.xml file if you are working in Maven project or add it to your application's classpath
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
is there a special guideline that should be followed
There is no "standard" way to do batch files, because the vast majority of their authors and maintainers either don't understand programming concepts, or they think they don't apply to batch files.
But I am a programmer. I'm used to compiling, and I'm used to debuggers. Batch files aren't compiled, and you can't run them through a debugger, so they make me nervous. I suggest you be extra strict on what you write, so you can be very sure it will do what you think it does.
There are some coding standards that say: If you write an if
statement, you must use braces, even if you don't have an else
clause. This saves you from subtle, hard-to-debug problems, and is unambiguously readable. I see no reason you couldn't apply this reasoning to batch files.
Let's take a look at your code.
IF EXIST somefile.txt IF EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt
And the IF
syntax, from the command, HELP IF
:
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXISTS filename command
...
IF EXIST filename (
command
) ELSE (
other command
)
So you are chaining IF
's as commands.
If you use the common coding-standard rule I mentioned above, you would always want to use parens. Here is how you would do so for your example code:
IF EXIST "somefile.txt" (
IF EXIST "someotherfile.txt" (
SET var="somefile.txt,someotherfile.txt"
)
)
Make sure you cleanly format, and do some form of indentation. You do it in code, and you should do it in your batch scripts.
Also, you should also get in the habit of always quoting your file names, and getting the quoting right. There is some verbiage under HELP FOR
and HELP SET
that will help you with removing extra quotes when re-quoting strings.
Edit
From your comments, and re-reading your original question, it seems like you want to build a comma separated list of files that exist. For this case, you could simply use a bunch of if
/else
statements, but that would result in a bunch of duplicated logic, and would not be at all clean if you had more than two files.
A better way is to write a sub-routine that checks for a single file's existence, and appends to a variable if the file specified exists. Then just call that subroutine for each file you want to check for:
@ECHO OFF
SETLOCAL
REM Todo: Set global script variables here
CALL :MainScript
GOTO :EOF
REM MainScript()
:MainScript
SETLOCAL
CALL :AddIfExists "somefile.txt" "%files%" "files"
CALL :AddIfExists "someotherfile.txt" "%files%" "files"
ECHO.Files: %files%
ENDLOCAL
GOTO :EOF
REM AddIfExists(filename, existingFilenames, returnVariableName)
:AddIfExists
SETLOCAL
IF EXIST "%~1" (
SET "result=%~1"
) ELSE (
SET "result="
)
(
REM Cleanup, and return result - concatenate if necessary
ENDLOCAL
IF "%~2"=="" (
SET "%~3=%result%"
) ELSE (
SET "%~3=%~2,%result%"
)
)
GOTO :EOF
You can only break
a block scope if you label it. For example:
myBlock: {
var a = 0;
break myBlock;
a = 1; // this is never run
};
a === 0;
You cannot break a block scope from within a function in the scope. This means you can't do stuff like:
foo: { // this doesn't work
(function() {
break foo;
}());
}
You can do something similar though with functions:
function myFunction() {myFunction:{
// you can now use break myFunction; instead of return;
}}
Yes, it's possible with a bit of tweak. Unfortunately, you still have to have VS 2010 installed.
First, install XNA Game Studio 4.0. The easiest way is to install the Windows Phone SDK 7.1 which contains everything required.
Copy the XNA Game Extension from VS 10 to VS 11 by opening a command prompt 'as administrator' and executing the following (may vary if not x64 computer with defaults paths) :
xcopy /e "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0" "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0"
Run notepad as administrator then open extension.vsixmanifest
in the destination directory just created.
Upgrade the Supported product version to match the new version (or duplicate the whole VisualStudio
element and change the Version
attribute, as @brainslugs83 said in comments):
<SupportedProducts>
<VisualStudio Version="11.0">
<Edition>VSTS</Edition>
<Edition>VSTD</Edition>
<Edition>Pro</Edition>
<Edition>VCSExpress</Edition>
<Edition>VPDExpress</Edition>
</VisualStudio>
</SupportedProducts>
Don't forget to clear/delete your cache in %localappdata%\Microsoft\VisualStudio\12.0\Extensions.
You may have to run the command to tells Visual Studio that new extensions are available. If you see an 'access denied' message, try launching the console as an administrator.
"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe" /setup
This has been tested for Windows Games, but not WP7 or Xbox games.
[Edit] According Jowsty, this works also for XBox 360 Games.
[Edit for Visual Studio 2013 & Windows 8.1] See here for documentation on installing Windows Phone SDK 7.1 on Windows 8.1. Use VS version number 12.0 in place of 11.0 for all of these steps, and they will still work correctly.
Possible solution without using substr()
#include<iostream>
#include<string>
using namespace std;
int main() {
string c="12345";
int p=0;
for(int i=0;i<c.length();i++) {
cout<<c[i];
p++;
if (p % 2 == 0 && i != c.length()-1) {
cout<<" "<<c[i];
p++;
}
}
}
I am using this function:
public static int[][] copy(final int[][] array) {
if (array != null) {
final int[][] copy = new int[array.length][];
for (int i = 0; i < array.length; i++) {
final int[] row = array[i];
copy[i] = new int[row.length];
System.arraycopy(row, 0, copy[i], 0, row.length);
}
return copy;
}
return null;
}
The big advantage of this approach is that it can also copy arrays that don't have the same row count such as:
final int[][] array = new int[][] { { 5, 3, 6 }, { 1 } };
From ScottGu's blog:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
Also see this.
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.
Wikipedia
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
Out-File
defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii
to change this behavior. In your case
Out-File -Encoding Ascii -append textfile.txt.
Add-Content
uses Ascii and also appends by default.
"This is a test" | Add-Content textfile.txt.
As for the lack of newline: You did not send a newline so it will not write one to file.
A "float" in most environments is a binary floating-point type. It can accurately store base-2 values (to a certain point), but cannot accurately store many base-10 (decimal) values. Floats are most appropriate for scientific calculations. They're not appropriate for most business-oriented math, and inappropriate use of floats will bite you. Many decimal values can't be exactly represented in base-2. 0.1
can't, for instance, and so you see strange results like 1.0 - 0.1 = 0.8999999
.
Decimals store base-10 numbers. Decimal is an good type for most business math (but any built-in "money" type is more appropriate for financial calculations), where the range of values exceeds that provided by integer types, and fractional values are needed. Decimals, as the name implies, are designed for base-10 numbers - they can accurately store decimal values (again, to a certain point).
I worked on a core team for the MSDN website. Now, I use c# razor for ecommerce sites with my programming team and we focus heavy on jQuery front end with back end c# razor pages and LINQ-Entity memory database so the pages are 1-2 millisecond response times even on nested for loops with queries and no page caching. We don't use MVC, just plain ASP.NET with razor pages being mapped with URL Rewrite module for IIS 7, no ASPX pages or ViewState or server-side event programming at all. It doesn't have the extra (unnecessary) layers MVC puts in code constructs for the regex challenged. Less is more for us. Its all lean and mean but I give props to MVC for its testability but that's all.
Razor pages have no event life cycle like ASPX pages. Its just rendering as one requested page. C# is such a great language and Razor gets out of its way nicely to let it do its job. The anonymous typing with generics and linq make life so easy with c# and razor pages. Using Razor pages will help you think and code lighter.
One of the drawback of Razor and MVC is there is no ViewState-like persistence. I needed to implement a solution for that so I ended up writing a jQuery plugin for that here -> http://www.jasonsebring.com/dumbFormState which is an HTML 5 offline storage supported plugin for form state that is working in all major browsers now. It is just for form state currently but you can use window.sessionStorage or window.localStorage very simply to store any kind of state across postbacks or even page requests, I just bothered to make it autosave and namespace it based on URL and form index so you don't have to think about it.
Yes, you can delete your commit without deleting the changes:
git reset @~
Try this:
$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);
http://api.cakephp.org/2.3/class-Model.html#_getDataSource
You will have to do this for each datasource if you have more than one though.
The m000493
method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd
:
string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));
string result = m000493(p0, "_p0lizei.");
// result == "gaia^unplugged^Ta..."
with return m0001cd(builder3.ToString());
changed to return builder3.ToString();
.
I also met the same problem recently, when I use waterline in express project for complex queries ,use the SQL statement to query.
this is my solution: first transform the return value(RowDataPacket object) into string, and then convert this string into the json object.
The following is code :
//select all user (??????)
find: function(req, res, next){
console.log("i am in user find list");
var sql="select * from tb_user";
req.models.tb_user.query(sql,function(err, results) {
console.log('>> results: ', results );
var string=JSON.stringify(results);
console.log('>> string: ', string );
var json = JSON.parse(string);
console.log('>> json: ', json);
console.log('>> user.name: ', json[0].name);
req.list = json;
next();
});
}
The following is console:
>> results: [ RowDataPacket {
user_id: '2fc48bd0-a62c-11e5-9a32-a31e4e4cd6a5',
name: 'wuwanyu',
psw: '123',
school: 'Northeastern university',
major: 'Communication engineering',
points: '10',
datems: '1450514441486',
createdAt: Sat Dec 19 2015 16:42:31 GMT+0800 (??????),
updatedAt: Sat Dec 19 2015 16:42:31 GMT+0800 (??????),
ID: 3,
phone: 2147483647 } ]
>> string: [{"user_id":"2fc48bd0-a62c-11e5-9a32-a31e4e4cd6a5","name":"wuwanyu","psw":"123","school":"Northeastern university","major":"Communication engineering","points":"10","datems":"1450514
441486","createdAt":"2015-12-19T08:42:31.000Z","updatedAt":"2015-12-19T08:42:31.000Z","ID":3,"phone":2147483647}]
>> json: [ { user_id: '2fc48bd0-a62c-11e5-9a32-a31e4e4cd6a5',
name: 'wuwanyu',
psw: '123',
school: 'Northeastern university',
major: 'Communication engineering',
points: '10',
datems: '1450514441486',
createdAt: '2015-12-19T08:42:31.000Z',
updatedAt: '2015-12-19T08:42:31.000Z',
ID: 3,
phone: 2147483647 } ]
>> user.name: wuwanyu
I faced this exception for a long time and was not able to pinpoint the problem. The exception says line 1 column 9. The mistake I did is to get the first line of the file which flume is processing.
Apache flume process the content of the file in patches. So, when flume throws this exception and says line 1, it means the first line in the current patch.
If your flume agent is configured to use batch size = 100, and (for example) the file contains 400 lines, this means the exception is thrown in one of the following lines 1, 101, 201,301.
How to discover the line which causes the problem?
You have three ways to do that.
1- pull the source code and run the agent in debug mode. If you are an average developer like me and do not know how to make this, check the other two options.
2- Try to split the file based on the batch size and run the flume agent again. If you split the file into 4 files, and the invalid json exists between lines 301 and 400, the flume agent will process the first 3 files and stop at the fourth file. Take the fourth file and again split it into more smaller files. continue the process until you reach a file with only one line and flume fails while processing it.
3- Reduce the batch size of the flume agent to only one and compare the number of processed events in the output of the sink you are using. For example, in my case I am using Solr sink. The file contains 400 lines. The flume agent is configured with batch size=100. When I run the flume agent, it fails at some point and throw that exception. At this point check how many documents are ingested in Solr. If the invalid json exists at line 346, the number of documents indexed into Solr will be 345, so the next line is the line which causes the problem.
In my case I followed the third option and fortunately I pinpoint the line which causes the problem.
This is a long answer but it actually does not solve the exception. How I overcome this exception?
I have no idea why Jackson library complain while parsing a json string contains escaped characters \n \r \t
. I think (but I am not sure) the Jackson parser is by default escaping these characters which cases the json string to be split into two lines (in case of \n
) and then it deals each line as a separate json string.
In my case we used a customized interceptor to remove these characters before being processed by the flume agent. This is the way we solved this problem.
Building on the answer from @dcarrith ...
Instead of editing the config files, I created an alias in the location that PHP is looking that connects to the real mysql.sock. (source)
Just run these two commands (no restart needed):
mkdir /var/mysql
ln -s /tmp/mysql.sock /var/mysql/mysql.sock
It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.
Let's say you have something like this in your code:
$str = "test";
echo($str{0});
since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:
$str = "test";
echo($str[0]);
Fixing the code in the question will look something like this:
public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
$records = $this->listRecords($zoneID, $type, $name);
if (isset($records->result[0]->id)) {
return $records->result[0]->id;
}
return false;
}
SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')
If you are using parametrized Stored procedure:
INNER JOIN ON t.PersonName = newTable.PersonName
using a table variable which contains passed in namesto validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.
essentially it will look something like this
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$
Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?
It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.
So do the regular expression and validate the structure but forget about validating against a service.
As of .NET Core 2.0, the constructor Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
now exists.
$("#mainTable").css("width", "200px");
$("#mainTable").css("height", "2000px");
There is an XML value alpha
that takes double values.
Since API 11+
the range is from 0f
to 1f
(inclusive), 0f
being transparent and 1f
being opaque:
android:alpha="0.0"
thats invisible
android:alpha="0.5"
see-through
android:alpha="1.0"
full visible
That's how it works.
Here's a function that will return the content of any meta tag and will memoize the result, avoiding unnecessary querying of the DOM.
var getMetaContent = (function(){
var metas = {};
var metaGetter = function(metaName){
var theMetaContent, wasDOMQueried = true;;
if (metas[metaName]) {
theMetaContent = metas[metaName];
wasDOMQueried = false;
}
else {
Array.prototype.forEach.call(document.getElementsByTagName("meta"), function(el) {
if (el.name === metaName) theMetaContent = el.content;
metas[metaName] = theMetaContent;
});
}
console.log("Q:wasDOMQueried? A:" + wasDOMQueried);
return theMetaContent;
}
return metaGetter;
})();
getMetaContent("description"); /* getMetaContent console.logs the content of the description metatag. If invoked a second time it confirms that the DOM was only queried once */
And here's an extended version that also queries for open graph tags, and uses Array#some:
var getMetaContent = (function(){
var metas = {};
var metaGetter = function(metaName){
wasDOMQueried = true;
if (metas[metaName]) {
wasDOMQueried = false;
}
else {
Array.prototype.some.call(document.getElementsByTagName("meta"), function(el) {
if(el.name === metaName){
metas[metaName] = el.content;
return true;
}
if(el.getAttribute("property") === metaName){
metas[metaName] = el.content;
return true;
}
else{
metas[metaName] = "meta tag not found";
}
});
}
console.info("Q:wasDOMQueried? A:" + wasDOMQueried);
console.info(metas);
return metas[metaName];
}
return metaGetter;
})();
getMetaContent("video"); // "http://video.com/video33353.mp4"
I did this to remove the error:
Mapper.CreateMap<FacebookUser, ProspectModel>();
prospect = Mapper.Map(prospectFromDb, prospect);
I have not looked at the VBulletin source code in some time, but the way they used to do it around 2003 was to embed a call to their server inside the code. IIRC, it was on a really long code line (like 200-300+ chars long) and was broken up over several string concatenations and such.
It did nothing "bad" if you pirated it - the forum still worked 100%. But your server's IP was logged along with other info and they used that to investigate and take legal action.
Your license number was embedded in this call, so they could easily track how many IPs/websites a given licensed copy was running on.
Select the lines you want to reformat (indenting), then hit Alt+Shift+F. Only the selected lines will be reformatted.
Wade73's answer for decimals doesn't quite work. I've modified it to allow only a single decimal point.
declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar)
values
(N'1234')
, (N'000005')
, (N'1,000')
, (N'293.8457')
, (N'x')
, (N'+')
, (N'293.8457.')
, (N'......');
-- This shows that Wade73's answer allows some non-numeric values to slip through.
select * from (
select
MyVar
, case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber
from
@MyTable
) t order by IsNumber;
-- Notice the addition of "and MyVar not like N'%.%.%'".
select * from (
select
MyVar
, case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' then 1 else 0 end as IsNumber
from
@MyTable
) t
order by IsNumber;
Another option is to repeat the rules in two prefix locations using an included file. Since prefix locations are position independent in the configuration, using them can save some confusion as you add other regex locations later on. Avoiding regex locations when you can will help your configuration scale smoothly.
server {
location /first/location/ {
include shared.conf;
}
location /second/location/ {
include shared.conf;
}
}
Here's a sample shared.conf:
default_type text/plain;
return 200 "http_user_agent: $http_user_agent
remote_addr: $remote_addr
remote_port: $remote_port
scheme: $scheme
nginx_version: $nginx_version
";
Here is my solution:
<td>
<a href="/yourURL"></a>
<div class="item-container">
<img class="icon" src="/iconURL" />
<p class="name">
SomeText
</p>
</div>
</td>
(LESS)
td {
padding: 1%;
vertical-align: bottom;
position:relative;
a {
height: 100%;
display: block;
position: absolute;
top:0;
bottom:0;
right:0;
left:0;
}
.item-container {
/*...*/
}
}
Like this you can still benefit from some table cell properties like vertical-align
.(Tested on Chrome)
I think the most efficient way to do this is this is using RemoveAt
:
rows.RemoveAt(rows.Count - 1)
Actually whether there are digits or not is irrelevant. The . (dot) is forbidden if you want to cast to int. Dot can't - logically - be part of Integer definition, so even:
select cast ('7.0' as int)
select cast ('7.' as int)
will fail but both are fine for floats.
I know this question has already been answered, but another option is simply to open the destination and source folders in Finder and then drag and drop them into the terminal. The paths will automatically be copied and properly formatted (thus negating the need to actually figure out proper file names/extensions).
I have to do over-network copies between Mac and Windows machines, sometimes fairly deep down in filetrees, and have found this the most effective way to do so.
So, as an example:
cp -r [drag and drop source folder from finder] [drag and drop destination folder from finder]
My solution is:
#include <iostream>
int fib(int number);
void call_fib(void);
int main()
{
call_fib();
return 0;
}
void call_fib(void)
{
int input;
std::cout<<"enter a number\t";
std::cin>> input;
if (input <0)
{
input=0;
std::cout<<"that is not a valid input\n" ;
call_fib();
}
else
{
std::cout<<"the "<<input <<"th fibonacci number is "<<fib(input);
}
}
int fib(int x)
{
if (x==0){return 0;}
else if (x==2 || x==1)
{
return 1;
}
else if (x>0)
{
return fib(x-1)+fib(x-2);
}
else
return -1;
}
it returns fib(0)=0 and error if negitive
Decorator method using decorator Python library:
import decorator
@decorator
def timing(func, *args, **kwargs):
'''Function timing wrapper
Example of using:
``@timing()``
'''
fn = '%s.%s' % (func.__module__, func.__name__)
timer = Timer()
with timer:
ret = func(*args, **kwargs)
log.info(u'%s - %0.3f sec' % (fn, timer.duration_in_seconds()))
return ret
See post on my Blog:
Try this script to create a temporary table TESTTEST and watch the order of precedence as the triggers are called in this order: 1) INSTEAD OF, 2) FOR, 3) AFTER
All of the logic is placed in INSTEAD OF trigger and I have 2 examples of how you might code some scenarios...
Good luck...
CREATE TABLE TESTTEST
(
ID INT,
Modified0 DATETIME,
Modified1 DATETIME
)
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_0] ON [dbo].TESTTEST
INSTEAD OF INSERT,UPDATE,DELETE
AS
BEGIN
SELECT 'INSTEAD OF'
SELECT 'TT0.0'
SELECT * FROM TESTTEST
SELECT *, 'I' Mode
INTO #work
FROM INSERTED
UPDATE #work SET Mode='U' WHERE ID IN (SELECT ID FROM DELETED)
INSERT INTO #work (ID, Modified0, Modified1, Mode)
SELECT ID, Modified0, Modified1, 'D'
FROM DELETED WHERE ID NOT IN (SELECT ID FROM INSERTED)
--Check Security or any other logic to add and remove from #work before processing
DELETE FROM #work WHERE ID=9 -- because you don't want anyone to edit this id?!?!
DELETE FROM #work WHERE Mode='D' -- because you don't want anyone to delete any records
SELECT 'EV'
SELECT * FROM #work
IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='I'))
BEGIN
SELECT 'I0.0'
INSERT INTO dbo.TESTTEST (ID, Modified0, Modified1)
SELECT ID, Modified0, Modified1
FROM #work
WHERE Mode='I'
SELECT 'Cool stuff would happen here if you had FOR INSERT or AFTER INSERT triggers.'
SELECT 'I0.1'
END
IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='D'))
BEGIN
SELECT 'D0.0'
DELETE FROM TESTTEST WHERE ID IN (SELECT ID FROM #work WHERE Mode='D')
SELECT 'Cool stuff would happen here if you had FOR DELETE or AFTER DELETE triggers.'
SELECT 'D0.1'
END
IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='U'))
BEGIN
SELECT 'U0.0'
UPDATE t SET t.Modified0=e.Modified0, t.Modified1=e.Modified1
FROM dbo.TESTTEST t
INNER JOIN #work e ON e.ID = t.ID
WHERE e.Mode='U'
SELECT 'U0.1'
END
DROP TABLE #work
SELECT 'TT0.1'
SELECT * FROM TESTTEST
END
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_1] ON [dbo].TESTTEST
FOR UPDATE
AS
BEGIN
SELECT 'FOR UPDATE'
SELECT 'TT1.0'
SELECT * FROM TESTTEST
SELECT 'I1'
SELECT * FROM INSERTED
SELECT 'D1'
SELECT * FROM DELETED
SELECT 'TT1.1'
SELECT * FROM TESTTEST
END
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_2] ON [dbo].TESTTEST
AFTER UPDATE
AS
BEGIN
SELECT 'AFTER UPDATE'
SELECT 'TT2.0'
SELECT * FROM TESTTEST
SELECT 'I2'
SELECT * FROM INSERTED
SELECT 'D2'
SELECT * FROM DELETED
SELECT 'TT2.1'
SELECT * FROM TESTTEST
END
GO
SELECT 'Start'
INSERT INTO TESTTEST (ID, Modified0) VALUES (9, GETDATE())-- not going to insert
SELECT 'RESTART'
INSERT INTO TESTTEST (ID, Modified0) VALUES (10, GETDATE())--going to insert
SELECT 'RESTART'
UPDATE TESTTEST SET Modified1=GETDATE() WHERE ID=10-- gointo to update
SELECT 'RESTART'
DELETE FROM TESTTEST WHERE ID=10-- not going to DELETE
SELECT 'FINISHED'
SELECT * FROM TESTTEST
DROP TABLE TESTTEST
Just to add an additional function should you need it. You can include a variable in the named location, for example a date identifier
date <- yyyymmdd
save(city, file=paste0("c:\\myuser\\somelocation\\",date,"_RData.Data")
This was you can always keep a check of when it was run
Try pgrep
. Its output format is much simpler and therefore easier to parse.
It isn't bad practice, but it can make code less readable. One useful refactoring to work around this is to move the loop to a separate method, and then use a return statement instead of a break, for example this (example lifted from @Chris's answer):
String item;
for(int x = 0; x < 10; x++)
{
// Linear search.
if(array[x].equals("Item I am looking for"))
{
//you've found the item. Let's stop.
item = array[x];
break;
}
}
can be refactored (using extract method) to this:
public String searchForItem(String itemIamLookingFor)
{
for(int x = 0; x < 10; x++)
{
if(array[x].equals(itemIamLookingFor))
{
return array[x];
}
}
}
Which when called from the surrounding code can prove to be more readable.
I'm using this on my site (for example here), but I'm using some extra stuff to do lazy loading, meaning extracting the code isn't as straightforward as I would like it to be for putting it in a fiddle.
Also, my templating engine is smarty, but I'm sure you get the idea.
The meat...
Updating the indicators:
<ol class="carousel-indicators">
{assign var='walker' value=0}
{foreach from=$item["imagearray"] key="key" item="value"}
<li data-target="#myCarousel" data-slide-to="{$walker}"{if $walker == 0} class="active"{/if}>
<img src='http://farm{$value["farm"]}.static.flickr.com/{$value["server"]}/{$value["id"]}_{$value["secret"]}_s.jpg'>
</li>
{assign var='walker' value=1 + $walker}
{/foreach}
</ol>
Changing the CSS related to the indicators:
.carousel-indicators {
bottom:-50px;
height: 36px;
overflow-x: hidden;
white-space: nowrap;
}
.carousel-indicators li {
text-indent: 0;
width: 34px !important;
height: 34px !important;
border-radius: 0;
}
.carousel-indicators li img {
width: 32px;
height: 32px;
opacity: 0.5;
}
.carousel-indicators li:hover img, .carousel-indicators li.active img {
opacity: 1;
}
.carousel-indicators .active {
border-color: #337ab7;
}
When the carousel has slid, update the list of thumbnails:
$('#myCarousel').on('slid.bs.carousel', function() {
var widthEstimate = -1 * $(".carousel-indicators li:first").position().left + $(".carousel-indicators li:last").position().left + $(".carousel-indicators li:last").width();
var newIndicatorPosition = $(".carousel-indicators li.active").position().left + $(".carousel-indicators li.active").width() / 2;
var toScroll = newIndicatorPosition + indicatorPosition;
var adjustedScroll = toScroll - ($(".carousel-indicators").width() / 2);
if (adjustedScroll < 0)
adjustedScroll = 0;
if (adjustedScroll > widthEstimate - $(".carousel-indicators").width())
adjustedScroll = widthEstimate - $(".carousel-indicators").width();
$('.carousel-indicators').animate({ scrollLeft: adjustedScroll }, 800);
indicatorPosition = adjustedScroll;
});
And, when your page loads, set the initial scroll position of the thumbnails:
var indicatorPosition = 0;
You need to grant the user or group rights to use the profile. They need to be added to the msdb database and then you will see them available in the mail wizard when you are maintaining security for mail.
Read up the security here: http://msdn.microsoft.com/en-us/library/ms175887.aspx
See a listing of mail procedures here: http://msdn.microsoft.com/en-us/library/ms177580.aspx
Example script for 'TestUser' to use the profile named 'General Admin Mail'.
USE [msdb]
GO
CREATE USER [TestUser] FOR LOGIN [testuser]
GO
USE [msdb]
GO
EXEC sp_addrolemember N'DatabaseMailUserRole', N'TestUser'
GO
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = 'General Admin Mail',
@principal_name = 'TestUser',
@is_default = 1 ;
Use your console:
console.log(object);
Or if you are inspecting html dom elements use console.dir(object). Example:
let element = document.getElementById('alertBoxContainer');
console.dir(element);
Or if you have an array of js objects you could use:
console.table(objectArr);
If you are outputting a lot of console.log(objects) you can also write
console.log({ objectName1 });
console.log({ objectName2 });
This will help you label the objects written to console.
change the
fieldname?: any[];
to this:
fieldname?: any;
Simply add style="line-height:0"
to each cell. This works in IE because it sets the line-height of both existant and non-existant text to about 19px and that forces the cells to expand vertically in most versions of IE. Regardless of whether or not you have text this needs to be done for IE to correctly display rows less than 20px high.
Note: This answer covers several versions of Chrome, scroll to see v52, v48, v46, v43 and v42 each with their updated changes.
If you wish your class to be compatible with the Java Beans specification, so that tools utilizing reflection (e.g. JavaBuilders, JGoodies Binding) can recognize boolean getters, either use getXXXX()
or isXXXX()
as a method name. From the Java Beans spec:
8.3.2 Boolean properties
In addition, for boolean properties, we allow a getter method to match the pattern:
public boolean is
<PropertyName>()
;This “is<PropertyName>” method may be provided instead of a “get<PropertyName>” method, or it may be provided in addition to a “get<PropertyName>” method. In either case, if the “is<PropertyName>” method is present for a boolean property then we will use the “is<PropertyName>” method to read the property value. An example boolean property might be:
public boolean isMarsupial(); public void setMarsupial(boolean m);
None of the above solutions worked for me but I eventually found a solution that did.
My version of this issue was caused by a third-party CSS file that set the 'box-sizing' to a different value. I was able to fix the issue without effecting other elements with the code below:
$table.closest(".dataTables_wrapper").find("*").css("box-sizing","content-box").css("-moz-box-sizing","content-box");
Hope this helps someone!
Application.Current results in an appdomain http://msdn.microsoft.com/en-us/library/system.appdomain_members.aspx
Also this should give you the location of the assembly
AppDomain.CurrentDomain.BaseDirectory
I seem to recall there being multiple ways of getting the location of the application. but this one worked for me in the past atleast (it's been a while since i've done winforms programming :/)
My answer is a mod of some prior answers from @JoeMills and @user.
Get a cURL
command to log into server:
Modify cURL command to be able to save session cookie after login
-H 'Cookie: <somestuff>'
curl
at beginning -c login_cookie.txt
'login_cookie.txt'
in the same folderCall a new web page using this new cookie that requires you to be logged in
curl -b login_cookie.txt <url_that_requires_log_in>
I have tried this on Ubuntu 20.04 and it works like a charm.
When we use the round() function, it will not give correct values.
you can check it using, round (2.735) and round(2.725)
please use
import math
num = input('Enter a number')
print(math.ceil(num*100)/100)
_httpClient = new HttpClient(handler) {Timeout = TimeSpan.FromSeconds(5)};
is what I usually do, seems to work out pretty good for me, its especially good when using proxies.
You can use window.onbeforeunload
.
window.onbeforeunload = confirmExit;
function confirmExit(){
alert("confirm exit is being called");
return false;
}
There is a universal way to get this:
Function FileName() As String
FileName = Mid(Application.Caption, 1, InStrRev(Application.Caption, "-") - 2)
End Function
A little more readable :)
public static <T> ArrayList<T> reverse(ArrayList<T> list) {
int length = list.size();
ArrayList<T> result = new ArrayList<T>(length);
for (int i = length - 1; i >= 0; i--) {
result.add(list.get(i));
}
return result;
}
Using the Apache Commons IO library...
boolean isFileUnlocked = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
isFileUnlocked = true;
} catch (IOException e) {
isFileUnlocked = false;
}
if(isFileUnlocked){
// Do stuff you need to do with a file that is NOT locked.
} else {
// Do stuff you need to do with a file that IS locked
}
I have used table to center image inside the box. It keeps aspect ratio and scales image in a way that is totally inside the box. If the image is smaller than the box then it is shown as it is in the center. Below code uses 40px width and 40px height box. (Not quite sure how well it works because I removed it from another more complex code and simplified it little bit)
.SmallThumbnailContainer {
display: inline-block;
position: relative;
float: left;
width: 40px;
height: 40px;
border: 1px solid #ccc;
margin: 0px;
padding: 0px;
}
.SmallThumbnailContainer {
width: 40px;
margin: 0px 10px 0px 0px;
}
.SmallThumbnailContainer tr {
height: 40px;
text-align: center;
}
.SmallThumbnailContainer tr td {
vertical-align: middle;
position: relative;
width: 40px;
}
.SmallThumbnailContainer tr td img {
overflow: hidden;
max-height: 40px;
max-width: 40px;
vertical-align: middle;
margin: -1px -1px 1px -1px;
}
_x000D_
<table class="SmallThumbnailContainer" cellpadding="0" cellspacing="0">
<tr>
<td>
<img src="https://www.gravatar.com/avatar/bf7d39f4ed9c289feca7de38a0093250?s=32&d=identicon&r=PG" width="32" height="32" alt="OP's SO avatar image used as a sample jpg because it is hosted on SO, thus always available" />
</td>
</tr>
</table>
_x000D_
Note: the native thumbnail size in this snippet is 32px x 32px, which is smaller than its 40px x 40px container. If the container is instead sized smaller than the thumbnail in any dimension, say 40px x 20px, the image flows outside the container in the dimensions that are smaller than the corresponding image dimension. The container is marked by a gray 1px border.
This will get you the difference between two DateTime objects in milliseconds:
DateTime d1 = new DateTime();
DateTime d2 = new DateTime();
long diffInMillis = d2.getMillis() - d1.getMillis();
These files are from Maven wrapper. It works similarly to the Gradle wrapper.
This allows you to run the Maven project without having Maven installed and present on the path. It downloads the correct Maven version if it's not found (as far as I know by default in your user home directory).
The mvnw
file is for Linux (bash) and the mvnw.cmd
is for the Windows environment.
To create or update all necessary Maven Wrapper files execute the following command:
mvn -N io.takari:maven:wrapper
To use a different version of maven you can specify the version as follows:
mvn -N io.takari:maven:wrapper -Dmaven=3.3.3
Both commands require maven on PATH
(add the path to maven bin
to Path
on System Variables) if you already have mvnw in your project you can use ./mvnw
instead of mvn
in the commands.
public class DA {
public static class VersionNetFramework {
public static string Get45or451FromRegistry()
{//https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
{
int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
if (true)
{
return (@"Version: " + CheckFor45DotVersion(releaseKey));
}
}
}
// Checking the version using >= will enable forward compatibility,
// however you should always compile your code on newer versions of
// the framework to ensure your app works the same.
private static string CheckFor45DotVersion(int releaseKey)
{//https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
if (releaseKey >= 394271)
return "4.6.1 installed on all other Windows OS versions or later";
if (releaseKey >= 394254)
return "4.6.1 installed on Windows 10 or later";
if (releaseKey >= 393297)
return "4.6 installed on all other Windows OS versions or later";
if (releaseKey >= 393295)
return "4.6 installed with Windows 10 or later";
if (releaseKey >= 379893)
return "4.5.2 or later";
if (releaseKey >= 378758)
return "4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2 or later";
if (releaseKey >= 378675)
return "4.5.1 installed with Windows 8.1 or later";
if (releaseKey >= 378389)
return "4.5 or later";
return "No 4.5 or later version detected";
}
public static string GetVersionFromRegistry()
{//https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
string res = @"";
// Opens the registry key for the .NET Framework entry.
using (RegistryKey ndpKey =
RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "").
OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
{
// As an alternative, if you know the computers you will query are running .NET Framework 4.5
// or later, you can use:
// using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
// RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
foreach (string versionKeyName in ndpKey.GetSubKeyNames())
{
if (versionKeyName.StartsWith("v"))
{
RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
string name = (string)versionKey.GetValue("Version", "");
string sp = versionKey.GetValue("SP", "").ToString();
string install = versionKey.GetValue("Install", "").ToString();
if (install == "") //no install info, must be later.
res += (versionKeyName + " " + name) + Environment.NewLine;
else
{
if (sp != "" && install == "1")
{
res += (versionKeyName + " " + name + " SP" + sp) + Environment.NewLine;
}
}
if (name != "")
{
continue;
}
foreach (string subKeyName in versionKey.GetSubKeyNames())
{
RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
name = (string)subKey.GetValue("Version", "");
if (name != "")
sp = subKey.GetValue("SP", "").ToString();
install = subKey.GetValue("Install", "").ToString();
if (install == "") //no install info, must be later.
res += (versionKeyName + " " + name) + Environment.NewLine;
else
{
if (sp != "" && install == "1")
{
res += (" " + subKeyName + " " + name + " SP" + sp) + Environment.NewLine;
}
else if (install == "1")
{
res += (" " + subKeyName + " " + name) + Environment.NewLine;
}
}
}
}
}
}
return res;
}
public static string GetUpdateHistory()
{//https://msdn.microsoft.com/en-us/library/hh925567(v=vs.110).aspx
string res=@"";
using (RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\Updates"))
{
foreach (string baseKeyName in baseKey.GetSubKeyNames())
{
if (baseKeyName.Contains(".NET Framework") || baseKeyName.StartsWith("KB") || baseKeyName.Contains(".NETFramework"))
{
using (RegistryKey updateKey = baseKey.OpenSubKey(baseKeyName))
{
string name = (string)updateKey.GetValue("PackageName", "");
res += baseKeyName + " " + name + Environment.NewLine;
foreach (string kbKeyName in updateKey.GetSubKeyNames())
{
using (RegistryKey kbKey = updateKey.OpenSubKey(kbKeyName))
{
name = (string)kbKey.GetValue("PackageName", "");
res += (" " + kbKeyName + " " + name) + Environment.NewLine;
if (kbKey.SubKeyCount > 0)
{
foreach (string sbKeyName in kbKey.GetSubKeyNames())
{
using (RegistryKey sbSubKey = kbKey.OpenSubKey(sbKeyName))
{
name = (string)sbSubKey.GetValue("PackageName", "");
if (name == "")
name = (string)sbSubKey.GetValue("Description", "");
res += (" " + sbKeyName + " " + name) + Environment.NewLine;
}
}
}
}
}
}
}
}
}
return res;
}
}
using class DA.VersionNetFramework
private void Form1_Shown(object sender, EventArgs e)
{
//
// Current OS Information
//
richTextBox1.Text = @"Current OS Information:";
richTextBox1.AppendText(Environment.NewLine +
"Machine Name: " + Environment.MachineName);
richTextBox1.AppendText(Environment.NewLine +
"Platform: " + Environment.OSVersion.Platform.ToString());
richTextBox1.AppendText(Environment.NewLine +
Environment.OSVersion);
//
// .NET Framework Environment Information
//
richTextBox1.AppendText(Environment.NewLine + Environment.NewLine +
".NET Framework Environment Information:");
richTextBox1.AppendText(Environment.NewLine +
"Environment.Version " + Environment.Version);
richTextBox1.AppendText(Environment.NewLine +
DA.VersionNetFramework.GetVersionDicription());
//
// .NET Framework Information From Registry
//
richTextBox1.AppendText(Environment.NewLine + Environment.NewLine +
".NET Framework Information From Registry:");
richTextBox1.AppendText(Environment.NewLine +
DA.VersionNetFramework.GetVersionFromRegistry());
//
// .NET Framework 4.5 or later Information From Registry
//
richTextBox1.AppendText(Environment.NewLine +
".NET Framework 4.5 or later Information From Registry:");
richTextBox1.AppendText(Environment.NewLine +
DA.VersionNetFramework.Get45or451FromRegistry());
//
// Update History
//
richTextBox1.AppendText(Environment.NewLine + Environment.NewLine +
"Update History");
richTextBox1.AppendText(Environment.NewLine +
DA.VersionNetFramework.GetUpdateHistory());
//
// Setting Cursor to first character of textbox
//
if (!richTextBox1.Text.Equals(""))
{
richTextBox1.SelectionStart = 1;
}
}
Result:
Current OS Information: Machine Name: D1 Platform: Win32NT Microsoft Windows NT 6.2.9200.0
.NET Framework Environment Information: Environment.Version 4.0.30319.42000 .NET 4.6 on Windows 8.1 64 - bit or later
.NET Framework Information From Registry: v2.0.50727 2.0.50727.4927 SP2 v3.0 3.0.30729.4926 SP2 v3.5 3.5.30729.4926 SP1
v4
Client 4.6.00079
Full 4.6.00079
v4.0
Client 4.0.0.0
.NET Framework 4.5 or later Information From Registry: Version: 4.6 installed with Windows 10 or later
Update History
Microsoft .NET Framework 4 Client Profile
KB2468871
KB2468871v2
KB2478063
KB2533523
KB2544514
KB2600211
KB2600217
Microsoft .NET Framework 4 Extended
KB2468871
KB2468871v2
KB2478063
KB2533523
KB2544514
KB2600211
KB2600217
Microsoft .NET Framework 4 Multi-Targeting Pack
KB2504637 Update for (KB2504637)
None of the solutions worked for me in Firefox.
The following solution changes the border style on focus for Firefox and sets the outline to none for other browsers.
I've effectively made the focus border go from a 3px blue glow to a border style that matches the text area border. Here's some border styles:
Dashed border (border 2px dashed red):
Textarea border (border 1px solid gray):
Here is the code:
input:focus, textarea:focus {_x000D_
outline: none; /** For Safari, etc **/_x000D_
border:1px solid gray; /** For Firefox **/_x000D_
}_x000D_
_x000D_
#textarea {_x000D_
position:absolute;_x000D_
top:10px;_x000D_
left:10px;_x000D_
right:10px;_x000D_
width:calc(100% - 20px);_x000D_
height:160px;_x000D_
display:inline-block;_x000D_
margin-top:-0.2em;_x000D_
}
_x000D_
<textarea id="textarea">yo</textarea>
_x000D_