Does your HOSTS file have an entry for localhost
? Some other situations this error is seen in seem to have this as a problem resolution.
Make sure you have 127.0.0.1 localhost
set in it...
For linear solution, you can use Manacher's algorithm. There is another algorithm call Gusfield's Algorithm, and below is the code in java:
public class Solution {
char[] temp;
public int match(int a, int b,int len){
int i = 0;
while (a-i>=0 && b+i<len && temp[a-i] == temp[b+i]) i++;
return i;
}
public String longestPalindrome(String s) {
//This makes use of the assumption that the string has not more than 1000 characters.
temp=new char[1001*2];
int[] z=new int[1001 * 2];
int L=0, R=0;
int len=s.length();
for(int i=0;i<len*2+1;i++){
temp[i]='.';
}
for(int i=0;i<len;++i){
temp[i*2+1] = s.charAt(i);
}
z[0]=1;
len=len*2+1;
for(int i=0;i<len;i++){
int ii = L - (i - L);
int n = R + 1 - i;
if (i > R)
{
z[i] = match(i, i,len);
L = i;
R = i + z[i] - 1;
}
else if (z[ii] == n)
{
z[i] = n + match(i-n, i+n,len);
L = i;
R = i + z[i] - 1;
}
else
{
z[i] = (z[ii]<= n)? z[ii]:n;
}
}
int n = 0, p = 0;
for (int i=0; i<len; ++i)
if (z[i] > n)
n = z[p = i];
StringBuilder result=new StringBuilder();
for (int i=p-z[p]+1; i<=p+z[p]-1; ++i)
if(temp[i]!='.')
result.append(String.valueOf(temp[i]));
return result.toString();
}
}
You can find more on other solutions such as the best O(n^2) solution or Manacher's algorithm from my own blog.
Content-Type: application/force-download
means "I, the web server, am going to lie to you (the browser) about what this file is so that you will not treat it as a PDF/Word Document/MP3/whatever and prompt the user to save the mysterious file to disk instead". It is a dirty hack that breaks horribly when the client doesn't do "save to disk".
Use the correct mime type for whatever media you are using (e.g. audio/mpeg
for mp3).
Use the Content-Disposition: attachment; etc etc
header if you want to encourage the client to download it instead of following the default behaviour.
Say you have a FaceView
which is some sort of image. You're going to have many of them on screen (or, in a collection view, table, stack view or other list).
In the class FaceView
you will need a variable "index"
class FaceView: UIView {
var index: Int
so that each FaceView can be self-aware of "which" face it is on screen.
So you must add var index: Int
to the class in question.
So you are adding many FaceView to your screen ...
let f = FaceView()
f.index = 73
.. you add f to your stack view, screen, or whatever.
You now add a click to f
f.addGestureRecognizer(UITapGestureRecognizer(target: self,
action: #selector(tapOneOfTheFaces)))
@objc func tapOneOfTheFaces(_ sender: UITapGestureRecognizer) {
if let tapped = sender.view as? CirclePerson {
print("we got it: \(tapped.index)")
You now know "which" face was clicked in your table, screen, stack view or whatever.
It's that easy.
Look into re-indexing tables in your database.
You can first find out the fragmentation level - and if it's above 10% or so you could benefit from re-indexing. If it's very high it's likely this is creating a significant performance bottle neck.
This should be done regularly.
Here are two solutions, I am using Oracle SQL server:
1) using over clause:
with org_table as
(select 1 id, 'Ali' uname
from dual
union
select 1, 'June'
from dual
union
select 2, 'Jame'
from dual
union
select 2, 'July' from dual)
select id, uname
from (select a.id,
a.uname,
ROW_NUMBER() OVER(PARTITION BY a.id ORDER BY a.id) AS freq
from org_table a)
where freq = 1
2) Using sub-query:
with org_table as
(select 1 id, 'Ali' uname
from dual
union
select 1, 'June'
from dual
union
select 2, 'Jame'
from dual
union
select 2, 'July' from dual)
select a.id,
(select b.uname
from org_table b
where b.id = a.id
and rownum = 1)
from (select distinct id from org_table) a
I can't see hotkey for macbook for use vim in standard terminal. Hope it will help someone. For macOS users (tested on macbook pro 2018):
fn + ? - move to beginning line
fn + ? - move to end line
fn + ? - move page up
fn + ? - move page down
fn + g - move the cursor to the beginning of the document
fn + shift + g - move the cursor to the end of the document
For the last two commands sometime needs to tap twice.
You should initialize variables to None and then check it:
var1 = None
if var1 is None:
var1 = 4
Which can be written in one line as:
var1 = 4 if var1 is None else var1
or using shortcut (but checking against None is recommended)
var1 = var1 or 4
alternatively if you will not have anything assigned to variable that variable name doesn't exist and hence using that later will raise NameError
, and you can also use that knowledge to do something like this
try:
var1
except NameError:
var1 = 4
but I would advise against that.
Kotlin version with infix function
infix fun View.below(view: View) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}
Then you can write:
view1 below view2
Or you can call it as a normal function:
view1.below(view2)
As I have not found any simple script so far, here's my two cents:
set ELEVATE_APP=Full command line without parameters for the app to run
set ELEVATE_PARMS=The actual parameters for the app
echo Set objShell = CreateObject("Shell.Application") >elevatedapp.vbs
echo Set objWshShell = WScript.CreateObject("WScript.Shell") >>elevatedapp.vbs
echo Set objWshProcessEnv = objWshShell.Environment("PROCESS") >>elevatedapp.vbs
echo objShell.ShellExecute "%ELEVATE_APP%", "%ELEVATE_PARMS%", "", "runas" >>elevatedapp.vbs
DEL elevatedapp.vbs
Use LinearLayout.LayoutParams
instead of MarginLayoutParams
. Here's the documentation.
This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.
Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.
function f(input, callback) {
var value;
// Assume the async call always succeed
async_call(input, function(result) { callback(result) };
}
The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.
xcopy "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i
Probably the problem is the space.Try with quotes.
A good summary of LLVM is this:
At the frontend you have Perl, and many other high level languages. At the backend, you have the natives code that run directly on the machine.
At the centre is your intermediate code representation. If every high level language can be represented in this LLVM IR format, then analysis tools based on this IR can be easily reused - that is the basic rationale.
Try just using:
pip install pycryptodome
or:
pip install pycryptodomex
Math
has static method where you can call directly like Math.abs()
while Date
has static method like Date.now()
and also instance method where you need to create new instance first var time = new Date()
to call time.getHours()
.
// The instance method of Date can be found on `Date.prototype` so you can just call:
var keys = Object.getOwnPropertyNames(Date.prototype);
// And for the static method
var keys = Object.getOwnPropertyNames(Date);
// But if the instance already created you need to
// pass its constructor
var time = new Date();
var staticKeys = Object.getOwnPropertyNames(time.constructor);
var instanceKeys = Object.getOwnPropertyNames(time.constructor.prototype);
Of course you will need to filter the obtained keys for the static method to get actual method names, because you can also get length, name
that aren't a function on the list.
But how if we want to obtain all available method from class that extend another class?
Of course you will need to scan through the root of prototype like using __proto__
. For saving your time you can use script below to get static method and deep method instance.
// var keys = new Set();_x000D_
function getStaticMethods(keys, clas){_x000D_
var keys2 = Object.getOwnPropertyNames(clas);_x000D_
_x000D_
for(var i = 0; i < keys2.length; i++){_x000D_
if(clas[keys2[i]].constructor === Function)_x000D_
keys.add(keys2[i]);_x000D_
}_x000D_
}_x000D_
_x000D_
function getPrototypeMethods(keys, clas){_x000D_
if(clas.prototype === void 0)_x000D_
return;_x000D_
_x000D_
var keys2 = Object.getOwnPropertyNames(clas.prototype);_x000D_
for (var i = keys2.length - 1; i >= 0; i--) {_x000D_
if(keys2[i] !== 'constructor')_x000D_
keys.add(keys2[i]);_x000D_
}_x000D_
_x000D_
var deep = Object.getPrototypeOf(clas);_x000D_
if(deep.prototype !== void 0)_x000D_
getPrototypeMethods(keys, deep);_x000D_
}_x000D_
_x000D_
// ====== Usage example ======_x000D_
// To avoid duplicate on deeper prototype we use `Set`_x000D_
var keys = new Set();_x000D_
getStaticMethods(keys, Date);_x000D_
getPrototypeMethods(keys, Date);_x000D_
_x000D_
console.log(Array.from(keys));
_x000D_
If you want to obtain methods from created instance, don't forget to pass the constructor
of it.
Extending bp's answer, I wanted to show you what he meant by immutable types.
First, this is okay:
>>> class TestB():
... def __init__(self, attr=1):
... self.attr = attr
...
>>> a = TestB()
>>> b = TestB()
>>> a.attr = 2
>>> a.attr
2
>>> b.attr
1
However, this only works for immutable (unchangable) types. If the default value was mutable (meaning it can be replaced), this would happen instead:
>>> class Test():
... def __init__(self, attr=[]):
... self.attr = attr
...
>>> a = Test()
>>> b = Test()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[1]
>>>
Note that both a
and b
have a shared attribute. This is often unwanted.
This is the Pythonic way of defining default values for instance variables, when the type is mutable:
>>> class TestC():
... def __init__(self, attr=None):
... if attr is None:
... attr = []
... self.attr = attr
...
>>> a = TestC()
>>> b = TestC()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[]
The reason my first snippet of code works is because, with immutable types, Python creates a new instance of it whenever you want one. If you needed to add 1 to 1, Python makes a new 2 for you, because the old 1 cannot be changed. The reason is mostly for hashing, I believe.
They are exactly the same. When you use it be consistent. Use one of them in your database
Some OS-specific interfaces:
_NSGetExecutablePath()
(man 3 dyld)readlink /proc/self/exe
getexecname()
sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1
readlink /proc/curproc/file
(FreeBSD doesn't have procfs by default)readlink /proc/curproc/exe
readlink /proc/curproc/file
GetModuleFileName()
with hModule
= NULL
There are also third party libraries that can be used to get this information, such as whereami as mentioned in prideout's answer, or if you are using Qt, QCoreApplication::applicationFilePath() as mentioned in the comments.
The portable (but less reliable) method is to use argv[0]
. Although it could be set to anything by the calling program, by convention it is set to either a path name of the executable or a name that was found using $PATH
.
Some shells, including bash and ksh, set the environment variable "_
" to the full path of the executable before it is executed. In that case you can use getenv("_")
to get it. However this is unreliable because not all shells do this, and it could be set to anything or be left over from a parent process which did not change it before executing your program.
background:url(../images/red_bullet.jpg) left 3px no-repeat;
I generally use 3px in place of top
. By increasing/decreasing that value, the image can be changed to the required height.
You could use the HTML5 Tag <mark>
:
<p>Enter the competition by
<mark class="red">January 30, 2011</mark> and you could win up to $$$$ — including amazing
<mark class="blue">summer</mark> trips!</p>
And use this in the CSS:
p {
font-size:14px;
color:#538b01;
font-weight:bold;
font-style:italic;
}
mark.red {
color:#ff0000;
background: none;
}
mark.blue {
color:#0000A0;
background: none;
}
The tag <mark>
has a default background color...at least in Chrome.
If you can use jQuery, and I highly recommend you do, you would simply do
$('#myTextArea').val('');
Otherwise, it is browser dependent. Assuming you have
var myTextArea = document.getElementById('myTextArea');
In most browsers you do
myTextArea.innerHTML = '';
But in Firefox, you do
myTextArea.innerText = '';
Figuring out what browser the user is using is left as an exercise for the reader. Unless you use jQuery, of course ;)
Edit: I take that back. Looks like support for .innerHTML on textarea's has improved. I tested in Chrome, Firefox and Internet Explorer, all of them cleared the textarea correctly.
Edit 2: And I just checked, if you use .val('') in jQuery, it just sets the .value property for textarea's. So .value should be fine.
The most ideal way of doing this is found here: Fragment: which callback invoked when press back button & customize it
public class MyActivity extends Activity
{
//...
//Defined in Activity class, so override
@Override
public void onBackPressed()
{
super.onBackPressed();
myFragment.onBackPressed();
}
}
public class MyFragment extends Fragment
{
//Your created method
public static void onBackPressed()
{
//Pop Fragments off backstack and do your other checks
}
}
This works:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots(1,1)
x1 = [0,1,2,3]
squad = ['Fultz','Embiid','Dario','Simmons']
ax1.set_xticks(x1)
ax1.set_xticklabels(squad, minor=False, rotation=45)
try using the css pseudoclass :focus
input[type="button"], input[type="button"]:focus {
/* your style goes here */
}
edit as for links and onclick events use (you shouldn’t use inline javascript eventhandlers, but for the sake of simplicity i will use them here):
<a href="some/page.php" title="perform some js action" onclick="callFunction(this.href);return false;">watch and learn</a>
with this.href you can even access the target of the link in your function. return false
will just prevent browsers from following the link when clicked.
if javascript is disabled the link will work as a normal link and just load some/page.php
—if you want your link to be dead when js is disabled use href="#"
@Bean
MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize("5120MB");
factory.setMaxRequestSize("5120MB");
return factory.createMultipartConfig();
}
put it in class where you are defining beans
All I needed was this :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
try {
String d = sdf.format(new Date());
System.out.println(d);
System.out.println(sdfLocal.parse(d));
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Output : slightly dubious, but I want only the date to be consistent
2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013
It looks like this issue has to do with the difference between the Content-Type
and Accept
headers. In HTTP, Content-Type
is used in request and response payloads to convey the media type of the current payload. Accept
is used in request payloads to say what media types the server may use in the response payload.
So, having a Content-Type
in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type
does matter.
If a server is not able to process the Content-Type
of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept
header, it will return a 406 error.)
In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.
You could fix this in one of two ways:
Include the DataServiceVersion header in the request and set it be less than v3. For example:
DataServiceVersion: 2.0;
(Option 2 assumes that you aren't using any v3 features in your request payload.)
The most commonly used way is using jQuery for this purpose:
var safestring = $('<div>').text(unsafestring).html();
If you want to to encode all the HTML entities you will have to use a library or write it yourself.
You can use a more compact library than jQuery, like HTML Encoder and Decode
Recently, AWS added a feature called Sessions Manager to the Systems Manager service that allows one to SSH into an instance without needing to setup a private key or opening up port 22. I believe authentication is done with IAM and optionally MFA.
You can find out more about it here:
To add to what Evan said: C does not have a built-in operator for exponentiation, because it is not a primitive operation for most CPUs. Thus, it's implemented as a library function.
Also, for computing the function e^x, you can use the exp(double)
, expf(float)
, and expl(long double)
functions.
Note that you do not want to use the ^
operator, which is the bitwise exclusive OR operator.
There is no function exit equivalent to php die() in JS, if you are not using any function then you can simply use return;
return;
Type switches can also be used with reflection stuff:
var str = "hello!"
var obj = reflect.ValueOf(&str)
switch obj.Elem().Interface().(type) {
case string:
log.Println("obj contains a pointer to a string")
default:
log.Println("obj contains something else")
}
If you look for POSIX compliant solution:
cd DirsRoot && find . -type f -print -o -name . -o -prune
-maxdepth is not POSIX compliant option.
Check if tools.jar used during compilation complies with the JRE set. If you are on eclipse, verify the versions as:
Goto Window->Preferences
- Check Ant Runtime by selecting Runtime under Ant in the left pane. Check the Global Entries under classpath tab. You can see the version in folder path.
- On the left pane check installed JREs under Java. Check the version.
I had also got the same problem when my selected JRE was 1.6.0_24 and tools.jar in Ant runtime was coming from jdk 1.7
If both of them are from different versions- 1.6/1.7, correct them by correcting their path.
Typically, tools.jar can be found at :C:\Program Files\Java\jdk1.x.x\lib. Likewise if required add the JRE by pointing it to C:\Program Files\Java\jdk1.x.x\
The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/
folder to store all assets, instead of different bundles.
Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.
Templates also benefit from centralizing your assets, because the links are much more concise[...]
I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.
Try this:
String yourVal = "20.5";
float a = (Float.valueOf(yourVal)).floatValue();
System.out.println(a);
I'm on Ubuntu 12.10 and running this command:
apt-get install libpq-dev
helped me - after that ran gem install pg -v "0.14.1", and all good now
Uses a "standard" set of character orderings (a,b,c, ... etc.). This is in contrast to some specific locales, which may sort characters in different orders ('a-with-acute' may be before or after 'a', depending on the locale, and so on).
On the other hand, looks purely at the values of the raw byte(s) that represent the character.
There's a great sample at http://msdn.microsoft.com/en-us/library/e6883c06.aspx that shows the results of the various StringComparison values. All the way at the end, it shows (excerpted):
StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
You can see that where InvariantCulture yields (U+0069, U+0049, U+00131), Ordinal yields (U+0049, U+0069, U+00131).
4 steps
npm install dotenv --save
Next add the following line to your app.
require('dotenv').config()
Then create a .env
file at the root directory of your application and add the variables to it.
// contents of .env
REACT_APP_API_KEY = 'my-secret-api-key'
.env
to your .gitignore
file so that Git ignores it and it never ends up on GitHub.If you are using create-react-app then you only need step 3 and 4 but keep in mind variable needs to start with REACT_APP_
for it to work.
Reference: https://create-react-app.dev/docs/adding-custom-environment-variables/
NOTE - Need to restart application after adding variable in .env file.
Reference - https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f
You need to use the readLine()
method in class BufferedReader
.
Create a new object from that class and operate this method on him and save it to a string.
On HTML5 the scrollamount and the scrolldelay attributes do not work. They are depricated attributes.
Use INDIRECT()
=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))
On mine, I had to install ARM AEBI a7a System Image and Google APIs, and also installed MIPS which was only available for API 15, 16, and 17 (I didn't go below 15.) Took about 12 hours of tinkering, but it works now.
alternatively, you can use Genymotion as an emulator, however will most likely lose design abilities otherwise available with included emulators.
It works now. Pretty slow, but it works. Of course, once you have the emulator started, as long as you don't close it, it will be much faster.
You may need to restart Android studio, and I restarted my entire computer just for good measure.
Hope that helps.
You could also use alias_attribute
if you still want to be able to refer to them as tasks as well:
class User < ActiveRecord::Base
alias_attribute :jobs, :tasks
has_many :tasks
end
Very Simple
private void button1_Click(object sender, EventArgs e)
{
ListViewItem item = new ListViewItem();
item.SubItems.Add(textBox2.Text);
item.SubItems.Add(textBox3.Text);
item.SubItems.Add(textBox4.Text);
listView1.Items.Add(item);
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
}
You can also Do this stuff...
ListViewItem item = new ListViewItem();
item.SubItems.Add("Santosh");
item.SubItems.Add("26");
item.SubItems.Add("India");
For C# the solution is to cast the values to a double (as Math.Ceiling takes a double):
int nPages = (int)Math.Ceiling((double)nItems / (double)nItemsPerPage);
In java you should do the same with Math.ceil().
You may also be interested in using joins on updates, which is possible as well.
Update someTable Set someValue = 4 From someTable s Inner Join anotherTable a on s.id = a.id Where a.id = 4
-- Only updates someValue in someTable who has a foreign key on anotherTable with a value of 4.
Edit: If the values you are updating aren't coming from somewhere else in the database, you'll need to issue multiple update queries.
The OP is just missing the table aliases after the delete
DELETE t1, t2
FROM table1 t1 LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE t1.id = some_id
The height is the text size you have set on the Paint variable.
Another way to find out the height is
mPaint.getTextSize();
I have found the answer and solution to this problem. Before, I did not know that php.ini resides where in wordpress files. Now I have found that file in wp-admin directory where I placed the code
post_max_size 33M
upload_max_filesize 32M
then it worked. It increases the upload file size for my worpdress website. But, it is the same 2M as was before on cPanel.
Since Spring 4.2 you can use @EventListener
(documentation)
@Component
class MyClassWithEventListeners {
@EventListener({ContextRefreshedEvent.class})
void contextRefreshedEvent() {
System.out.println("a context refreshed event happened");
}
}
Try initializing with null value.
private java.util.Date date2 = null;
Also private java.util.Date date2 = "";
will not work as "" is a string.
Very simple. Create a span for the text, get the width and reduce font-size until the span has the same width of the div container:
while($("#container").find("span").width() > $("#container").width()) {
var currentFontSize = parseInt($("#container").find("span").css("font-size"));
$("#container").find("span").css("font-size",currentFontSize-1);
}
I am quite sure that Xcode wants us to be logged in with our "normal" account to the App Store app when it tries to upload an app to the Mac App Store (MAS) via the Organizer window.
Usually, we developers all test our apps using our MAS test account. This seems to switch the logged App Store user, too. For me, this always works fine:
If you are using Xcode 6 and designing for iOS 8, none of these solutions are correct. To get your iPhone-only views to be sized correctly, don't turn off size classes, don't turn off inferred metrics, and don't set constraints (yet). Instead, use the size class control, which is an easy to miss text button at the bottom of Interface Builder that initially reads "wAny hAny".
Click the button, and choose Compact Width, Regular Height. This resize your views and cover all iPhone portrait orientations. Apple's docs here: https://developer.apple.com/library/ios/recipes/xcode_help-IB_adaptive_sizes/chapters/SelectingASizeClass.html or search on "Selecting a Size Class in Interface Builder"
if (/(^|;)\s*visited=/.test(document.cookie)) {
alert("Hello again!");
} else {
document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
alert("This is your first time!");
}
is one way to do it. Note that document.cookie
is a magic property, so you don't have to worry about overwriting anything, either.
There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage
and friends are convenient and useful.
This could be accomplished with a single line of code:
IF OBJECT_ID('tempdb..#tempTableName') IS NOT NULL DROP TABLE #tempTableName;
Does your console app require user interaction? If so, that's a serious no-no and you should redesign your application. While there are some hacks to make this sort of work in older versions of the OS, this is guaranteed to break in the future.
If your app does not require user interaction, then perhaps your problem is related to the user the service is running as. Try making sure that you run as the correct user, or that the user and/or resources you are using have the right permissions.
If you require some kind of user-interaction, then you will need to create a client application and communicate with the service and/or sub-application via rpc, sockets, or named pipes.
Another solution to the problem could be the following set of CSS rules:
.ellipsis{
white-space:nowrap;
overflow:hidden;
}
.ellipsis:after{
content:'...';
}
The only drawback with the above CSS is that it would add the "..." irrespective of whether the text-overflows the container or not. Still, if you have a case where you have a bunch of elements and are sure that content will overflow, this one would be a simpler set of rules.
My two cents. Hats off to the original technique by Justin Maxwell
You need to select the li
tags contained within the .edgetoedge
class. .edgetoedge
only matches the one ul
tag:
$(".edgetoedge li").removeClass("highlight");
This is useful when you want to have a global variable. You define the global variables in some source file, and declare them extern in a header file so that any file that includes that header file will then see the same global variable.
You could also do the following:
// untested
Calendar cal = GregorianCalendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 23);// I might have the wrong Calendar constant...
cal.set(Calendar.MONTH, 8);// -1 as month is zero-based
cal.set(Calendar.YEAR, 2009);
Timestamp tstamp = new Timestamp(cal.getTimeInMillis());
Use the moment.js library for time and date management.
import moment = require('moment');
const now = moment();
now.subtract(7, 'seconds'); // 7 seconds ago
now.subtract(7, 'days'); // 7 days and 7 seconds ago
now.subtract(7, 'months'); // 7 months, 7 days and 7 seconds ago
now.subtract(7, 'years'); // 7 years, 7 months, 7 days and 7 seconds ago
// because `now` has been mutated, it no longer represents the current time
You have to do this to echo it:
echo $row['note'];
(The data is coming as an array)
AF_INET
is an address family that is used to designate the type of addresses that your socket can communicate with (in this case, Internet Protocol v4 addresses). When you create a socket, you have to specify its address family, and then you can only use addresses of that type with the socket. The Linux kernel, for example, supports 29 other address families such as UNIX (AF_UNIX
) sockets and IPX (AF_IPX
), and also communications with IRDA and Bluetooth (AF_IRDA
and AF_BLUETOOTH
, but it is doubtful you'll use these at such a low level).
For the most part, sticking with AF_INET
for socket programming over a network is the safest option. There is also AF_INET6
for Internet Protocol v6 addresses.
Hope this helps,
And just to provide a contrast, there's also pip.
I forgot to mention. This should also accept whitespace.
You could use:
/^[-@.\/#&+\w\s]*$/
Note how this makes use of the character classes \w
and \s
.
EDIT:- Added \ to escape /
Adding to the accepted answer by Luke West. If you have any entitlements:
I follow this simple setup with meld. Meld is free and opensource diff tool. You will see nice side by side comparison of files and directory for any code changes.
[diff] tool = meld
git difftool --dir-diff ./
git difftool --cached --dir-diff ./
Use svn revert --recursive folder_name
svn revert
is inherently dangerous, since its entire purpose is to throw away data — namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes.
http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.revert.html
For the version of the framework that is installed, it varies depending on which service packs and hotfixes you have installed. Take a look at this MSDN page for more details. It suggests looking in %systemroot%\Microsoft.NET\Framework
to get the version.
Environment.Version will programmatically give you the version of the CLR.
Note that this is the version of the CLR, and not necessarily the same as the latest version of the framework you have installed (.NET 3.0 and 3.5 both use v2 of the CLR).
Watch out for possible unintended literals in your argument
for example you can have a space within your argument, rendering it to a string / literal:
float(' 0.33')
After making sure the unintended space did not make it into the argument, I was left with:
float(0.33)
Like this it works like a charm.
Take away is: Pay Attention for unintended literals (e.g. spaces that you didn't see) within your input.
So this is my first answer here, and because I needed something similar I did with pseudo elements for 2 inner shadows, and an extra DIV for an upper outer shadow. Don't know if this is the best solutions but maybe it will help someone.
HTML
<div class="shadow-block">
<div class="shadow"></div>
<div class="overlay">
<div class="overlay-inner">
content here
</div>
</div>
</div>
CSS
.overlay {
background: #f7f7f4;
height: 185px;
overflow: hidden;
position: relative;
width: 100%;
}
.overlay:before {
border-radius: 50% 50% 50% 50%;
box-shadow: 0 0 50px 2px rgba(1, 1, 1, 0.6);
content: " ";
display: block;
margin: 0 auto;
width: 80%;
}
.overlay:after {
border-radius: 50% 50% 50% 50%;
box-shadow: 0 0 70px 5px rgba(1, 1, 1, 0.5);
content: "-";
display: block;
margin: 0 auto;
position: absolute;
bottom: -65px;
left: -50%;
right: -50%;
width: 80%;
}
.shadow {
position: relative;
width:100%;
height:8px;
margin: 0 0 -22px 0;
-webkit-box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
border-radius: 50%;
}
I know this is a very old question and the problem is marked as fixed. However, if someone with a case like mine where the table have trigger for data logging on update events, this will cause problem. Both the columns will get the update and log will make useless entries. The way I did
IF (CONDITION) IS TRUE
BEGIN
UPDATE table SET columnx = 25
END
ELSE
BEGIN
UPDATE table SET columny = 25
END
Now this have another benefit that it does not have unnecessary writes on the table like the above solutions.
This works:
word = str(input("Enter string:"))
notChar = 0
isChar = 0
for char in word:
if not char.isalpha():
notChar += 1
else:
isChar += 1
print(isChar, " were letters; ", notChar, " were not letters.")
I would use the RadioButtons in a ListBox, and then bind to the SelectedValue.
This is an older thread about this topic, but the base idea should be the same: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/323d067a-efef-4c9f-8d99-fecf45522395/
Try the following:
var filteredFileSet = fileList.Where(item => filterList.Contains(item));
When you iterate over filteredFileSet (See LINQ Execution) it will consist of a set of IEnumberable values. This is based on the Where Operator checking to ensure that items within the fileList data set are contained within the filterList set.
As fileList is an IEnumerable set of string values, you can pass the 'item' value directly into the Contains method.
Travis-ci offers a new container-based infrastructure that uses docker. This can be very useful if you're trying to troubleshoot a travis-ci build by reproducing it locally. This is taken from Travis CI's documentation.
If you're having trouble tracking down the exact problem in a build it often helps to run the build locally. To do this you need to be using our container based infrastructure (ie, have sudo: false
in your .travis.yml
), and to know which Docker image you are using on Travis CI.
Select an image from Docker Hub. If you're not using a language-specific image pick ci-ruby
. Open a terminal and start an interactive Docker session using the image URL:
docker run -it travisci/ubuntu-ruby:18.04 /bin/bash
Switch to the travis
user:
su - travis
/
folder of the image.There is also this free API that you can use to make free barcodes in java.
It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:
insert into errortable (dateupdated, table1id)
values (sysdate, 1083);
It seems silly to convert the system date to a string just to convert it back to a date.
If you want to see the full date, then you can do:
select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;
You have to actively choose to install MSYS to get the make.exe. So you should always have at least (the native) mingw32-make.exe if MinGW was installed properly. And if you installed MSYS you will have make.exe (in the MSYS subfolder probably).
Note that many projects require first creating a makefile (e.g. using a configure script or automake .am file) and it is this step that requires MSYS or cygwin. Makes you wonder why they bothered to distribute the native make at all.
Once you have the makefile, it is unclear if the native executable requires a different path separator than the MSYS make (forward slashes vs backward slashes). Any autogenerated makefile is likely to have unix-style paths, assuming the native make can handle those, the compiled output should be the same.
Some time your $watch is calling dynamically
and it will create its instances so you have to call deregistration function before your $watch
function
if(myWatchFun)
myWatchFun(); // it will destroy your previous $watch if any exist
myWatchFun = $scope.$watch("abc", function () {});
Environment:Linux Error: "jenkins Failed to connect to repository : Error performing command: git ls-remote -h"
Solution : if repository URL and credential configured correctly ,problem on git installion and config a) make sure git installed on your linux machine. if git not installed , install it ("sudo yum install git") b) Goto to -> Manage Jenkins -> Global Tool Configuration ->Git->Path to Git executable make sure "git" command present.
python is an interpreted language, so you don't need to compile your scripts to make them run. The easiest way to get one running is to navigate to it's folder in a terminal and execute "python somefile.py". This depends on you having python installed from the python site.
You can compile python apps, but that is generally not something a new developer needs to do initially. If that is what you're looking for, take a peek at py2exe. This will take your python script and package it up as an executable file like any program on your windows-based computer. You can also compile individual files using python, as described in the "Compiling Python modules to byte code" section at this site.
Let me assume that your data.frame is a mix of different datatypes and not all columns need to be modified.
to modify only columns 12 to 18 (of the total 21), just do this
df[, 12:18][df[, 12:18] == 0] <- NA
Using top
instead of margin-top
is another possible solution, if appropriate.
Write editTextBackground.xml in drawable folder in resources
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1dp"
android:color="@color/borderColor" />
</shape>
don't forget to declare color in resources named borderColor
.
and assign this background to the EditText
in xml background attribute
<EditText
android:id="@+id/text"
android:background="@drawable/editTextBackground"
/>
and it'll set border to EditText
.
You can change border of edit text without drawable by using style
attribute
style="@style/Widget.AppCompat.EditText"
for more details visit customize edit text
select case when [am or _pm] ='PM' and datepart(HOUR,time_received)<>12
then dateadd(hour,12,time_received)
else time_received
END
from table
works
Another example : I use it to group Data by date. But some data don't have date. I can group it with the header "NoDate"
The problem is that you call remove
on the root of your Firebase:
ref = new Firebase("myfirebase.com")
ref.remove();
This will remove the entire Firebase through the API.
You'll typically want to remove specific child nodes under it though, which you do with:
ref.child(key).remove();
Give my credit to @chad-m 's answer.
Here is the Swift version:
MyNavigationController.swift
import UIKit
class MyNavigationController: UINavigationController, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.delegate = self
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if viewController == self.viewControllers.first {
self.setNavigationBarHidden(true, animated: animated)
} else {
self.setNavigationBarHidden(false, animated: animated)
}
}
}
Difference between chad-m's answer and mine:
Inherit from UINavigationController, so you won't pollute your rootViewController.
use self.viewControllers.first
rather than homeViewController
, so you won't do this 100 times for your 100 UINavigationControllers in 1 StoryBoard.
You need to move the unique_ptr
:
vec.push_back(std::move(ptr2x));
unique_ptr
guarantees that a single unique_ptr
container has ownership of the held pointer. This means that you can't make copies of a unique_ptr
(because then two unique_ptr
s would have ownership), so you can only move it.
Note, however, that your current use of unique_ptr
is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:
std::unique_ptr<int> ptr(new int(1));
In C++14 we have an even better way to do so:
make_unique<int>(5);
You can insert arbitrary PowerShell script code in a double-quoted string by using a subexpression, for example, $() like so:
"C:\temp\mybackup $(get-date -f yyyy-MM-dd).zip"
And if you are getting the path from somewhere else - already as a string:
$dirName = [io.path]::GetDirectoryName($path)
$filename = [io.path]::GetFileNameWithoutExtension($path)
$ext = [io.path]::GetExtension($path)
$newPath = "$dirName\$filename $(get-date -f yyyy-MM-dd)$ext"
And if the path happens to be coming from the output of Get-ChildItem:
Get-ChildItem *.zip | Foreach {
"$($_.DirectoryName)\$($_.BaseName) $(get-date -f yyyy-MM-dd)$($_.extension)"}
Many answer above are correct but same time convoluted with other aspects of authN/authZ. What actually resolves the exception in question is this line:
services.AddScheme<YourAuthenticationOptions, YourAuthenticationHandler>(YourAuthenticationSchemeName, options =>
{
options.YourProperty = yourValue;
})
Alternatively you could read you csv with header=None
and then add it with df.columns
:
Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None)
Cov.columns = ["Sequence", "Start", "End", "Coverage"]
In Visual Studio 2012, 2013, 2015, you can also do it with Web Essentials, just right click the files and from context menu > Web Essential >> Diff selected files:
Edit: It's now available as a separate extension
simply use cookies to store your visited page list.
and apply some if else.
EDIT: also use ServerVariables HTTP_REFERER.
Make it simple:
render(<BrowserRouter><Main /></BrowserRouter>, document.getElementById('root'));
and don't forget: import { BrowserRouter } from "react-router-dom";
If you visit this link https://msdn.microsoft.com/library/ms748948%28v=vs.100%29.aspx#Window_Lifetime_Events and scroll down to Window Lifetime Events it will show you the event order.
Open:
Close:
Main advantage of MVC architecture is differentiating the layers of a project in Model,View and Controller for the Re-usability of code, easy to maintain code and maintenance. The best thing is the developer feels good to add some code in between the project maintenance.
Here you can see the some more points on Main Advantages of MVC Architecture.
I had the same problem, I changed the FXML name to the FXML file in the controller class and the problem was solved.
The array decays to a pointer when passed.
Section 6.4 of the C FAQ covers this very well and provides the K&R references etc.
That aside, imagine it were possible for the function to know the size of the memory allocated in a pointer. You could call the function two or more times, each time with different input arrays that were potentially different lengths; the length would therefore have to be passed in as a secret hidden variable somehow. And then consider if you passed in an offset into another array, or an array allocated on the heap (malloc
and all being library functions - something the compiler links to, rather than sees and reasons about the body of).
Its getting difficult to imagine how this might work without some behind-the-scenes slice objects and such right?
Symbian did have a AllocSize()
function that returned the size of an allocation with malloc()
; this only worked for the literal pointer returned by the malloc, and you'd get gobbledygook or a crash if you asked it to know the size of an invalid pointer or a pointer offset from one.
You don't want to believe its not possible, but it genuinely isn't. The only way to know the length of something passed into a function is to track the length yourself and pass it in yourself as a separate explicit parameter.
Sort of:
class some_class {
static std::vector<std::string> v; // declaration
};
const char *vinit[] = {"one", "two", "three"};
std::vector<std::string> some_class::v(vinit, end(vinit)); // definition
end
is just so I don't have to write vinit+3
and keep it up to date if the length changes later. Define it as:
template<typename T, size_t N>
T * end(T (&ra)[N]) {
return ra + N;
}
Zookeeper is just a Java process and when you start a Zookeeper instance it runs a org.apache.zookeeper.server.quorum.QuorumPeerMain
class. So you can check for a running Zookeeper like this:
jps -l | grep zookeeper
or even like this:
jps | grep Quorum
upd:
regarding this: will hostname be the hostname of my box??
- the answer is yes.
In Bootstrap 4:
class="font-weight-bold"
Or:
<strong>text</strong>
For pre 1.1 django it is simple (for default admin site instance):
reverse('admin_%s_%s_change' % (app_label, model_name), args=(object_id,))
In the past, I've used a .cmd script I found on the Internet. I hate the way localization normally messes with dates. Anytime you have dates in filenames (or anywhere else, if I may be so bold) I figure you want them in ISO 8601 format:
2015-02-19T14:54:51Z
or something else that has Y M D H M in that order, such as
2015-02-19 14:54
because it fixes the MDY / DMY ambiguity and because it's sortable as text.
I don't know where I got that .cmd script, but it may have been http://ss64.com/nt/syntax-getdate.html, which works beautifully on my YYYY-MM-DD Windows 8.1 and on a M/D/YYYY vanilla install of Windows 7. Both give the same format:
2015-02-09 04:43
My solution to not having sessionStorage transferable over tabs was to create a localProfile and bang off this variable. If this variable is set but my sessionStorage variables arent go ahead and reinitialize them. When user logs out window closes destroy this localStorage variable
Just from reading that i would have never understood that "$@"
expands into a list of separate parameters. Whereas, "$*"
is one parameter consisting of all the parameters added together.
If it still makes no sense do this.
http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/
I'm using IronPython here (same as .NET API) and reading the file as UTF-8 in order to properly handle the BOM fixed the problem for me:
xmlFile = Path.Combine(directory_str, 'file.xml')
doc = XPathDocument(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))
It would work as well with the XmlDocument
:
doc = XmlDocument()
doc.Load(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))
listView1.View = View.Details;
listView1.Columns.Add("Target No.", 83, HorizontalAlignment.Center);
listView1.Columns.Add(" Range ", 100, HorizontalAlignment.Center);
listView1.Columns.Add(" Azimuth ", 100, HorizontalAlignment.Center);
i also had same problem .. i drag column to left .. but now ok .. so let's say i have 283*196 size of listview ..... We declared in the column width -2 for auto width .. For fitting in the listview ,we can divide listview width into 3 parts (83,100,100) ...
Answering this for Ubuntu
users for reference.
Run command google-chrome --app-url "http://localhost/"
Replace your desired URL in the parameter.
You can get more options like incognito mode etc.
Run google-chrome --help
to see the options.
BrenBarn is correct. The error means you tried to do something like None[5]
. In the backtrace, it says self.imageDef=self.values[2]
, which means that your self.values
is None
.
You should go through all the functions that update self.values
and make sure you account for all the corner cases.
The examples above are a bit confusing, and this is probably the best way:
$.ajaxSetup({
headers: {
'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
}
});
I took the above from a combination of Rico and Yossi's answer.
I've added the following script as manage.sh
inside my Django project, it sources the virtualenv and then runs the manage.py
script with whatever arguments you pass to it. It makes it very easy in general to run commands inside the virtualenv (cron, systemd units, basically anywhere):
#! /bin/bash
# this is a convenience script that first sources the venv (assumed to be in
# ../venv) and then executes manage.py with whatever arguments you supply the
# script with. this is useful if you need to execute the manage.py from
# somewhere where the venv isn't sourced (e.g. system scripts)
# get the script's location
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
# source venv <- UPDATE THE PATH HERE WITH YOUR VENV's PATH
source $DIR/../venv/bin/activate
# run manage.py script
$DIR/manage.py "$@"
Then in your cron entry you can just run:
0 3 * * * /home/user/project/manage.sh command arg
Just remember that you need to make the manage.sh
script executable
def grade(inlist):
grade_1, grade_2, grade_3, average =inlist
print (grade_1)
print (grade_2)
mark=[1,2,3,4]
grade(mark)
I'am posting this answer because many visitors enter here from google for this problem.
string result = this.GetType().GetMethod("Print").Invoke(this, new object[]{"firstParam", 157, "third_Parammmm" } );
when external .dll -instead of this.GetType()
, you might use typeof(YourClass)
.
.a files are usually libraries which get statically linked (or more accurately archives), and
.so are dynamically linked libraries.
To do a port you will need the source code that was compiled to make them, or equivalent files on your AIX machine.
instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0;
once your window has scrolled pass a certain height:
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 135) {
$('#task_flyout').addClass('fixed');
} else {
$('#task_flyout').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
Request and response.
To understand the req
, try out console.log(req);
.
In my case (Dockerfile script to build an Android CI container - https://github.com/menny/docker_android), I had to do these steps:
mkdir ~/.android && touch ~/.android/repositories.cfg
yes | sdkmanager --licenses
sdkmanager "build-tools;26.0.0"
sdkmanager "platform-tools" "tools"
sdkmanager "platforms;android-26" "platforms;android-25" "platforms;android-24"
.....
sdkmanager --update
yes | sdkmanager --licenses
Two notes:
repositories.cfg
file or sdkmanager
would die.$_SERVER['HTTP_REFERER']
will give you the referrer page's URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they're not obliged to set the http_referer as well. You're missing all _
, is that a typo?
You can use git-copy to duplicate the repo with all histories.
git copy http://a.com/old.git http://a.com/new.git
You already have multiple answers to your question, but I would like to add another minor one here that might help to add something.
To view data structures in Perl you can use Data::Dumper
. To print a string you can use say
, which adds a newline character "\n"
after every call instead of adding it explicitly.
I usually use \s
which matches a whitespace character. If you add +
it matches one or more whitespace characters. You can read more about it here perlre
.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use feature 'say';
my $line = "file1.gz file2.gz file3.gz";
my @abc = split /\s+/, $line;
print Dumper \@abc;
say for @abc;
Just thought i'd share this with anyone who needs more clarity on how to achieve this:
myCanvas is a Canvas control and Parent to all other controllers. This code works to neatly resize to any resolution from 1366 x 768 upward. Tested up to 4k resolution 4096 x 2160
Take note of all the MainWindow property settings (WindowStartupLocation, SizeToContent and WindowState) - important for this to work correctly - WindowState for my user case requirement was Maximized
xaml
<Window x:Name="mainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyApp"
xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
x:Class="MyApp.MainWindow"
Title="MainWindow" SizeChanged="MainWindow_SizeChanged"
Width="1366" Height="768" WindowState="Maximized" WindowStartupLocation="CenterOwner" SizeToContent="WidthAndHeight">
<Canvas x:Name="myCanvas" HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1356">
<Image x:Name="maxresdefault_1_1__jpg" Source="maxresdefault-1[1].jpg" Stretch="Fill" Opacity="0.6" Height="767" Canvas.Left="-6" Width="1366"/>
<Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" Height="0" Canvas.Left="-811" Canvas.Top="148" Width="766"/>
<Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" HorizontalAlignment="Right" Width="210" Height="0" Canvas.Left="1653" Canvas.Top="102"/>
<Image x:Name="imgscroll" Source="BcaKKb47i[1].png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" Height="523" Canvas.Left="-3" Canvas.Top="122" Width="580">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="89.093"/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
.cs
private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
{
myCanvas.Width = e.NewSize.Width;
myCanvas.Height = e.NewSize.Height;
double xChange = 1, yChange = 1;
if (e.PreviousSize.Width != 0)
xChange = (e.NewSize.Width / e.PreviousSize.Width);
if (e.PreviousSize.Height != 0)
yChange = (e.NewSize.Height / e.PreviousSize.Height);
ScaleTransform scale = new ScaleTransform(myCanvas.LayoutTransform.Value.M11 * xChange, myCanvas.LayoutTransform.Value.M22 * yChange);
myCanvas.LayoutTransform = scale;
myCanvas.UpdateLayout();
}
If you're using typing (introduced in Python 3.5) you can use typing.Optional
, where Optional[X]
is equivalent to Union[X, None]
. It is used to signal that the explicit value of None
is allowed . From typing.Optional:
def foo(arg: Optional[int] = None) -> None:
...
For query: SELECT * FROM (SELECT id, product FROM product) as product
you can use:
$sub_query_from = '(SELECT id, product FROM product ) as product';
$this->db->select();
$this->db->from($sub_query_from);
$query = $this->db->get()
Please notice, that in sub_query_from string you must use spaces between ... product ) as...
I ended up creating my own plugin. Here it is in case this helps anyone:
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
Here's some sample code of how to use it:
<script type="text/javascript"><!--
jQuery(function($) {
$('.timer').countTo({
from: 50,
to: 2500,
speed: 1000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
//--></script>
<span class="timer"></span>
View the demo on JSFiddle: http://jsfiddle.net/YWn9t/
I quote VonC response, adding something.
Plus, there is Bug 206299 open to request using Ctrl+Tab for switching tabs instead of Ctrl+PgUp(PgDn).
If not satisfied, you can assign yourself the Key Binding, from Window > Preferences > General > Keys.
To me, it is better to put the transition codes with the original/minimum selectors than with the :hover or any other additional selectors:
#content #nav a {_x000D_
background-color: #FF0;_x000D_
_x000D_
-webkit-transition: background-color 1000ms linear;_x000D_
-moz-transition: background-color 1000ms linear;_x000D_
-o-transition: background-color 1000ms linear;_x000D_
-ms-transition: background-color 1000ms linear;_x000D_
transition: background-color 1000ms linear;_x000D_
}_x000D_
_x000D_
#content #nav a:hover {_x000D_
background-color: #AD310B;_x000D_
}
_x000D_
<div id="content">_x000D_
<div id="nav">_x000D_
<a href="#link1">Link 1</a>_x000D_
</div>_x000D_
</div>
_x000D_
I was also having a similar problem. Finally found one solution at https://techmeals.com/fe/questions/htmlcss/4/How-to-customize-the-select-drop-down-in-css-which-works-for-all-the-browsers
Note:
1) For Firefox support there is special CSS handling for SELECT element's parent, please take a closer look.
2) Download the down.png from Down.png
CSS code
/* For Firefox browser we need to style for SELECT element parent. */
@-moz-document url-prefix() {
/* Please note this is the parent of "SELECT" element */
.select-example {
background: url('https://techmeals.com/external/images/down.png');
background-color: #FFFFFF;
border: 1px solid #9e9e9e;
background-size: auto 6px;
background-repeat: no-repeat;
background-position: 96% 13px;
}
}
/* IE specific styles */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active)
{
select.my-select-box {
padding: 0 0 0 5px;
}
}
/* IE specific styles */
@supports (-ms-accelerator:true) {
select.my-select-box {
padding: 0 0 0 5px;
}
}
select.my-select-box {
outline: none;
background: #fff;
-moz-appearance: window;
-webkit-appearance: none;
border-radius: 0px;
text-overflow: "";
background-image: url('https://techmeals.com/external/images/down.png');
background-size: auto 6px;
background-repeat: no-repeat;
background-position: 96% 13px;
cursor: pointer;
height: 30px;
width: 100%;
border: 1px solid #9e9e9e;
padding: 0 15px 0 5px;
padding-right: 15px\9; /* This will be apllied only to IE 7, IE 8 and IE 9 as */
*padding-right: 15px; /* This will be apllied only to IE 7 and below. */
_padding-right: 15px; /* This will be apllied only to IE 6 and below. */
}
HTML code
<div class="select-example">
<select class="my-select-box">
<option value="1">First Option</option>
<option value="2">Second Option</option>
<option value="3">Third Option</option>
<option value="4">Fourth Option</option>
</select>
</div>
It seems that Xcode really likes to be in the Applications folder and be called Xcode, especially when using xcodebuild
(when building for Carthage for example) - and xcode-select
doesn't always seem to cut it.
I have a client project that's still using Swift 2.2, and I'm stuck on Xcode 7 for that and using Xcode 8 for anything else.
So, in my Applications folder, I have Xcode 7 (renamed to Xcode_7) and Xcode 8 (renamed to Xcode_8). Then I rename whichever one I need to simply Xcode, and back again when done. It's a ball-ache, but seems to work.
This shell script simplifies it a bit…
xcode-version.sh
cd /Applications
if [[ $1 = "-8" ]]
then
if [ -e Xcode_8.app ]
then
mv Xcode.app Xcode_7.app
mv Xcode_8.app Xcode.app
echo "Switched to Xcode 8"
else
echo "Already using Xcode 8"
fi
elif [[ $1 = "-7" ]]
then
if [ -e Xcode_7.app ]
then
mv Xcode.app Xcode_8.app
mv Xcode_7.app Xcode.app
echo "Switched to Xcode 7"
else
echo "Already using Xcode 7"
fi
else
echo "usage: xcode-version -7/8"
fi
xcode-select --switch Xcode.app
It's not that hard:
def escapeSpecialCharacters ( text, characters ):
for character in characters:
text = text.replace( character, '\\' + character )
return text
>>> escapeSpecialCharacters( 'I\'m "stuck" :\\', '\'"' )
'I\\\'m \\"stuck\\" :\\'
>>> print( _ )
I\'m \"stuck\" :\
In Swift 5, By using UILabel extensions to embed icon in leading as well as trailing side of the text as follows:-
extension UILabel {
func addTrailing(image: UIImage, text:String) {
let attachment = NSTextAttachment()
attachment.image = image
let attachmentString = NSAttributedString(attachment: attachment)
let string = NSMutableAttributedString(string: text, attributes: [:])
string.append(attachmentString)
self.attributedText = string
}
func addLeading(image: UIImage, text:String) {
let attachment = NSTextAttachment()
attachment.image = image
let attachmentString = NSAttributedString(attachment: attachment)
let mutableAttributedString = NSMutableAttributedString()
mutableAttributedString.append(attachmentString)
let string = NSMutableAttributedString(string: text, attributes: [:])
mutableAttributedString.append(string)
self.attributedText = mutableAttributedString
}
}
To use above mentioned code in your desired label as:-
Image in right of text then:-
statusLabel.addTrailing(image: UIImage(named: "rightTick") ?? UIImage(), text: " Verified ")
Image in left of text then:-
statusLabel.addLeading(image: UIImage(named: "rightTick") ?? UIImage(), text: " Verified ")
Output:-
Create Common Method to Convert String to Date format
public static void main(String[] args) throws Exception {
long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}
private static long ConvertStringToDate(String dateString, String format) {
try {
return new SimpleDateFormat(format).parse(dateString).getTime();
} catch (ParseException e) {}
return 0;
}
With an Android-powered device, you can develop and debug your Android applications just as you would on the emulator.
1. Declare your application as "debuggable" in AndroidManifest.xml
.
<application
android:debuggable="true"
... >
...
</application>
2. On your handset, navigate to Settings > Security and check Unknown sources
3. Go to Settings > Developer Options and check USB debugging
Note that if Developer Options
is invisible you will need to navigate to Settings > About Phone and tap on Build number
several times until you are notified that it has been unlocked.
4. Set up your system to detect your device.
Follow the instructions below for your OS:
Install the Google USB Driver from the ADT SDK Manager
(Support for: ADP1, ADP2, Verizon Droid, Nexus One, Nexus S).
For devices not listed above, install an OEM driver for your device
Your device should automatically work; Go to the next step
Add a udev
rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, click here. To set up device detection on Ubuntu Linux:
/etc/udev/rules.d/51-android.rules
.SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"
chmod a+r /etc/udev/rules.d/51-android.rules
Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.
5. Run the project with your connected device.
With Eclipse/ADT: run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the available emulator(s) and connected device(s).
With ADB: issue commands with the -d flag to target your connected device.
Still need help? Click here for the full guide.
Considering the String
you're asking about is
C:\Hello\AnotherFolder\The File Name.PDF
we need to extract everything after the last separator, ie. \
. That is what we are interested in.
You can do
String fullPath = "C:\\Hello\\AnotherFolder\\The File Name.PDF";
int index = fullPath.lastIndexOf("\\");
String fileName = fullPath.substring(index + 1);
This will retrieve the index of the last \
in your String
and extract everything that comes after it into fileName
.
If you have a String
with a different separator, adjust the lastIndexOf
to use that separator. (There's even an overload that accepts an entire String
as a separator.)
I've omitted it in the example above, but if you're unsure where the String
comes from or what it might contain, you'll want to validate that the lastIndexOf
returns a non-negative value because the Javadoc states it'll return
-1 if there is no such occurrence
DELETE only by using DOS command without any installation:
Create an empty folder "test" on C or D drive and use following DOS command
robocopy /MIR c:\test D:\UserData\FolderToDelete > NUL
After completing above command, your folder will be empty, now you can delete the folder.
Don't worry your test folder will always be empty, so you can delete it at any time.
Even more useful, if you have multiple parameters you can access any/all of them with:
_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
.Returns((string a, string b, string c) => string.Concat(a,b,c));
You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.
It seems that when this error appears it is an indication that the selenium-java plugin for maven is out-of-date.
Changing the version in the pom.xml should fix the problem
That is htmlFor in JSX and class is className in JSX
I saw a nested function technique for computing a weighted average on S.O. one time, altering that technique can solve your issue.
def group_weight(overall_size):
def inner(group):
return len(group)/float(overall_size)
inner.__name__ = 'weight'
return inner
d = {"my_label": pd.Series(['A','B','A','C','D','D','E'])}
df = pd.DataFrame(d)
print df.groupby('my_label').apply(group_weight(len(df)))
my_label
A 0.285714
B 0.142857
C 0.142857
D 0.285714
E 0.142857
dtype: float64
Here is how to do a weighted average within groups
def wavg(val_col_name,wt_col_name):
def inner(group):
return (group[val_col_name] * group[wt_col_name]).sum() / group[wt_col_name].sum()
inner.__name__ = 'wgt_avg'
return inner
d = {"P": pd.Series(['A','B','A','C','D','D','E'])
,"Q": pd.Series([1,2,3,4,5,6,7])
,"R": pd.Series([0.1,0.2,0.3,0.4,0.5,0.6,0.7])
}
df = pd.DataFrame(d)
print df.groupby('P').apply(wavg('Q','R'))
P
A 2.500000
B 2.000000
C 4.000000
D 5.545455
E 7.000000
dtype: float64
If you want to solve this without using Ajax, use the FileReader()
Web API.
Example implementation:
.csv
filefunction readSingleFile(e) {_x000D_
var file = e.target.files[0];_x000D_
if (!file) {_x000D_
return;_x000D_
}_x000D_
_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(e) {_x000D_
var contents = e.target.result;_x000D_
displayContents(contents);_x000D_
displayParsed(contents);_x000D_
};_x000D_
reader.readAsText(file);_x000D_
}_x000D_
_x000D_
function displayContents(contents) {_x000D_
var element = document.getElementById('file-content');_x000D_
element.textContent = contents;_x000D_
}_x000D_
_x000D_
function displayParsed(contents) {_x000D_
const element = document.getElementById('file-parsed');_x000D_
const json = contents.split(',');_x000D_
element.textContent = JSON.stringify(json);_x000D_
}_x000D_
_x000D_
document.getElementById('file-input').addEventListener('change', readSingleFile, false);
_x000D_
<input type="file" id="file-input" />_x000D_
_x000D_
<h3>Raw contents of the file:</h3>_x000D_
<pre id="file-content">No data yet.</pre>_x000D_
_x000D_
<h3>Parsed file contents:</h3>_x000D_
<pre id="file-parsed">No data yet.</pre>
_x000D_
Another related tip is to use "%~1" instead of "%1". Type "CALL /?" at the command line in Windows to get more details.
You can get the ID, or any other attribute, using jQuery's attrib function.
$('ul.art-vmenu li').attrib('id');
To get the menu text, which is in the t span, you can do this:
$('ul.art-vmenu li').children('span.t').html();
To change the HTML is just as easy:
$('ul.art-vmenu li').children('span.t').html("I'm different");
Of course, if you wanted to get all the span.t's in the first place, it would be simpler to do:
$('ul.art-vemnu li span.t').html();
But I'm assuming you've already got the li's, and want to use child() to find something within that element.
The Theme My Login plugin may help - it allows you to redirect users of specific roles to specific pages.
From @Johan La Rooy's solution, sorting the images using sorted(glob.glob('*.png'))
does not work for me, the output list is still not ordered by their names.
However, the sorted(glob.glob('*.png'), key=os.path.getmtime)
works perfectly.
I am a bit confused how can sorting by their names does not work here.
Thank @Martin Thoma for posting this great question and @Johan La Rooy for the helpful solutions.
document.location
is an object, while document.location.href
is a string. But the former has a toString
method, so you can read from it as if it was a string and get the same value as document.location.href
.
In some browsers - most modern ones, I think - you can also assign to document.location
as if it were a string. According to the Mozilla documentation however, it is better to use window.location
for this purpose as document.location
was originally read-only and so may not be as widely supported.
You can use
(get-item $scriptPath).Directoryname
to get the string path or if you want the Directory type use:
(get-item $scriptPath).Directory
If you want to have the ListView in an AppCompatActivity instead of ListActivity, you can do the following (Modifying @Shardul's answer):
public class ListViewDemoActivity extends AppCompatActivity {
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems=new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
//RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
int clickCounter=0;
private ListView mListView;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_list_view_demo);
if (mListView == null) {
mListView = (ListView) findViewById(R.id.listDemo);
}
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}
//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v) {
listItems.add("Clicked : "+clickCounter++);
adapter.notifyDataSetChanged();
}
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(R.id.listDemo);
}
return mListView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}
And in you layout instead of using android:id="@android:id/list"
you can use android:id="@+id/listDemo"
So now you can have a ListView
inside a normal AppCompatActivity
.
You are using an adjacent sibling selector (+
) when the elements are not siblings. The label is the parent of the input, not it's sibling.
CSS has no way to select an element based on it's descendents (nor anything that follows it).
You'll need to look to JavaScript to solve this.
Alternatively, rearrange your markup:
<input id="foo"><label for="foo">…</label>
It's the array that's causing trouble in:
void print_graph(g_node graph_node[], double weight[][], int nodes);
The second and subsequent dimensions must be given:
void print_graph(g_node graph_node[], double weight[][32], int nodes);
Or you can just give a pointer to pointer:
void print_graph(g_node graph_node[], double **weight, int nodes);
However, although they look similar, those are very different internally.
If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):
void fvla(int m, int C[m][m]); // valid: VLA with prototype scope
void fvla(int m, int C[m][m]) // valid: adjusted to auto pointer to VLA
{
typedef int VLA[m][m]; // valid: block scope typedef VLA
struct tag {
int (*y)[n]; // invalid: y not ordinary identifier
int z[n]; // invalid: z not ordinary identifier
};
int D[m]; // valid: auto VLA
static int E[m]; // invalid: static block scope VLA
extern int F[m]; // invalid: F has linkage and is VLA
int (*s)[m]; // valid: auto pointer to VLA
extern int (*r)[m]; // invalid: r has linkage and points to VLA
static int (*q)[m] = &B; // valid: q is a static block pointer to VLA
}
[...] In my main(), the variable I am trying to pass into the function is a
double array[][]
, so how would I pass that into the function? Passingarray[0][0]
into it gives me incompatible argument type, as does&array
and&array[0][0]
.
In your main()
, the variable should be:
double array[10][20];
or something faintly similar; maybe
double array[][20] = { { 1.0, 0.0, ... }, ... };
You should be able to pass that with code like this:
typedef struct graph_node
{
int X;
int Y;
int active;
} g_node;
void print_graph(g_node graph_node[], double weight[][20], int nodes);
int main(void)
{
g_node g[10];
double array[10][20];
int n = 10;
print_graph(g, array, n);
return 0;
}
That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:
/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c
Try using chown -R
on the var/lib/gems
directory, assigning ownership to the user [rubyusername
] in this example, the user that will be installing and developing with gems.
# chown -R rubyusername:rubyusername /var/lib/gems
This recursively changes everything under the gems directory. For extra security on multi-user systems, you can also create a group, rather than chowning the individual rubyusername, and add users to that group.
Just started using Lombok today. So far I like it, but one drawback I didn't see mentioned was refactoring support.
If you have a class annotated with @Data
, it will generate the getters and setters for you based on the field names. If you use one of those getters in another class, then decide the field is poorly named, it will not find usages of those getters and setters and replace the old name with the new name.
I would imagine this would have to be done via an IDE plug-in and not via Lombok.
UPDATE (Jan 22 '13)
After using Lombok for 3 months, I still recommend it for most projects. I did, however, find another drawback that is similar to the one listed above.
If you have a class, say MyCompoundObject.java
that has 2 members, both annotated with @Delegate
, say myWidgets
and myGadgets
, when you call myCompoundObject.getThingies()
from another class, it's impossible to know if it's delegating to the Widget
or Gadget
because you can no longer jump to source within the IDE.
Using the Eclipse "Generate Delegate Methods..." provides you with the same functionality, is just as quick and provides source jumping. The downside is it clutters your source with boilerplate code that take the focus off the important stuff.
UPDATE 2 (Feb 26 '13)
After 5 months, we're still using Lombok, but I have some other annoyances. The lack of a declared getter & setter can get annoying at times when you are trying to familiarize yourself with new code.
For example, if I see a method called getDynamicCols()
but I don't know what it's about, I have some extra hurdles to jump to determine the purpose of this method. Some of the hurdles are Lombok, some are the lack of a Lombok smart plugin. Hurdles include:
Outline
view, so I didn't see the methods. Lack of References search. If I want to see who's calling getDynamicCols(args...)
, I have to generate or code the setter to be able to search for references. UPDATE 3 (Mar 7 '13)
Learning to use the various ways of doing things in Eclipse I guess. You can actually set a conditional breakpoint (BP) on a Lombok generated method. Using the Outline
view, you can right-click the method to Toggle Method Breakpoint
. Then when you hit the BP, you can use the debugging Variables
view to see what the generated method named the parameters (usually the same as the field name) and finally, use the Breakpoints
view to right-click the BP and select Breakpoint Properties...
to add a condition. Nice.
UPDATE 4 (Aug 16 '13)
Netbeans doesn't like it when you update your Lombok dependencies in your Maven pom. The project still compiles, but files get flagged for having compilation errors because it can't see the methods Lombok is creating. Clearing the Netbeans cache resolves the issue. Not sure if there is a "Clean Project" option like there is in Eclipse. Minor issue, but wanted to make it known.
UPDATE 5 (Jan 17 '14)
Lombok doesn't always play nice with Groovy, or at least the groovy-eclipse-compiler
. You might have to downgrade your version of the compiler.
Maven Groovy and Java + Lombok
UPDATE 6 (Jun 26 '14)
A word of warning. Lombok is slightly addictive and if you work on a project where you can't use it for some reason, it will annoy the piss out of you. You may be better off just never using it at all.
UPDATE 7 (Jul 23 '14)
This is a bit of an interesting update because it directly addresses the safety of adopting Lombok that the OP asked about.
As of v1.14, the @Delegate
annotation has been demoted to an Experimental status. The details are documented on their site (Lombok Delegate Docs).
The thing is, if you were using this feature, your backout options are limited. I see the options as:
@Delegate
annotations and generate/handcode the delegate code. This is a little harder if you were using attributes within the annotation.@Delegate
annotation and maybe add back in the annotations that you do want.As far as I can tell, Delombok doesn't have an option to remove a subset of annotations; it's all or nothing at least for the context of a single file. I opened a ticket to request this feature with Delombok flags, but I wouldn't expect that in the near future.
UPDATE 8 (Oct 20 '14)
If it's an option for you, Groovy offers most of the same benefits of Lombok, plus a boat load of other features, including @Delegate. If you think you'll have a hard time selling the idea to the powers that be, take a look at the @CompileStatic
or @TypeChecked
annotation to see if that can help your cause. In fact, the primary focus of the Groovy 2.0 release was static safety.
UPDATE 9 (Sep 1 '15)
Lombok is still being actively maintained and enhanced, which bodes well to the safety level of adoption. The @Builder annotations is one of my favorite new features.
UPDATE 10 (Nov 17 '15)
This may not seem directly related to the OP's question, but worth sharing. If you're looking for tools to help you reduce the amount of boilerplate code you write, you can also check out Google Auto - in particular AutoValue. If you look at their slide deck, the list Lombok as a possible solution to the problem they are trying to solve. The cons they list for Lombok are:
I'm not sure how much I agree with their evaluation. And given the cons of AutoValue that are documented in the slides, I'll be sticking with Lombok (if Groovy is not an option).
UPDATE 11 (Feb 8 '16)
I found out Spring Roo has some similar annotations. I was a little surprised to find out Roo is still a thing and finding documentation for the annotations is a bit rough. Removal also doesn't look as easy as de-lombok. Lombok seems like the safer choice.
UPDATE 12 (Feb 17 '16)
While trying to come up with justifications for why it's safe to bring in Lombok for the project I'm currently working on, I found a piece of gold that was added with v1.14
- The Configuration System! This is means you can configure a project to dis-allow certain features that your team deems unsafe or undesirable. Better yet, it can also create directory specific config with different settings. This is AWESOME.
UPDATE 13 (Oct 4 '16)
If this kind of thing matters to you, Oliver Gierke felt it was safe to add Lombok to Spring Data Rest.
UPDATE 14 (Sep 26 '17)
As pointed out by @gavenkoa in the comments on the OPs question, JDK9 compiler support isn't yet available (Issue #985). It also sounds like it's not going to be an easy fix for the Lombok team to get around.
UPDATE 15 (Mar 26 '18)
The Lombok changelog indicates as of v1.16.20 "Compiling lombok on JDK1.9 is now possible" even though #985 is still open.
Changes to accommodate JDK9, however, necessitated some breaking changes; all isolated to changes in config defaults. It's a little concerning that they introduced breaking changes, but the version only bumped the "Incremental" version number (going from v1.16.18 to v1.16.20). Since this post was about the safety, if you had a yarn/npm
like build system that automatically upgraded to the latest incremental version, you might be in for a rude awakening.
UPDATE 16 (Jan 9 '19)
It seems the JDK9 issues have been resolved and Lombok works with JDK10, and even JDK11 as far as I can tell.
One thing I noticed though that was concerning from a safety aspect is the fact that the change log going from v1.18.2 to v1.18.4 lists two items as BREAKING CHANGE
!? I'm not sure how a breaking change happens in a semver "patch" update. Could be an issue if you use a tool that auto-updates patch versions.
In my case I need to set VERIFYHOST
and VERIFYPEER
to false
, like this:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
before the call to curl_exec($ch)
.
Because i am working between two development environments with self-assigned certificates.
With valid certificates there is no need to set VERIFYHOST
and VERIFYPEER
to false
because the curl_exec($ch)
method will work and return the response you expect.
Timer.Elapsed
expects method of specific signature (with arguments object
and EventArgs
). If you want to use your PlayMusicEvent
method with additional argument evaluated during event registration, you can use lambda expression as an adapter:
myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));
Edit: you can also use shorter version:
myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);
if(checkBox.getAttribute("checked") != null) // if Checked
checkBox.click(); //to Uncheck it
You can also add an and
statement to be sure if checked is true.
Put the title in its own span.
<span id="dialog_title_span">'+dialog_title+'</span>
$('#dialog_title_span').text("new dialog title");
Besides the answer given above, I just want to add that this error can also occur while importing data with incorrect lines terminated character.
For example I save the dump file in csv format in windows. then while importing
LOAD DATA INFILE '/path_to_csv_folder/db.csv' INTO TABLE table1
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;
Windows saved end of line as \r\n (i.e. CF LF) where as I was using \n. I was getting crazy why phpMyAdmin was able to import the file while I couldn't. Only when I open the file in notepadd++ and saw the end of file then I realized that mysql was unable to find any lines terminated symbol (and I guess it consider all the lines as input to the field; making it complain.)
Anyway after making from \n to \r\n; it work like a charm.
LOAD DATA INFILE '/path_to_csv_folder/db.csv' INTO TABLE table1
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;
When I installed nodemon using : npm install nodemon -g --save
, my path for the global npm packages was not present in the PATH variable .
If you just add it to the $PATH variable it will get fixed.
Edit the ~/.bashrc
file in your home folder and add this line :-
export PATH=$PATH:~/npm
Here "npm" is the path to my global npm packages . Replace it with the global path in your system
You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates
subfolder):
@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)
Or if this is not the case simply:
@Html.Partial("nameOfPartial", Model)
Encoding.Unicode
is Microsoft's misleading name for UTF-16 (a double-wide encoding, used in the Windows world for historical reasons but not used by anyone else). http://msdn.microsoft.com/en-us/library/system.text.encoding.unicode.aspx
If you inspect your bytes
array, you'll see that every second byte is 0x00
(because of the double-wide encoding).
You should be using Encoding.UTF8.GetBytes
instead.
But also, you will see different results depending on whether or not you consider the terminating '\0'
byte to be part of the data you're hashing. Hashing the two bytes "Hi"
will give a different result from hashing the three bytes "Hi"
. You'll have to decide which you want to do. (Presumably you want to do whichever one your friend's PHP code is doing.)
For ASCII text, Encoding.UTF8
will definitely be suitable. If you're aiming for perfect compatibility with your friend's code, even on non-ASCII inputs, you'd better try a few test cases with non-ASCII characters such as é
and ?
and see whether your results still match up. If not, you'll have to figure out what encoding your friend is really using; it might be one of the 8-bit "code pages" that used to be popular before the invention of Unicode. (Again, I think Windows is the main reason that anyone still needs to worry about "code pages".)
For the record, I like Job's answer above but I'm curious about a solution just using the variable name by itself in a "do-nothing" statement:
void foo(int x) {
x; /* unused */
...
}
Sure, this has drawbacks; for instance, without the "unused" note it looks like a mistake rather than an intentional line of code.
The benefit is that no DEFINE is needed and it gets rid of the warning.
Are there any performance, optimization, or other differences?
If you want specifically do something when click on close button exactly like you described:
<a href="#" class="btn close_link" data-dismiss="modal">Close</a>
you need to attach an event using css selector:
$(document).on('click', '[data-dismiss="modal"]', function(){what you want to do})
But if you want to do something when modal close, you can use the already wrote tips
I guess this has been solved by now but still the best thing to do here is to send the token with your form
{!! csrf_field() !!}
and then in your ajax
$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
url: "test",
type:"POST",
data: { '_token': token, 'someOtherData': someOtherData },
success:function(data){
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
I found this here:
On windows (win xp), the parent process will not finish until the longtask.py
has finished its work. It is not what you want in CGI-script. The problem is not specific to Python, in PHP community the problems are the same.
The solution is to pass DETACHED_PROCESS
Process Creation Flag to the underlying CreateProcess
function in win API. If you happen to have installed pywin32 you can import the flag from the win32process module, otherwise you should define it yourself:
DETACHED_PROCESS = 0x00000008
pid = subprocess.Popen([sys.executable, "longtask.py"],
creationflags=DETACHED_PROCESS).pid
According to my perspective, the main difference between script and program:
Scripts can be used with the other technologies. Example: PHP scripts, Javascripts, etc. can be used within HTML.
Programs are stand-alone chunks of code that can never be embedded into the other technologies.
If I am wrong at any place please correct me.I will admire your correction.
import tensorflow as tf
import numpy as np
def softmax(x):
return (np.exp(x).T / np.exp(x).sum(axis=-1)).T
logits = np.array([[1, 2, 3], [3, 10, 1], [1, 2, 5], [4, 6.5, 1.2], [3, 6, 1]])
sess = tf.Session()
print(softmax(logits))
print(sess.run(tf.nn.softmax(logits)))
sess.close()
This is similar to CommonsWare answer but with a minor tweak: android:gravity="top|start"
. Complete code example:
<EditText
android:id="@+id/EditText02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lines="5"
android:gravity="top|start"
android:inputType="textMultiLine"
android:scrollHorizontally="false"
/>
$(document).ready(
function()
{
$("input:checkbox").change(
function()
{
if( $(this).is(":checked") )
{
$("#formName").submit();
}
}
)
}
);
Though it would probably be better to add classes to each of the checkboxes and do
$(".checkbox_class").change();
so that you can choose which checkboxes submit the form instead of all of them doing it.
You can use COM, or P/Invoke from .Net, to open the Winspool.drv driver and send bytes directly to devices. But you don't want to do that; this typically works only for the one device on the one version of the one driver you test with, and breaks on everything else. Take this from long, painful, personal experience.
What you want to do is get a barcode font or library that draws barcodes using plain old GDI or GDI+ commands; there's one for .Net here. This works on all devices, even after Zebra changes the driver.
Here is a bit specific example, I would like to show. Say you have many duplicate entries in some of your rows. If you have string entries you could easily use string methods to find all indexes to drop.
ind_drop = df[df['column_of_strings'].apply(lambda x: x.startswith('Keyword'))].index
And now to drop those rows using their indexes
new_df = df.drop(ind_drop)
WebView browser = (WebView) findViewById(R.id.webview);
browser.getSettings().setLoadWithOverviewMode(true);
browser.getSettings().setUseWideViewPort(true);
browser.getSettings().setMinimumFontSize(40);
This works great for me since the text size has been set to really small by .setLoadWithOverViewMode and .setUseWideViewPort.
You can use in your vimrc
those commands:
set ignorecase
- All your searches will be case insensitiveset smartcase
- Your search will be case sensitive if it contains an uppercase letterYou need to set ignorecase
if you want to use what smartcase
provides.
I wrote recently an article about Vim search commands (both built in command and the best plugins to search efficiently).
Try
SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]')
FROM traptabclob;
Here is a sqlfiddle demo
I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
# the inbox. You can change that number to reference
# any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content
One thing you need to keep in mind is the size of your data set. I believe that Dillie-O was the only one who even remotely hit the point.
If you have a small, single user, consumer app then I would say DB. I have a DVD management app that uses the file system (in Program Files at that) and it is a PIA to backup. I wish EVERY time that they would store them in a db, and let me choose where to save that file.
For a larger commercial application then I would start to change my thinking. I used to work for a company that developed the county clerks information management application. We would store the images on disk, in an encoded format [to deal with FS problems with large numbers of files] based on the county assigned instrument number. This was useful on another front as the image could exist before the DB record (due to their workflow).
As with most things: 'It depends on what you are doing'
I had got the same CORS error while working on a Vue.js project. You can resolve this either by building a proxy server or another way would be to disable the security settings of your browser (eg, CHROME) for accessing cross origin apis (this is temporary solution & not the best way to solve the issue). Both these solutions had worked for me. The later solution does not require any mock server or a proxy server to be build. Both these solutions can be resolved at the front end.
You can disable the chrome security settings for accessing apis out of the origin by typing the below command on the terminal:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --user-data-dir="/tmp/chrome_dev_session" --disable-web-security
After running the above command on your terminal, a new chrome window with security settings disabled will open up. Now, run your program (npm run serve / npm run dev) again and this time you will not get any CORS error and would be able to GET request using axios.
Hope this helps!
You can create a a method and pass paramters to it and get the json as a response.
private JSONObject jsonResult(String Name,int id, String curriculum) throws JSONException {
JSONObject json = null;
json = new JSONObject("{\"" + "Name" + "\":" + "\"" + Name+ "\""
+ "," + "\"" + "Id" + "\":" + id + "," + "\"" + "Curriculum"
+ "\":" + "\"" + curriculum+ "\"" + "}");
return json;
}
I hope this will help you.
I've a PHP library which helps to insert array into MySQL Database. By using this you can create update and delete. Your array key value should be same as the table column value. Just using a single line code for the create operation
DB::create($db, 'YOUR_TABLE_NAME', $dataArray);
where $db is your Database connection.
Similarly, You can use this for update and delete. Select operation will be available soon. Github link to download : https://github.com/pairavanvvl/crud
Can't you just use a Definite Assignment Assertion? (See https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions)
i.e. declaring the property as makes!: any[];
The ! assures typescript that there definitely will be a value at runtime.
Sorry I haven't tried this in angular but it worked great for me when I was having the exact same problem in React.
You could use two separate configs. One as the input with optional properties (that will have default values), and another with only the required properties. This can be made convenient with &
and Required
:
interface DefaultedFuncConfig {
b?: boolean;
}
interface MandatoryFuncConfig {
a: boolean;
}
export type FuncConfig = MandatoryFuncConfig & DefaultedFuncConfig;
export const func = (config: FuncConfig): Required<FuncConfig> => ({
b: true,
...config
});
// will compile
func({ a: true });
func({ a: true, b: true });
// will error
func({ b: true });
func({});
Right click on a photo and open in a new tab/window. Right click on inspect element
. Search for:
instagram://media?id=
This will give you:
instagram://media?id=############# /// the ID
The full id construct from
photoID_userID
To get the user id, search for:
instapp:owner_user_id Will be in content=
Recently I had the same problem when using htmlTable() (‘htmlTable’ package) and I found a simpler solution: convert the data frame to a matrix with as.matrix():
htmlTable(as.matrix(df))
And be sure that the rownames are just indices. as.matrix() conservs the same columnames. That's it.
Following the comment of @DMR, I did't notice that htmlTable()
has the parameter rnames = FALSE
for cases like this. So a better answer would be:
htmlTable(df, rnames = FALSE)
You have to stop the current process and run your new one. In Eclipse, you can press this button to ReLaunch your application:
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
I solve such queries using this pattern:
SELECT *
FROM t
WHERE t.field=(
SELECT MAX(t.field)
FROM t AS t0
WHERE t.group_column1=t0.group_column1
AND t.group_column2=t0.group_column2 ...)
That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:
WITH site_history AS (
SELECT sites.siteName, sites.siteIP, history.date
FROM sites
JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
SELECT MAX(date)
FROM site_history h0
WHERE h.siteName=h0.siteName)
ORDER BY siteName
It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date
field should be unique for each siteName
, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history
table has an unique index for (site, date)
, this query is also very fast, index range scan on the history
table scanning just the first item can be used.
The general form of the syntax is
<protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish> | #semver:<semver>]
which means for your case it will be
npm install git+ssh://[email protected]/visionmedia/express.git
From npmjs docs:
npm install :
Installs the package from the hosted git provider, cloning it with git. For a full git remote url, only that URL will be attempted.
<protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish>
| #semver:] is one of git, git+ssh, git+http, git+https, or git+file.
If # is provided, it will be used to clone exactly that commit. If the commit-ish has the format #semver:, can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither # or
semver: is specified, then master is used.
If the repository makes use of submodules, those submodules will be cloned as well.
If the package being installed contains a prepare script, its dependencies and devDependencies will be installed, and the prepare script will be run, before the package is packaged and installed.
The following git environment variables are recognized by npm and will be added to the environment when running git:
- GIT_ASKPASS
- GIT_EXEC_PATH
- GIT_PROXY_COMMAND
- GIT_SSH
- GIT_SSH_COMMAND
- GIT_SSL_CAINFO GIT_SSL_NO_VERIFY
See the git man page for details.
Examples:
npm install git+ssh://[email protected]:npm/npm.git#v1.0.27 npm install git+ssh://[email protected]:npm/npm#semver:^5.0 npm install git+https://[email protected]/npm/npm.git npm install git://github.com/npm/npm.git#v1.0.27 GIT_SSH_COMMAND='ssh -i ~/.ssh/custom_ident' npm install git+ssh://[email protected]:npm/npm.git npm install
Are you looking for a particular extension? In your phpinfo();
, just hit Ctrl+F in your web browser, type in the first 3-4 letters of the extension you're looking for, and it should show you whether or not its loaded.
Usually in phpinfo()
it doesn't show you all the loaded extensions in one location, it has got a separate section for each loaded extension where it shows all of its variables, file paths, etc, so if there is no section for your extension name it probably means it isn't loaded.
Alternatively you can open your php.ini file and use the Ctrl+F method to find your extension, and see if its been commented out (usually by a semicolon near the start of the line).
public class MyObject implements Cloneable, Serializable{
@Override
@SuppressWarnings(value = "unchecked")
protected MyObject clone(){
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
ByteArrayOutputStream bOs = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bOs);
oos.writeObject(this);
ois = new ObjectInputStream(new ByteArrayInputStream(bOs.toByteArray()));
return (MyObject)ois.readObject();
} catch (Exception e) {
//Some seriouse error :< //
return null;
}finally {
if (oos != null)
try {
oos.close();
} catch (IOException e) {
}
if (ois != null)
try {
ois.close();
} catch (IOException e) {
}
}
}
}
Too late for the party here is the approch without converting to string
x=0
k=len(a)-1
for i in a:
x+=(10**k)*i
k-=1
JavaScript Code
function ctrl($scope){
$scope.call={state:['second','first','nothing','Never', 'Gonna', 'Give', 'You', 'Up']}
$scope.whatClassIsIt= function(someValue){
if(someValue=="first")
return "ClassA"
else if(someValue=="second")
return "ClassB";
else
return "ClassC";
}
}
To avoid all the Oracle mess of not knowing where it is looking for the TNSNAMES.ORA (I have the added confusion of multiple Oracle versions and 32/64 bit), you can copy the setting from your existing TNSNAMES.ORA to your own config file and use that for your connection.
Say you're happy with the 'DSDSDS' reference in TNSNAMES.ORA which maps to something like:
DSDSDS=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=DSDSDSHost)(Port=4521)))(CONNECT_DATA=(SERVICE_NAME=DSDSDSService)))
string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=DSDSDSHost)(Port=4521)))(CONNECT_DATA=(SERVICE_NAME=DSDSDSService)));User Id=UNUNUN;Password=PWPWPW;";
Now, with EF Core you can convert data type transparently in your AppDbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// i.e. Store TimeSpan as string (custom)
modelBuilder
.Entity<YourClass>()
.Property(x => x.YourTimeSpan)
.HasConversion(
timeSpan => timeSpan.ToString(), // To DB
timeSpanString => TimeSpan.Parse(timeSpanString) // From DB
);
// i.e. Store TimeSpan as string (using TimeSpanToStringConverter)
modelBuilder
.Entity<YourClass>()
.Property(x => x.YourTimeSpan)
.HasConversion(new TimeSpanToStringConverter());
// i.e. Store TimeSpan as number of ticks (custom)
modelBuilder
.Entity<YourClass>()
.Property(x => x.YourTimeSpan)
.HasConversion(
timeSpan => timeSpan.Ticks, // To DB
timeSpanString => TimeSpan.FromTicks(timeSpanString) // From DB
);
// i.e. Store TimeSpan as number of ticks (using TimeSpanToTicksConverter)
modelBuilder
.Entity<YourClass>()
.Property(x => x.YourTimeSpan)
.HasConversion(new TimeSpanToTicksConverter());
}
I use a variation of one of the answers here. I want to replace spaces with "-" so its SEO friendly and also make lower case. Also not reference system.web from my services layer.
private string MakeUrlString(string input)
{
var array = input.ToCharArray();
array = Array.FindAll<char>(array, c => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-');
var newString = new string(array).Replace(" ", "-").ToLower();
return newString;
}
This error occurred for me when using window.location.reload()
. Replacing with window.location = window.location.href
solved the problem.