Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
@Jonathan Leffler: Thank you. Your solution works.
A complete working example:
/** compile-time dispatch
$ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
*/
#include <stdio.h>
#define QUOTE(name) #name
#define STR(macro) QUOTE(macro)
#ifndef TEST_FUN
# define TEST_FUN some_func
#endif
#define TEST_FUN_NAME STR(TEST_FUN)
void some_func(void)
{
printf("some_func() called\n");
}
void another_func(void)
{
printf("do something else\n");
}
int main(void)
{
TEST_FUN();
printf("TEST_FUN_NAME=%s\n", TEST_FUN_NAME);
return 0;
}
Example:
$ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
do something else
TEST_FUN_NAME=another_func
You get this error because a class which has no constructor has a default constructor, which is argument-less and is equivalent to the following code:
public ACSubClass() {
super();
}
However since your BaseClass declares a constructor (and therefore doesn't have the default, no-arg constructor that the compiler would otherwise provide) this is illegal - a class that extends BaseClass can't call super();
because there is not a no-argument constructor in BaseClass.
This is probably a little counter-intuitive because you might think that a subclass automatically has any constructor that the base class has.
The simplest way around this is for the base class to not declare a constructor (and thus have the default, no-arg constructor) or have a declared no-arg constructor (either by itself or alongside any other constructors). But often this approach can't be applied - because you need whatever arguments are being passed into the constructor to construct a legit instance of the class.
Or one can simply use: $('#myElem').valid()
if ($('#myElem').valid()){
// will also trigger unobtrusive validation only for this element if in place
// add your extra logic here to execute only when element is valid
}
Note that validate()
needs to be called on the form before checking it using this method.
Documentation link: https://jqueryvalidation.org/valid/
Declare a variable in component.ts and initialize it to some value
buttonDisabled: boolean;
ngOnInit() {
this.buttonDisabled = false;
}
Now in .html or in the template, you can put following code:
<button disabled="{{buttonDisabled}}"> Click Me </button>
Now you can enable/disable button by changing value of buttonDisabled
variable.
You can use this code.It may help you:
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int count=0;
String[] wCount=str1.split(" ");
for(int i=0;i<wCount.length;i++){
if(!wCount[i].isEmpty())
{
count++;
}
}
System.out.println(count);
}
The click will affect a label if we have one attached to the input checkbox?
I think that is better to use the .change() function
<input type="checkbox" id="something" />
$("#something").change( function(){
alert("state changed");
});
If you are stuck on django 1.2 like I am and RedirectView doesn't exist, another route-centric way to add the redirect mapping is using:
(r'^match_rules/$', 'django.views.generic.simple.redirect_to', {'url': '/new_url'}),
You can also re-route everything on a match. This is useful when changing the folder of an app but wanting to preserve bookmarks:
(r'^match_folder/(?P<path>.*)', 'django.views.generic.simple.redirect_to', {'url': '/new_folder/%(path)s'}),
This is preferable to django.shortcuts.redirect if you are only trying to modify your url routing and do not have access to .htaccess, etc (I'm on Appengine and app.yaml doesn't allow url redirection at that level like an .htaccess).
For swift change navigation bar color:
self.navigationController?.navigationBar.barTintColor = UIColor.red
change title font,size, color:
self.title = "title"
self.navigationController?.navigationBar.titleTextAttributes = [
NSAttributedString.Key.foregroundColor : UIColor.white,
NSAttributedString.Key.font : UIFont(name: "Futura", size: 30)!
]
hibernate-distribution-3.6.10.Final\lib\jpa : Add this jar to solve the issue. It is present in lib folder inside that you have a folder called jpa ---> inside that you have hibernate-jpa-2.0-1.0.1.Final jar
Find complete example of Spring Mvc Validation
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.technicalkeeda.bean.Login;
public class LoginValidator implements Validator {
public boolean supports(Class aClass) {
return Login.class.equals(aClass);
}
public void validate(Object obj, Errors errors) {
Login login = (Login) obj;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName",
"username.required", "Required field");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userPassword",
"userpassword.required", "Required field");
}
}
public class LoginController extends SimpleFormController {
private LoginService loginService;
public LoginController() {
setCommandClass(Login.class);
setCommandName("login");
}
public void setLoginService(LoginService loginService) {
this.loginService = loginService;
}
@Override
protected ModelAndView onSubmit(Object command) throws Exception {
Login login = (Login) command;
loginService.add(login);
return new ModelAndView("loginsucess", "login", login);
}
}
In Chrome 8 the path is always 'C:\fakepath\' with the correct file name.
Create a C# class that maps to your Json and use Newsoft JsonConvert
to Deserialise it.
For example:
public Class MyResponse
{
public Meta Meta { get; set; }
public Response Response { get; set; }
}
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
Well, according to Google's lectures (maybe here, I don't remember) , you should consider using Fragments whenever it's possible, as it makes your code easier to maintain and control.
However, I think that on some cases it can get too complex, as the activity that hosts the fragments need to navigate/communicate between them.
I think you should decide by yourself what's best for you. It's usually not that hard to convert an activity to a fragment and vice versa.
I've created a post about this dillema here, if you wish to read some further.
Michael has given a very comprehensive answer, but I'd like to point out a few things which you can still do to be able to use grids in IE in a nearly painless way.
repeat
functionality is supportedYou can still use the repeat functionality, it's just hiding behind a different syntax. Instead of writing repeat(4, 1fr)
, you have to write (1fr)[4]
. That's it.
See this series of articles for the current state of affairs: https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/
Grid gaps are supported in all browsers except IE. So you can use the @supports
at-rule to set the grid-gaps conditionally for all new browsers:
Example:
.grid {
display: grid;
}
.item {
margin-right: 1rem;
margin-bottom: 1rem;
}
@supports (grid-gap: 1rem) {
.grid {
grid-gap: 1rem;
}
.item {
margin-right: 0;
margin-bottom: 0;
}
}
It's a little verbose, but on the plus side, you don't have to give up grids altogether just to support IE.
I can't stress this enough - half the pain of grids is solved just be using autoprefixer in your build step. Write your CSS in a standards-complaint way, and just let autoprefixer do it's job transforming all older spec properties automatically. When you decide you don't want to support IE, just change one line in the browserlist config and you'll have removed all IE-specific code from your built files.
I have a angular 5 + spring boot app(application.properties 1.3+) with help of compression(link attached below) was able to reduce the size of main.bundle.ts size from 2.7 MB to 530 KB.
Also by default --aot and --build-optimizer are enabled with --prod mode you need not specify those separately.
The difference decreases for smaller arguments to range(..)
/ xrange(..)
:
$ python -m timeit "for i in xrange(10111):" " for k in range(100):" " pass"
10 loops, best of 3: 59.4 msec per loop
$ python -m timeit "for i in xrange(10111):" " for k in xrange(100):" " pass"
10 loops, best of 3: 46.9 msec per loop
In this case xrange(100)
is only about 20% more efficient.
However, I disagree the official definition of Guide to naming conventions on groupId, artifactId, and version which proposes the groupId must start with a reversed domain name you control.
com
means this project belongs to a company, and org
means this project belongs to a social organization. These are alright, but for those strange domain like xxx.tv, xxx.uk, xxx.cn, it does not make sense to name the groupId started with "tv.","cn.", the groupId should deliver the basic information of the project rather than the domain.
Your problem may be solved if you give your div
a fixed width, as follows:
div#thing {
position: absolute;
top: 0px;
z-index: 2;
width:400px;
margin-left:-200px;
left:50%;
}
The error message is so vague, for me I had this code:
var streamReader = new StreamReader(response.GetResponseStream());
var xmlSerializer = new XmlSerializer(typeof(aResponse));
theResponse = (bResponse) xmlSerializer.Deserialize(streamReader);
Notice xmlSerializer is instantiated with aResponse but on deserializing I accidentally casted it to bResonse.
Update Mar 20, 2017 for Swift 3 syntax:
If you don't care whether the optional method exists, just call delegate?.optionalMethod?()
Otherwise, using guard
is probably the best approach:
weak var delegate: SomeDelegateWithOptionals?
func someMethod() {
guard let method = delegate?.optionalMethod else {
// optional not implemented
alternativeMethod()
return
}
method()
}
Original answer:
You can use the "if let" approach to test an optional protocol like this:
weak var delegate: SomeDelegateWithOptionals?
func someMethod() {
if let delegate = delegate {
if let theMethod = delegate.theOptionalProtocolMethod? {
theMethod()
return
}
}
// Reaching here means the delegate doesn't exist or doesn't respond to the optional method
alternativeMethod()
}
So, in an ideal world you'd have a spec for all pages in your site. You would also have a test infrastructure that could hit all your pages to test them.
You're presumably not in an ideal world. Why not do this...?
Create a mapping between the well known old URLs and the new ones. Redirect when you see an old URL. I'd possibly consider presenting a "this page has moved, it's new url is XXX, you'll be redirected shortly".
If you have no mapping, present a "sorry - this page has moved. Here's a link to the home page" message and redirect them if you like.
Log all redirects - especially the ones with no mapping. Over time, add mappings for pages that are important.
Running Visual Studio Code as Administrator should do the trick.
If you're on Windows you can:
Make sure you have all other instances of VS Code closed and then try to run as Administrator. The electron framework likes to stall processes when closing them so it's best to check your task manager and kill the remaining processes.
Related Changes in CodebaseIf for some weird reason this is not running your commands as an Administrator you can try the runas
command. Microsoft: runas command
runas /user:Administrator myCommand
runas "/user:First Last" "my command"
This should cover all major types:
public class ViewBagUtils
{
public static string ToJavascriptValue(dynamic val)
{
if (val == null) return "null";
if (val is string) return val;
if (val is bool) return val.ToString().ToLower();
if (val is DateTime) return val.ToString();
if (double.TryParse(val.ToString(), out double dval)) return dval.ToString();
throw new ArgumentException("Could not convert value.");
}
}
And in your .cshtml file inside the <script>
tag:
@using Namespace_Of_ViewBagUtils
const someValue = @ViewBagUtils.ToJavascriptValue(ViewBag.SomeValue);
Note that for string values, you'll have to use the @ViewBagUtils
expression inside single (or double) quotes, like so:
const someValue = "@ViewBagUtils.ToJavascriptValue(ViewBag.SomeValue)";
Taken From www.regular-expressions.info
Greediness: Greedy quantifiers first tries to repeat the token as many times as possible, and gradually gives up matches as the engine backtracks to find an overall match.
Laziness: Lazy quantifier first repeats the token as few times as required, and gradually expands the match as the engine backtracks through the regex to find an overall match.
JDBC does not support named parameters. Unless you are bound to using plain JDBC (which causes pain, let me tell you that) I would suggest to use Springs Excellent JDBCTemplate which can be used without the whole IoC Container.
NamedParameterJDBCTemplate supports named parameters, you can use them like that:
NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("name", name);
paramSource.addValue("city", city);
jdbcTemplate.queryForRowSet("SELECT * FROM customers WHERE name = :name AND city = :city", paramSource);
Thanks for the question, and the solution using the Array.indexOf method.
I used the code from this solution to create a inList() function that would, IMO, make the writing simpler and the reading clearer:
function inList(psString, psList)
{
var laList = psList.split(',');
var i = laList.length;
while (i--) {
if (laList[i] === psString) return true;
}
return false;
}
USAGE:
if (inList('Houston', 'LA,New York,Houston') {
// THEN do something when your string is in the list
}
In particular if you need recursive clone
GIT_SSL_NO_VERIFY=true git clone --recursive https://github.com/xx/xx.git
Using dplyr you can:
df <- df %>% dplyr:: select(grep("ABC", names(df)), grep("XYZ", names(df)))
If you don't want to use NPOI.Mapper, then I'd advise you to check out this solution - it handles reading excel cell into various type and also has a simple import helper: https://github.com/hidegh/NPOI.Extensions
var data = sheet.MapTo<OrderDetails>(true, rowMapper =>
{
// map singleItem
return new OrderDetails()
{
Date = rowMapper.GetValue<DateTime>(SheetColumnTitles.Date),
// use reusable mapper for re-curring scenarios
Region = regionMapper(rowMapper.GetValue<string>(SheetColumnTitles.Region)),
Representative = rowMapper.GetValue<string>(SheetColumnTitles.Representative),
Item = rowMapper.GetValue<string>(SheetColumnTitles.Item),
Units = rowMapper.GetValue<int>(SheetColumnTitles.Units),
UnitCost = rowMapper.GetValue<decimal>(SheetColumnTitles.UnitCost),
Total = rowMapper.GetValue<decimal>(SheetColumnTitles.Total),
// read date and total as string, as they're displayed/formatted on the excel
DateFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Date),
TotalFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Total)
};
});
The order in which the classes appear in the html element does not matter, what counts is the order in which the blocks appear in the style sheet.
In your case .smallbox-paysummary
is defined after .smallbox
hence the 10px precedence.
Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.
Sometimes a prototype in some place add an extra element.
This is along the lines of Lawrence Wenham's answer, but depending on your use case, it may or may not be an improvement -- you don't need the setters.
public interface IPerson {
int GetAge();
string GetName();
}
public interface IGetPerson {
IPerson GetPerson();
}
public static class IGetPersonAdditions {
public static int GetAgeViaPerson(this IGetPerson getPerson) { // I prefer to have the "ViaPerson" in the name in case the object has another Age property.
IPerson person = getPerson.GetPersion();
return person.GetAge();
}
public static string GetNameViaPerson(this IGetPerson getPerson) {
return getPerson.GetPerson().GetName();
}
}
public class Person: IPerson, IGetPerson {
private int Age {get;set;}
private string Name {get;set;}
public IPerson GetPerson() {
return this;
}
public int GetAge() { return Age; }
public string GetName() { return Name; }
}
Now any object that knows how to get a person can implement IGetPerson, and it will automatically have the GetAgeViaPerson() and GetNameViaPerson() methods. From this point, basically all Person code goes into IGetPerson, not into IPerson, other than new ivars, which have to go into both. And in using such code, you don't have to be concerned about whether or not your IGetPerson object is itself actually an IPerson.
Is there any disadvantages/consequences of pushing empty commits?
Aside from the extreme confusion someone might get as to why there's a bunch of commits with no content in them on master, not really.
You can change the commit that you pushed to remote, but the sha1 of the commit (basically it's id number) will change permanently, which alters the source tree -- You'd then have to do a git push -f
back to remote.
DON'T DO THIS IN PRODUCTION
The answer given by @ravi-luthra technically works but it has some issues!
In my case, I was just trying to recover disk space. The lib/docker/overlay
folder was taking 30GB of space and I only run a few containers regularly. Looks like docker has some issue with data leakage and some of the temporary data are not cleared when the container stops.
So I went ahead and deleted all the contents of lib/docker/overlay
folder. After that, My docker instance became un-useable. When I tried to run or build any container, It gave me this error:
failed to create rwlayer: symlink ../04578d9f8e428b693174c6eb9a80111c907724cc22129761ce14a4c8cb4f1d7c/diff /var/lib/docker/overlay2/l/C3F33OLORAASNIYB3ZDATH2HJ7: no such file or directory
Then with some trial and error, I solved this issue by running
(WARNING: This will delete all your data inside docker volumes)
docker system prune --volumes -a
So It is not recommended to do such dirty clean ups unless you completely understand how the system works.
I get this fairly regularily. Currently what's working for me (with Photon) is:
If this doesn't work :
I know, stupid isn't it.
GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH
. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:
export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH
Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).
Depends on the database as each database has a different way to add sequence numbers. I would alter the table to add the column then write a db script in groovy/python/etc to read in the data and update the id with a sequence. Once the data has been set, I would add a sequence to the table that starts after the top number. Once the data has been set, set the primary keys correctly.
You can simply use named constructors for creating different types of buttons with icons. For instance
FlatButton.icon(onPressed: null, icon: null, label: null);
RaisedButton.icon(onPressed: null, icon: null, label: null);
But if you have specfic requirements then you can always create custom button with different layouts or simply wrap a widget in GestureDetector.
select * from messages group by name desc
A former project of mine was going to use freely downloadable data from EODData.
If you dont want to hard-code the cell addresses you can use the ROW()
function.
eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))
Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.
You can use unirest, It provides easy method to post request. `
import unirest
def callback(response):
print "code:"+ str(response.code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "body:"+ str(response.body)
print "******************"
print "raw_body:"+ str(response.raw_body)
# consume async post request
def consumePOSTRequestASync():
params = {'test1':'param1','test2':'param2'}
# we need to pass a dummy variable which is open method
# actually unirest does not provide variable to shift between
# application-x-www-form-urlencoded and
# multipart/form-data
params['dummy'] = open('dummy.txt', 'r')
url = 'http://httpbin.org/post'
headers = {"Accept": "application/json"}
# call get service with headers and params
unirest.post(url, headers = headers,params = params, callback = callback)
# post async request multipart/form-data
consumePOSTRequestASync()
If you want to center your windows during runtime use the code below, copy it into your application:
protected void ReallyCenterToScreen()
{
Screen screen = Screen.FromControl(this);
Rectangle workingArea = screen.WorkingArea;
this.Location = new Point() {
X = Math.Max(workingArea.X, workingArea.X + (workingArea.Width - this.Width) / 2),
Y = Math.Max(workingArea.Y, workingArea.Y + (workingArea.Height - this.Height) / 2)};
}
And finally call the method above to get it working:
ReallyCenterToScreen();
The simplest solution that I can think of is using Properties class.
Saving the map:
Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
for (Map.Entry<String,String> entry : ldapContent.entrySet()) {
properties.put(entry.getKey(), entry.getValue());
}
properties.store(new FileOutputStream("data.properties"), null);
Loading the map:
Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(new FileInputStream("data.properties"));
for (String key : properties.stringPropertyNames()) {
ldapContent.put(key, properties.get(key).toString());
}
EDIT:
if your map contains plaintext values, they will be visible if you open file data via any text editor, which is not the case if you serialize the map:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(ldapContent);
out.close();
EDIT2:
instead of for loop (as suggested by OldCurmudgeon) in saving example:
properties.putAll(ldapContent);
however, for the loading example this is the best that can be done:
ldapContent = new HashMap<Object, Object>(properties);
std::map
takes up to four template type arguments, the third one being a comparator. E.g.:
struct cmpByStringLength {
bool operator()(const std::string& a, const std::string& b) const {
return a.length() < b.length();
}
};
// ...
std::map<std::string, std::string, cmpByStringLength> myMap;
Alternatively you could also pass a comparator to map
s constructor.
Note however that when comparing by length you can only have one string of each length in the map as a key.
An implementation of Iterable
is one that provides an Iterator
of itself:
public interface Iterable<T>
{
Iterator<T> iterator();
}
An iterator is a simple way of allowing some to loop through a collection of data without assignment privileges (though with ability to remove).
public interface Iterator<E>
{
boolean hasNext();
E next();
void remove();
}
See Javadoc.
With jQuery
you can use
$('#main-div .specific-class').length
otherwise in VanillaJS (from IE8
included) you may use
document.querySelectorAll('#main-div .specific-class').length;
This will allow you to pipe the output of your useless.sh
script through a command such as sed
and save the stderr
in a variable named error
. The result of the pipe is sent to stdout
for display or to be piped into another command.
It sets up a couple of extra file descriptors to manage the redirections needed in order to do this.
#!/bin/bash
exec 3>&1 4>&2 #set up extra file descriptors
error=$( { ./useless.sh | sed 's/Output/Useless/' 2>&4 1>&3; } 2>&1 )
echo "The message is \"${error}.\""
exec 3>&- 4>&- # release the extra file descriptors
It looks like you are trying to use (almost) straight up C code here. Go has a few differences.
const
. The term const
has a different meaning in Go, as it does in C. The list should be defined as var
instead.basenameOpts
as opposed to basename_opts
.char
type in Go. You probably want byte
(or rune
if you intend to allow unicode codepoints).var x = foo
.For example:
type opt struct {
shortnm byte
longnm, help string
needArg bool
}
var basenameOpts = []opt {
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a",
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
An alternative is to declare the list with its type and then use an init
function to fill it up. This is mostly useful if you intend to use values returned by functions in the data structure. init
functions are run when the program is being initialized and are guaranteed to finish before main
is executed. You can have multiple init
functions in a package, or even in the same source file.
type opt struct {
shortnm byte
longnm, help string
needArg bool
}
var basenameOpts []opt
func init() {
basenameOpts = []opt{
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a",
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
}
Since you are new to Go, I strongly recommend reading through the language specification. It is pretty short and very clearly written. It will clear a lot of these little idiosyncrasies up for you.
Here is how I did it:
This was easier for me than trying to figure out the specific regex necessary.
int indexPictureData = result.IndexOf("-PictureData:");
int indexIdentity = result.IndexOf("-Identity:");
string returnValue = result.Remove(indexPictureData + 13);
returnValue = returnValue + " [bytecoderemoved] " + result.Remove(0, indexIdentity); `
Have you thought about using mouseOver and mouseOut to simulate this. Also look into mouseEnter and mouseLeave
I've done most things you are proposing with Java compiler and bytecode and solved the problem in the past. It's been almost 1 month since I ran my Java code (and back then everything was fixed), but now the problem appeared again. Don't know why, pretty annoyed though!
This time the solution was: Right click to project name -> Open module settings F4 -> Language level ...and there you can define the language level your project/pc is.
No maven/pom configuration worked for me both in the past and now and I've already set the Java compiler and bytecode at 12.
YouTube Help says that &autoplay=1
has to be after the video ID - I assume, immediately after.
<?php header("Access-Control-Allow-Origin: http://example.com"); ?>
This command disables only first console warning info
Result: console result
To specify a directory to search for (binary) libraries, you just use -L
:
-L/data[...]/lib
To specify the actual library name, you use -l
:
-lfoo # (links libfoo.a or libfoo.so)
To specify a directory to search for include files (different from libraries!) you use -I
:
-I/data[...]/lib
So I think what you want is something like
g++ -g -Wall -I/data[...]/lib testing.cpp fileparameters.cpp main.cpp -o test
These compiler flags (amongst others) can also be found at the GNU GCC Command Options manual:
Reinstall everything??? no way! just add the path to SDK tools and platform tools in your classpath from Environment Variables.
Then restart Eclipse.
other way go to Devices -> Reset adb
, or simply open the task manager and kill the adb.exe
process.
There are many ways to do this:
Go to current File once:
Visual Studio 2013
VS 13 has it's own shortcut to do this: Ctrl+\, S (Press Ctrl + \, Release both keys, Press the S key)
You can edit this default shortcut, if you are searching for SolutionExplorer.SyncWithActiveDocument
in your Keyboard Settings
(Tools->Options->Enviornment->Keyboard)
In addition there is also a new icon in the Solution Explorer, more about this here.
Visual Studio 2012
If you use VS 2012, there is a great plugin to add this new functionality from VS2013 to VS2012: . The default shortcut is strg + alt + ü. I think this one is the best, as navigating to the solution explorer is mapped to strg + ü.
Resharper
If you use Resharper try Shift+Alt+L
This is a nice mapping as you can use Strg+Alt+L for navigating to the solution explorer
Track current file all the time:
Visual Studio >= 2012:
If you like to track your current file in the solution explorer all the time, you can use the solution from the accepted answer (Tools->Options->Projects and Solutions->Track Active Item in Solution Explorer), but I think this can get very annoying in large projects.
I was frustrated trying to connect my Android App to my RESTful service using https. Also I was a bit annoyed about all the answers that suggested to disable certificate checking altogether. If you do so, whats the point of https?
After googled about the topic for a while, I finally found this solution where external jars are not needed, just Android APIs. Thanks to Andrew Smith, who posted it on July, 2014
/**
* Set up a connection to myservice.domain using HTTPS. An entire function
* is needed to do this because myservice.domain has a self-signed certificate.
*
* The caller of the function would do something like:
* HttpsURLConnection urlConnection = setUpHttpsConnection("https://littlesvr.ca");
* InputStream in = urlConnection.getInputStream();
* And read from that "in" as usual in Java
*
* Based on code from:
* https://developer.android.com/training/articles/security-ssl.html#SelfSigned
*/
public static HttpsURLConnection setUpHttpsConnection(String urlString)
{
try
{
// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// My CRT file that I put in the assets folder
// I got this file by following these steps:
// * Go to https://littlesvr.ca using Firefox
// * Click the padlock/More/Security/View Certificate/Details/Export
// * Saved the file as littlesvr.crt (type X.509 Certificate (PEM))
// The MainActivity.context is declared as:
// public static Context context;
// And initialized in MainActivity.onCreate() as:
// MainActivity.context = getApplicationContext();
InputStream caInput = new BufferedInputStream(MainActivity.context.getAssets().open("littlesvr.crt"));
Certificate ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL(urlString);
HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
return urlConnection;
}
catch (Exception ex)
{
Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
return null;
}
}
It worked nice for my mockup App.
you can use this code:
$("body").css("overflow", "hidden");
First I would verify that your project's generated information isn't corrupt. Do a clean and rebuild on your solution.
If that doesn't help, one thing I've seen work in the past for designer issues is opening up a windows forms project, then closing it again. This is a little chicken-entrails-ish, though, so don't hold your breath.
I Have Been suffering from same thing since long time. It specially happens when you're connected to remote server(Which might be slow), or you have poor network connection. I doubt if Microsoft knows what the right answer is.
But since I've tried to find the solution. Only 1 layman approach worked
"The query is currently executing. Do you want to cancel the query?"
Click on "Yes"
After a while it will ask to whether you want to save this query or not?
Click on "Cancel"
And post that, may be you're studio is stable again to execute your query.
What it does in background is disconnecting your query window with the connection. So for running the query again, it will take time for connecting the remote server again. But trust me this trade-off is far better than the suffering of seeing that timer which runs for eternity.
PS: This works for me, Kudos if works for you too. !!!
To close ajax fancybox window, use this:
onclick event -> $.fancybox.close();
return false;
I think using cal_info() is the easiest way to convert from number to string.
$monthNum = sprintf("%02s", $result["month"]); //Returns `08`
$monthName = cal_info(0); //Returns Gregorian (Western) calendar array
$monthName = $monthName[months][$monthNum];
echo $monthName; //Returns "August"
See the docs for cal_info()
Here's a modification of the accepted answer to provide more functionality.
RangeCollection.cs:
public class RangeCollection<T> : ObservableCollection<T>
{
#region Members
/// <summary>
/// Occurs when a single item is added.
/// </summary>
public event EventHandler<ItemAddedEventArgs<T>> ItemAdded;
/// <summary>
/// Occurs when a single item is inserted.
/// </summary>
public event EventHandler<ItemInsertedEventArgs<T>> ItemInserted;
/// <summary>
/// Occurs when a single item is removed.
/// </summary>
public event EventHandler<ItemRemovedEventArgs<T>> ItemRemoved;
/// <summary>
/// Occurs when a single item is replaced.
/// </summary>
public event EventHandler<ItemReplacedEventArgs<T>> ItemReplaced;
/// <summary>
/// Occurs when items are added to this.
/// </summary>
public event EventHandler<ItemsAddedEventArgs<T>> ItemsAdded;
/// <summary>
/// Occurs when items are removed from this.
/// </summary>
public event EventHandler<ItemsRemovedEventArgs<T>> ItemsRemoved;
/// <summary>
/// Occurs when items are replaced within this.
/// </summary>
public event EventHandler<ItemsReplacedEventArgs<T>> ItemsReplaced;
/// <summary>
/// Occurs when entire collection is cleared.
/// </summary>
public event EventHandler<ItemsClearedEventArgs<T>> ItemsCleared;
/// <summary>
/// Occurs when entire collection is replaced.
/// </summary>
public event EventHandler<CollectionReplacedEventArgs<T>> CollectionReplaced;
#endregion
#region Helper Methods
/// <summary>
/// Throws exception if any of the specified objects are null.
/// </summary>
private void Check(params T[] Items)
{
foreach (T Item in Items)
{
if (Item == null)
{
throw new ArgumentNullException("Item cannot be null.");
}
}
}
private void Check(IEnumerable<T> Items)
{
if (Items == null) throw new ArgumentNullException("Items cannot be null.");
}
private void Check(IEnumerable<IEnumerable<T>> Items)
{
if (Items == null) throw new ArgumentNullException("Items cannot be null.");
}
private void RaiseChanged(NotifyCollectionChangedAction Action)
{
this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
#endregion
#region Bulk Methods
/// <summary>
/// Adds the elements of the specified collection to the end of this.
/// </summary>
public void AddRange(IEnumerable<T> NewItems)
{
this.Check(NewItems);
foreach (var i in NewItems) this.Items.Add(i);
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
this.OnItemsAdded(new ItemsAddedEventArgs<T>(NewItems));
}
/// <summary>
/// Adds variable IEnumerable<T> to this.
/// </summary>
/// <param name="List"></param>
public void AddRange(params IEnumerable<T>[] NewItems)
{
this.Check(NewItems);
foreach (IEnumerable<T> Items in NewItems) foreach (T Item in Items) this.Items.Add(Item);
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
//TO-DO: Raise OnItemsAdded with combined IEnumerable<T>.
}
/// <summary>
/// Removes the first occurence of each item in the specified collection.
/// </summary>
public void Remove(IEnumerable<T> OldItems)
{
this.Check(OldItems);
foreach (var i in OldItems) Items.Remove(i);
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
OnItemsRemoved(new ItemsRemovedEventArgs<T>(OldItems));
}
/// <summary>
/// Removes all occurences of each item in the specified collection.
/// </summary>
/// <param name="itemsToRemove"></param>
public void RemoveAll(IEnumerable<T> OldItems)
{
this.Check(OldItems);
var set = new HashSet<T>(OldItems);
var list = this as List<T>;
int i = 0;
while (i < this.Count) if (set.Contains(this[i])) this.RemoveAt(i); else i++;
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
OnItemsRemoved(new ItemsRemovedEventArgs<T>(OldItems));
}
/// <summary>
/// Replaces all occurences of a single item with specified item.
/// </summary>
public void ReplaceAll(T Old, T New)
{
this.Check(Old, New);
this.Replace(Old, New, false);
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
this.OnItemReplaced(new ItemReplacedEventArgs<T>(Old, New));
}
/// <summary>
/// Clears this and adds specified collection.
/// </summary>
public void ReplaceCollection(IEnumerable<T> NewItems, bool SupressEvent = false)
{
this.Check(NewItems);
IEnumerable<T> OldItems = new List<T>(this.Items);
this.Items.Clear();
foreach (T Item in NewItems) this.Items.Add(Item);
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
this.OnReplaced(new CollectionReplacedEventArgs<T>(OldItems, NewItems));
}
private void Replace(T Old, T New, bool BreakFirst)
{
List<T> Cloned = new List<T>(this.Items);
int i = 0;
foreach (T Item in Cloned)
{
if (Item.Equals(Old))
{
this.Items.Remove(Item);
this.Items.Insert(i, New);
if (BreakFirst) break;
}
i++;
}
}
/// <summary>
/// Replaces the first occurence of a single item with specified item.
/// </summary>
public void Replace(T Old, T New)
{
this.Check(Old, New);
this.Replace(Old, New, true);
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
this.OnItemReplaced(new ItemReplacedEventArgs<T>(Old, New));
}
#endregion
#region New Methods
/// <summary>
/// Removes a single item.
/// </summary>
/// <param name="Item"></param>
public new void Remove(T Item)
{
this.Check(Item);
base.Remove(Item);
OnItemRemoved(new ItemRemovedEventArgs<T>(Item));
}
/// <summary>
/// Removes a single item at specified index.
/// </summary>
/// <param name="i"></param>
public new void RemoveAt(int i)
{
T OldItem = this.Items[i]; //This will throw first if null
base.RemoveAt(i);
OnItemRemoved(new ItemRemovedEventArgs<T>(OldItem));
}
/// <summary>
/// Clears this.
/// </summary>
public new void Clear()
{
IEnumerable<T> OldItems = new List<T>(this.Items);
this.Items.Clear();
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
this.OnCleared(new ItemsClearedEventArgs<T>(OldItems));
}
/// <summary>
/// Adds a single item to end of this.
/// </summary>
/// <param name="t"></param>
public new void Add(T Item)
{
this.Check(Item);
base.Add(Item);
this.OnItemAdded(new ItemAddedEventArgs<T>(Item));
}
/// <summary>
/// Inserts a single item at specified index.
/// </summary>
/// <param name="i"></param>
/// <param name="t"></param>
public new void Insert(int i, T Item)
{
this.Check(Item);
base.Insert(i, Item);
this.OnItemInserted(new ItemInsertedEventArgs<T>(Item, i));
}
/// <summary>
/// Returns list of T.ToString().
/// </summary>
/// <returns></returns>
public new IEnumerable<string> ToString()
{
foreach (T Item in this) yield return Item.ToString();
}
#endregion
#region Event Methods
private void OnItemAdded(ItemAddedEventArgs<T> i)
{
if (this.ItemAdded != null) this.ItemAdded(this, new ItemAddedEventArgs<T>(i.NewItem));
}
private void OnItemInserted(ItemInsertedEventArgs<T> i)
{
if (this.ItemInserted != null) this.ItemInserted(this, new ItemInsertedEventArgs<T>(i.NewItem, i.Index));
}
private void OnItemRemoved(ItemRemovedEventArgs<T> i)
{
if (this.ItemRemoved != null) this.ItemRemoved(this, new ItemRemovedEventArgs<T>(i.OldItem));
}
private void OnItemReplaced(ItemReplacedEventArgs<T> i)
{
if (this.ItemReplaced != null) this.ItemReplaced(this, new ItemReplacedEventArgs<T>(i.OldItem, i.NewItem));
}
private void OnItemsAdded(ItemsAddedEventArgs<T> i)
{
if (this.ItemsAdded != null) this.ItemsAdded(this, new ItemsAddedEventArgs<T>(i.NewItems));
}
private void OnItemsRemoved(ItemsRemovedEventArgs<T> i)
{
if (this.ItemsRemoved != null) this.ItemsRemoved(this, new ItemsRemovedEventArgs<T>(i.OldItems));
}
private void OnItemsReplaced(ItemsReplacedEventArgs<T> i)
{
if (this.ItemsReplaced != null) this.ItemsReplaced(this, new ItemsReplacedEventArgs<T>(i.OldItems, i.NewItems));
}
private void OnCleared(ItemsClearedEventArgs<T> i)
{
if (this.ItemsCleared != null) this.ItemsCleared(this, new ItemsClearedEventArgs<T>(i.OldItems));
}
private void OnReplaced(CollectionReplacedEventArgs<T> i)
{
if (this.CollectionReplaced != null) this.CollectionReplaced(this, new CollectionReplacedEventArgs<T>(i.OldItems, i.NewItems));
}
#endregion
#region RangeCollection
/// <summary>
/// Initializes a new instance.
/// </summary>
public RangeCollection() : base() { }
/// <summary>
/// Initializes a new instance from specified enumerable.
/// </summary>
public RangeCollection(IEnumerable<T> Collection) : base(Collection) { }
/// <summary>
/// Initializes a new instance from specified list.
/// </summary>
public RangeCollection(List<T> List) : base(List) { }
/// <summary>
/// Initializes a new instance with variable T.
/// </summary>
public RangeCollection(params T[] Items) : base()
{
this.AddRange(Items);
}
/// <summary>
/// Initializes a new instance with variable enumerable.
/// </summary>
public RangeCollection(params IEnumerable<T>[] Items) : base()
{
this.AddRange(Items);
}
#endregion
}
Events Classes:
public class CollectionReplacedEventArgs<T> : ReplacedEventArgs<T>
{
public CollectionReplacedEventArgs(IEnumerable<T> Old, IEnumerable<T> New) : base(Old, New) { }
}
public class ItemAddedEventArgs<T> : EventArgs
{
public T NewItem;
public ItemAddedEventArgs(T t)
{
this.NewItem = t;
}
}
public class ItemInsertedEventArgs<T> : EventArgs
{
public int Index;
public T NewItem;
public ItemInsertedEventArgs(T t, int i)
{
this.NewItem = t;
this.Index = i;
}
}
public class ItemRemovedEventArgs<T> : EventArgs
{
public T OldItem;
public ItemRemovedEventArgs(T t)
{
this.OldItem = t;
}
}
public class ItemReplacedEventArgs<T> : EventArgs
{
public T OldItem;
public T NewItem;
public ItemReplacedEventArgs(T Old, T New)
{
this.OldItem = Old;
this.NewItem = New;
}
}
public class ItemsAddedEventArgs<T> : EventArgs
{
public IEnumerable<T> NewItems;
public ItemsAddedEventArgs(IEnumerable<T> t)
{
this.NewItems = t;
}
}
public class ItemsClearedEventArgs<T> : RemovedEventArgs<T>
{
public ItemsClearedEventArgs(IEnumerable<T> Old) : base(Old) { }
}
public class ItemsRemovedEventArgs<T> : RemovedEventArgs<T>
{
public ItemsRemovedEventArgs(IEnumerable<T> Old) : base(Old) { }
}
public class ItemsReplacedEventArgs<T> : ReplacedEventArgs<T>
{
public ItemsReplacedEventArgs(IEnumerable<T> Old, IEnumerable<T> New) : base(Old, New) { }
}
public class RemovedEventArgs<T> : EventArgs
{
public IEnumerable<T> OldItems;
public RemovedEventArgs(IEnumerable<T> Old)
{
this.OldItems = Old;
}
}
public class ReplacedEventArgs<T> : EventArgs
{
public IEnumerable<T> OldItems;
public IEnumerable<T> NewItems;
public ReplacedEventArgs(IEnumerable<T> Old, IEnumerable<T> New)
{
this.OldItems = Old;
this.NewItems = New;
}
}
Note: I did not manually raise OnCollectionChanged
in the base methods because it appears only to be possible to create a CollectionChangedEventArgs
using the Reset
action. If you try to raise OnCollectionChanged
using Reset
for a single item change, your items control will appear to flicker, which is something you want to avoid.
Use PropertyInfo.PropertyType
to get the type of the property.
public bool ValidateData(object data)
{
foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
{
if (propertyInfo.PropertyType == typeof(string))
{
string value = propertyInfo.GetValue(data, null);
if value is not OK
{
return false;
}
}
}
return true;
}
With Java 8 Optional
:
for (Object object : Optional.ofNullable(someList).orElse(Collections.emptyList())) {
// do whatever
}
require
loads a file from the $LOAD_PATH
. If you want to require a file relative to the currently executing file instead of from the $LOAD_PATH
, use require_relative
.
I went the way of jQuery's .parseXML()
however found that the XML path syntax of 'Page[Name="test"] > controls > test'
wouldn't work (if anyone knows why please shout out!).
Instead I chained together the individual .find()
results into something that looked like this:
$xmlDoc.find('Page[Name="test"]')
.find('contols')
.find('test')
The result achieves the same as what I would expect the one shot find.
MobileSafari supports the orientationchange
event on the window
object. Unfortunately there doesn't seem to be a way to directly control the zoom via JavaScript. Perhaps you could dynamically write/change the meta
tag which controls the viewport — but I doubt that would work, it only affects the initial state of the page. Perhaps you could use this event to actually resize your content using CSS. Good luck!
This may be created sql injection point "SQL Injection Piggy-backed Queries". attackers able to append multiple malicious sql statements. so do not append user inputs directly to the queries.
Security considerations
The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.
// MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
More info:
I created a script to ignore differences in line endings:
It will display the files which are not added to the commit list and were modified (after ignoring differences in line endings). You can add the argument "add" to add those files to your commit.
#!/usr/bin/perl
# Usage: ./gitdiff.pl [add]
# add : add modified files to git
use warnings;
use strict;
my ($auto_add) = @ARGV;
if(!defined $auto_add) {
$auto_add = "";
}
my @mods = `git status --porcelain 2>/dev/null | grep '^ M ' | cut -c4-`;
chomp(@mods);
for my $mod (@mods) {
my $diff = `git diff -b $mod 2>/dev/null`;
if($diff) {
print $mod."\n";
if($auto_add eq "add") {
`git add $mod 2>/dev/null`;
}
}
}
Source code: https://github.com/lepe/scripts/blob/master/gitdiff.pl
Updates:
Basic Authentication use base 64 Encoding for generating cryptographic string which contains the information of username and password.
Digest Access Authentication uses the hashing methodologies to generate the cryptographic result
You should really use a set based solution involving two queries (basic insert):
INSERT INTO TableB (Id2Column, Column33, Column44)
SELECT id, column1, column2 FROM TableA
UPDATE TableA SET column1 = column2 * column3
And for your transform:
INSERT INTO TableB (Id2Column, Column33, Column44)
SELECT
id,
column1 * column4 * 100,
(column2 / column12)
FROM TableA
UPDATE TableA SET column1 = column2 * column3
Now if your transform is more complicated than that and involved multiple tables, post another question with the details.
I can't comment on @omega's comment because I don't have enough reputation but the answer to that question should be something like:
shake.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="100" <!-- how long the animation lasts -->
android:fromDegrees="-5" <!-- how far to swing left -->
android:pivotX="50%" <!-- pivot from horizontal center -->
android:pivotY="50%" <!-- pivot from vertical center -->
android:repeatCount="10" <!-- how many times to swing back and forth -->
android:repeatMode="reverse" <!-- to make the animation go the other way -->
android:toDegrees="5" /> <!-- how far to swing right -->
Class.java
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
view.startAnimation(shake);
This is just one way of doing what you want, there may be better methods out there.
The easiest way I can think of is the following:
<?php
$selection = array('PHP', 'ASP');
echo '<select>
<option value="0">Please Select Option</option>';
foreach ($selection as $selection) {
$selected = ($options == $selection) ? "selected" : "";
echo '<option '.$selected.' value="'.$selection.'">'.$selection.'</option>';
}
echo '</select>';
The code basically places all of your options in an array which are called upon in the foreach loop. The loop checks to see if your $options variable matches the current selection it's on, if it's a match then $selected will = selected, if not then it is set as blank. Finally the option tag is returned containing the selection from the array and if that particular selection is equal to your $options variable, it's set as the selected option.
>>> def is_near_integer(n, precision=8, get_integer=False):
... if get_integer:
... return int(round(n, precision))
... else:
... return round(n) == round(n, precision)
...
>>> print(is_near_integer(10648 ** (1.0/3)))
True
>>> print(is_near_integer(10648 ** (1.0/3), get_integer=True))
22
>>> for i in [4.9, 5.1, 4.99, 5.01, 4.999, 5.001, 4.9999, 5.0001, 4.99999, 5.000
01, 4.999999, 5.000001]:
... print(i, is_near_integer(i, 4))
...
4.9 False
5.1 False
4.99 False
5.01 False
4.999 False
5.001 False
4.9999 False
5.0001 False
4.99999 True
5.00001 True
4.999999 True
5.000001 True
>>>
If you want happen to be using LESS it can be achieved like so:
li {
.glyphicon-ok();
&:before {
.glyphicon();
margin-left:-25px;
float:left;
}
}
It exists because it is more convenient to use, also it is a whole different ideology using attributes to mark the authorization parameters rather than xml configuration. It wasn't meant to beat general purpose config or any other authorization frameworks, just MVC's way of doing it. I'm saying this, because it seems you are looking for a technical feature advantages which are probably non... just superb convenience.
BobRock already listed the advantages. Just to add to his answer, another scenarios are that you can apply this attribute to whole controller, not just actions, also you can add different role authorization parameters to different actions in same controller to mix and match.
You cannot 'alter' the property syntax this way. What you can do is this:
class Foo
{
string MyProperty { get; set; } // auto-property with inaccessible backing field
}
and a generic version would look like this:
class Foo<T>
{
T MyProperty { get; set; }
}
The Java virtual machine is organized into three generations: a young generation, an old generation, and a permanent generation. Most objects are initially allocated in the young generation. The old generation contains objects that have survived some number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.
Take a look at this JQuery plugin:
It adds vertical (fixed header row) or horizontal (fixed first column) scrolling to an existing HTML table. There is a demo you can check for both cases of scrolling.
You are right in what you write in the edit of your question.
After running DBCC CHECKIDENT('TableName', RESEED, 0)
:
- Newly created tables will start with identity 0
- Existing tables will continue with identity 1
The solution is in the script below, it's sort of a poor-mans-truncate :)
-- Remove all records from the Table
DELETE FROM TableName
-- Use sys.identity_columns to see if there was a last known identity value
-- for the Table. If there was one, the Table is not new and needs a reset
IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'TableName' AND last_value IS NOT NULL)
DBCC CHECKIDENT (TableName, RESEED, 0);
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
With a few setup steps you can easily deploy changes to your website using a one-liner like
git push production
Which is nice and simple, and you don't have to log into the remote server and do a pull or anything. Note that this will work best if you don't use your production checkout as a working branch! (The OP was working within a slightly different context, and I think @Robert Gould's solution addressed it well. This solution is more appropriate for deployment to a remote server.)
First you need to set up a bare repository somewhere on your server, outside of your webroot.
mkdir mywebsite.git
cd mywebsite.git
git init --bare
Then create file hooks/post-receive
:
#!/bin/sh
GIT_WORK_TREE=/path/to/webroot/of/mywebsite git checkout -f
And make the file executable:
chmod +x hooks/post-receive
On your local machine,
git remote add production [email protected]:mywebsite.git
git push production +master:refs/heads/master
All set! Now in the future you can use git push production
to deploy your changes!
Credit for this solution goes to http://sebduggan.com/blog/deploy-your-website-changes-using-git/. Look there for a more detailed explanation of what's going on.
You need to create a new Window class. You can design that then any way you want. You can create and show a window modally like this:
MyWindow popup = new MyWindow();
popup.ShowDialog();
You can add a custom property for your result value, or if you only have two possible results ( + possibly undeterminate, which would be null
), you can set the window's DialogResult
property before closing it and then check for it (it is the value returned by ShowDialog()
).
All of the above did not work for me, but a rebuild of the rpm database, with the following command, did:
sudo rpm --rebuilddb
Thanks all for the help.
As of .NET Core 2.0, the constructor Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
now exists.
The device pixel ratio is the ratio between physical pixels and logical pixels. For instance, the iPhone 4 and iPhone 4S report a device pixel ratio of 2, because the physical linear resolution is double the logical linear resolution.
The formula is:
Where:
is the physical linear resolution
and:
is the logical linear resolution
Other devices report different device pixel ratios, including non-integer ones. For example, the Nokia Lumia 1020 reports 1.6667, the Samsumg Galaxy S4 reports 3, and the Apple iPhone 6 Plus reports 2.46 (source: dpilove). But this does not change anything in principle, as you should never design for any one specific device.
The CSS "pixel" is not even defined as "one picture element on some screen", but rather as a non-linear angular measurement of viewing angle, which is approximately of an inch at arm's length. Source: CSS Absolute Lengths
This has lots of implications when it comes to web design, such as preparing high-definition image resources and carefully applying different images at different device pixel ratios. You wouldn't want to force a low-end device to download a very high resolution image, only to downscale it locally. You also don't want high-end devices to upscale low resolution images for a blurry user experience.
If you are stuck with bitmap images, to accommodate for many different device pixel ratios, you should use CSS Media Queries to provide different sets of resources for different groups of devices. Combine this with nice tricks like background-size: cover
or explicitly set the background-size
to percentage values.
#element { background-image: url('lores.png'); }
@media only screen and (min-device-pixel-ratio: 2) {
#element { background-image: url('hires.png'); }
}
@media only screen and (min-device-pixel-ratio: 3) {
#element { background-image: url('superhires.png'); }
}
This way, each device type only loads the correct image resource. Also keep in mind that the px
unit in CSS always operates on logical pixels.
As more and more device types appear, it gets trickier to provide all of them with adequate bitmap resources. In CSS, media queries is currently the only way, and in HTML5, the picture element lets you use different sources for different media queries, but the support is still not 100 % since most web developers still have to support IE11 for a while more (source: caniuse).
If you need crisp images for icons, line-art, design elements that are not photos, you need to start thinking about SVG, which scales beautifully to all resolutions.
It is also available in general settings
Settings -> Security -> Verify Apps
Just un-check it.
( I am running 4.2.2 but most probably it should be available in 4.0 and higher. Cant say about previous versions ... )
I solved a lot of issues by using the following code. Issues were : -
const sequelize = new Sequelize("test", "root", "root", {
host: "127.0.0.1",
dialect: "mysql",
port: "8889",
connectionLimit: 10,
socketPath: "/Applications/MAMP/tmp/mysql/mysql.sock",
// It will disable logging
logging: false
});
Imo use cases for ng-container
are simple replacements for which a custom template/component would be overkill. In the API doc they mention the following
use a ng-container to group multiple root nodes
and I guess that's what it is all about: grouping stuff.
Be aware that the ng-container
directive falls away instead of a template where its directive wraps the actual content.
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()
the x/yticks has the same properties as matplotlib.text
There is a problem with setting the tint color on the view after presenting; even if you do it in the completion block of presentViewController:animated:completion:, it causes a flicker effect on the color of the button titles. This is sloppy, unprofessional and completely unacceptable.
Other solutions presented depend on the view hierarchy remaining static, something that Apple is loathe to do. Expect those solutions to fail in future releases of iOS.
The one sure-fire way to solve this problem and to do it everywhere, is via adding a category to UIAlertController and swizzling the viewWillAppear.
The header:
//
// UIAlertController+iOS9TintFix.h
//
// Created by Flor, Daniel J on 11/2/15.
//
#import <UIKit/UIKit.h>
@interface UIAlertController (iOS9TintFix)
+ (void)tintFix;
- (void)swizzledViewWillAppear:(BOOL)animated;
@end
The implementation:
//
// UIAlertController+iOS9TintFix.m
//
// Created by Flor, Daniel J on 11/2/15.
//
#import "UIAlertController+iOS9TintFix.h"
#import <objc/runtime.h>
@implementation UIAlertController (iOS9TintFix)
+ (void)tintFix {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method method = class_getInstanceMethod(self, @selector(viewWillAppear:));
Method swizzle = class_getInstanceMethod(self, @selector(swizzledViewWillAppear:));
method_exchangeImplementations(method, swizzle);});
}
- (void)swizzledViewWillAppear:(BOOL)animated {
[self swizzledViewWillAppear:animated];
for (UIView *view in self.view.subviews) {
if (view.tintColor == self.view.tintColor) {
//only do those that match the main view, so we don't strip the red-tint from destructive buttons.
self.view.tintColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
[view setNeedsDisplay];
}
}
}
@end
Add a .pch (precompiled header) to your project and include the category:
#import "UIAlertController+iOS9TintFix.h"
Make sure you register your pch in the project properly, and it will include the category methods in every class that uses the UIAlertController.
Then, in your app delegates didFinishLaunchingWithOptions method, import your category and call
[UIAlertController tintFix];
and it will automatically propagate to every single instance of UIAlertController within your app, whether launched by your code or anyone else's.
This solution works for both iOS 8.X and iOS 9.X and lacks the flicker of the tint change post-presentation approach. It is also completely agnostic with respect to the view hierarchy of the sub-views of the UIAlertController.
Happy hacking!
Aside: sed expressions containing BASH variables need to be double ("
)-quoted for the variable to be interpreted correctly.
If you also double-quote your $BASH variable (recommended practice)
... then you can escape the variable double quotes as shown:
sed -i "s/foo/bar ""$VARIABLE""/g" <file>
I.e., replace the $VARIABLE-associated "
with ""
.
(Simply -escaping "$VAR"
as \"$VAR\"
results in a "
-quoted output string.)
Examples
$ VAR='apples and bananas'
$ echo $VAR
apples and bananas
$ echo "$VAR"
apples and bananas
$ printf 'I like %s!\n' $VAR
I like apples!
I like and!
I like bananas!
$ printf 'I like %s!\n' "$VAR"
I like apples and bananas!
Here, $VAR is "
-quoted before piping to sed (sed is either '
- or "
-quoted):
$ printf 'I like %s!\n' "$VAR" | sed 's/$VAR/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed 's/"$VAR"/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed 's/$VAR/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed 's/""$VAR""/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed "s/$VAR/cherries/g"
I like cherries!
$ printf 'I like %s!\n' "$VAR" | sed "s/""$VAR""/cherries/g"
I like cherries!
Compare that to:
$ printf 'I like %s!\n' $VAR | sed "s/$VAR/cherries/g"
I like apples!
I like and!
I like bananas!
$ printf 'I like %s!\n' $VAR | sed "s/""$VAR""/cherries/g"
I like apples!
I like and!
I like bananas!
... and so on ...
Conclusion
My recommendation, as standard practice, is to
"
-quote BASH variables ("$VAR"
)"
-quote, again, those variables (""$VAR""
) if they are used in a sed expression (which itself must be "
-quoted, not '
-quoted)$ VAR='apples and bananas'
$ echo "$VAR"
apples and bananas
$ printf 'I like %s!\n' "$VAR" | sed "s/""$VAR""/cherries/g"
I like cherries!
You can't convert binary data to String. As a solution you can encode binary data and then convert to String. For example, look at this How do you convert binary data to Strings and back in Java?
If it helps, You can also create an alias in your .bashrc
or .bash_profile
.
function dsize()
{
dir=$(pwd)
if [ "$1" != "" ]; then
dir=$1
fi
echo $(du -hs $dir)
}
This prints the size of the current directory or the directory you have passed as an argument.
Also, if you have commited sensitive data (e.g. a file containing passwords), you should completely delete it from the history of the repository. Here's a guide explaining how to do that: http://help.github.com/remove-sensitive-data/
No, you cannot specify whether the stroke is drawn inside or outside an element. I made a proposal to the SVG working group for this functionality in 2003, but it received no support (or discussion).
As I noted in the proposal,
Edit: This answer may be wrong in the future. It should be possible to achieve these results using SVG Vector Effects, by combining veStrokePath
with veIntersect
(for 'inside') or with veExclude
(for 'outside). However, Vector Effects are still a working draft module with no implementations that I can yet find.
Edit 2: The SVG 2 draft specification includes a stroke-alignment
property (with center|inside|outside possible values). This property may make it into UAs eventually.
Edit 3: Amusingly and dissapointingly, the SVG working group has removed stroke-alignment
from SVG 2. You can see some of the concerns described after the prose here.
You can also try this:
<a href="" onclick="if (confirm('Delete selected item?')){return true;}else{event.stopPropagation(); event.preventDefault();};" title="Link Title">
Link Text
</a>
Ok here is the short Version without correct NTP Time:
String get_xml_server_reponse(String server_url){
URL xml_server = null;
String xmltext = "";
InputStream input;
try {
xml_server = new URL(server_url);
try {
input = xml_server.openConnection().getInputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
final StringBuilder sBuf = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null)
{
sBuf.append(line);
}
}
catch (IOException e)
{
Log.e(e.getMessage(), "XML parser, stream2string 1");
}
finally {
try {
input.close();
}
catch (IOException e)
{
Log.e(e.getMessage(), "XML parser, stream2string 2");
}
}
xmltext = sBuf.toString();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
return xmltext;
}
long get_time_zone_time_l(GeoPoint gp){
String raw_offset = "";
String dst_offset = "";
double Longitude = gp.getLongitudeE6()/1E6;
double Latitude = gp.getLatitudeE6()/1E6;
long tsLong = System.currentTimeMillis()/1000;
if (tsLong != 0)
{
// https://maps.googleapis.com/maps/api/timezone/xml?location=39.6034810,-119.6822510×tamp=1331161200&sensor=false
String request = "https://maps.googleapis.com/maps/api/timezone/xml?location="+Latitude+","+ Longitude+ "×tamp="+tsLong +"&sensor=false";
String xmltext = get_xml_server_reponse(request);
if(xmltext.compareTo("")!= 0)
{
int startpos = xmltext.indexOf("<TimeZoneResponse");
xmltext = xmltext.substring(startpos);
XmlPullParser parser;
try {
parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(new StringReader (xmltext));
int eventType = parser.getEventType();
String tagName = "";
while(eventType != XmlPullParser.END_DOCUMENT) {
switch(eventType) {
case XmlPullParser.START_TAG:
tagName = parser.getName();
break;
case XmlPullParser.TEXT :
if (tagName.equalsIgnoreCase("raw_offset"))
if(raw_offset.compareTo("")== 0)
raw_offset = parser.getText();
if (tagName.equalsIgnoreCase("dst_offset"))
if(dst_offset.compareTo("")== 0)
dst_offset = parser.getText();
break;
}
try {
eventType = parser.next();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (XmlPullParserException e) {
e.printStackTrace();
erg += e.toString();
}
}
int ro = 0;
if(raw_offset.compareTo("")!= 0)
{
float rof = str_to_float(raw_offset);
ro = (int)rof;
}
int dof = 0;
if(dst_offset.compareTo("")!= 0)
{
float doff = str_to_float(dst_offset);
dof = (int)doff;
}
tsLong = (tsLong + ro + dof) * 1000;
}
return tsLong;
}
And use it with:
GeoPoint gp = new GeoPoint(39.6034810,-119.6822510);
long Current_TimeZone_Time_l = get_time_zone_time_l(gp);
Me, I'd do it something like this:
HTML:
onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"
JS:
function myfunction(params)
{
var path = params.path;
/* do stuff */
// on ok condition
params.ok(params.okArgs);
// on cancel condition
params.cancel(params.cancelArgs);
}
But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.
To keep the log clean as nothing happened (with some downsides with this approach (due to push -f)):
git checkout <branch>
git reset --hard <commit-hash-before-merge>
git push -f origin HEAD:<remote-branch>
'commit-hash-before-merge' comes from the log (git log) after merge.
You can simply return
if you want to skip the current iteration.
Since you're in a function, if you return
before doing anything else, then you have effectively skipped execution of the code below the return
statement.
I just changed the .htaccess file contents and as shown in the following links answer. And tried refreshing the page (which didn't work, and couldn't find the request to my controller) it worked.
Then just because of my doubt I undone the changes I did to my .htaccess inside my public_html folder back to original .htaccess content. So it's now as follows (which is originally it was):
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]
And now also it works.
Hint: Seems like before the Rewrite Rules haven't been clearly setup within the Server context.
My file structure is as follows:
/
|- gheapp
| |- application
| L- system
|
|- public_html
| |- .htaccess
| L- index.php
And in the index.php
I have set up the following paths to the system and the application:
$system_path = '../gheapp/system';
$application_folder = '../gheapp/application';
Note: by doing so, our application source code becomes hidden to the public at first.
Please, if you guys find anything wrong with my answer, comment and re-correct me!
Hope beginners would find this answer helpful.
Thanks!
Try to consider following image
For example Object.MemberwiseClone creates a shallow copy link
and using ICloneable interface you can get deep copy as described here
I tried Omega's example however it was not working with my C# code. I recommend using this instead:
[RegularExpression(@"^(?=[^\d_].*?\d)\w(\w|[!@#$%]){7,20}", ErrorMessage = @"Error. Password must have one capital, one special character and one numerical character. It can not start with a special character or a digit.")]
first configure routing
import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';
and
@RouteConfig([
{ path: '/addDisplay', component: AddDisplay, as: 'addDisplay' },
{ path: '/<secondComponent>', component: '<secondComponentName>', as: 'secondComponentAs' },
])
then in your component import and then inject Router
import {Router} from 'angular2/router'
export class AddDisplay {
constructor(private router: Router)
}
the last thing you have to do is to call
this.router.navigateByUrl('<pathDefinedInRouteConfig>');
or
this.router.navigate(['<aliasInRouteConfig>']);
You can't style a disabled checkbox directly because it's controlled by the browser / OS.
However you can be clever and replace the checkbox with a label that simulates a checkbox using pure CSS. You need to have an adjacent label that you can use to style a new "pseudo checkbox". Essentially you're completely redrawing the thing but it gives you complete control over how it looks in any state.
I've thrown up a basic example so that you can see it in action: http://jsfiddle.net/JohnSReid/pr9Lx5th/3/
Here's the sample:
input[type="checkbox"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
label:before {_x000D_
background: linear-gradient(to bottom, #fff 0px, #e6e6e6 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
border: 1px solid #035f8f;_x000D_
height: 36px;_x000D_
width: 36px;_x000D_
display: block;_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
content: '';_x000D_
background: linear-gradient(to bottom, #e6e6e6 0px, #fff 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
border-color: #3d9000;_x000D_
color: #96be0a;_x000D_
font-size: 38px;_x000D_
line-height: 35px;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:disabled + label:before {_x000D_
border-color: #eee;_x000D_
color: #ccc;_x000D_
background: linear-gradient(to top, #e6e6e6 0px, #fff 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
content: '?';_x000D_
}
_x000D_
<div><input id="cb1" type="checkbox" disabled checked /><label for="cb1"></label></div>_x000D_
<div><input id="cb2" type="checkbox" disabled /><label for="cb2"></label></div>_x000D_
<div><input id="cb3" type="checkbox" checked /><label for="cb3"></label></div>_x000D_
<div><input id="cb4" type="checkbox" /><label for="cb4"></label></div>
_x000D_
Depending on your level of browser compatibility and accessibility, some additional tweaks will need to be made.
Suppose I have the following table T
:
a b
--------
1 abc
1 def
1 ghi
2 jkl
2 mno
2 pqr
And I do the following query:
SELECT a, b
FROM T
GROUP BY a
The output should have two rows, one row where a=1
and a second row where a=2
.
But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.
This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).
Fixing it might look like this:
SELECT a, MAX(b) AS x
FROM T
GROUP BY a
Now it's clear that you want the following result:
a x
--------
1 ghi
2 pqr
Use HH
for 24 hour hours format:
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
Or the tt
format specifier for the AM/PM
part:
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")
Take a look at the custom Date and Time format strings documentation.
To use DHCP, you'd have to run a DHCP server on the primary and a client on the secondary; the primary could then query the server to find out what address it handed out. Probably overkill.
I can't help you with Windows directly. On Unix, the "arp" command will tell you what IP addresses are known to be attached to the local ethernet segment. Windows will have this same information (since it's a core part of the IP/Ethernet interface) but I don't know how you get at it.
Of course, the networking stack will only know about the other host if it has previously seen traffic from it. You may have to first send a broadcast packet on the interface to elicit some sort of response and thus populate the local ARP table.
Try this to Convert from Decimal to Hex
#include<stdio.h>
#include<conio.h>
int main(void)
{
int count=0,digit,n,i=0;
int hex[5];
clrscr();
printf("enter a number ");
scanf("%d",&n);
if(n<10)
{
printf("%d",n);
}
switch(n)
{
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("B");
break;
case 13:
printf("C");
break;
case 14:
printf("D");
break;
case 15:
printf("E");
break;
case 16:
printf("F");
break;
default:;
}
while(n>16)
{
digit=n%16;
hex[i]=digit;
i++;
count++;
n=n/16;
}
hex[i]=n;
for(i=count;i>=0;i--)
{
switch(hex[i])
{
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("C");
break;
case 13:
printf("D");
break;
case 14:
printf("E");
break;
case 15:
printf("F");
break;
default:
printf("%d",hex[i]);
}
}
getch();
return 0;
}
Personally, I like the 'batch' command.
$ batch
> mycommand -x arg1 -y arg2 -z arg3
> ^D
This stuffs it in to the background, and then mails the results to you. It's a part of cron.
Just manually delete you database. Ensure you create backup first (in my case db.sqlite3 is my database)
Run this command manage.py migrate
In cases where you don't want the metaclass-based solution above, and you don't like the simple function decorator-based approach (e.g. because in that case static methods on the singleton class won't work), this compromise works:
class singleton(object):
"""Singleton decorator."""
def __init__(self, cls):
self.__dict__['cls'] = cls
instances = {}
def __call__(self):
if self.cls not in self.instances:
self.instances[self.cls] = self.cls()
return self.instances[self.cls]
def __getattr__(self, attr):
return getattr(self.__dict__['cls'], attr)
def __setattr__(self, attr, value):
return setattr(self.__dict__['cls'], attr, value)
By keys()
and values()
methods of dictionary and zip
.
zip
will return a list of tuples which acts like an ordered dictionary.
Demo:
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]
Here's a simple example:
Pattern pattern = Pattern.compile(regexPattern);
List<String> list = new ArrayList<String>();
Matcher m = pattern.matcher(input);
while (m.find()) {
list.add(m.group());
}
(if you have more capturing groups, you can refer to them by their index as an argument of the group method. If you need an array, then use list.toArray()
)
The \ArrayObject
class has the possibility to exchange the current array to disconnect the original reference. To do so, it comes with two handy methods: exchangeArray()
and getArrayCopy()
. The rest is plain simple array_merge()
of the provided object with the ArrayObject
s public properties:
class MergeBase extends ArrayObject
{
public final function merge( Array $toMerge )
{
$this->exchangeArray( array_merge( $this->getArrayCopy(), $toMerge ) );
}
}
The usage is as easy as this:
$base = new MergeBase();
$base[] = 1;
$base[] = 2;
$toMerge = [ 3,4,5, ];
$base->merge( $toMerge );
I modified @Richard Bronosky's fiddle like this.
It's better approach to use data-*
attribute rather than a custom attribute.
I replaced <textarea placeholdernl>
to <textarea data-placeholder>
and some other styles as well.
edited
Here is the Richard's original answer which contains full code snippet.
for a border flash: actually very simple: replace from to to 99% black and e.g 1% the shift to blue you can even make it shorter, animation time set to e.g 5sec.
@keyframes myborder {
0% {border-color: black;}
99% {border-color:black;}
100% {border-color: blue;}
}
Yes, but you need to move the variable assignment into the query:
SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;
Test case:
CREATE TABLE user (`user` int, `group` int);
INSERT INTO user VALUES (123456, 5);
INSERT INTO user VALUES (111111, 5);
Result:
SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;
+--------+-------+
| user | group |
+--------+-------+
| 123456 | 5 |
| 111111 | 5 |
+--------+-------+
2 rows in set (0.00 sec)
Note that for SET
, either =
or :=
can be used as the assignment operator. However inside other statements, the assignment operator must be :=
and not =
because =
is treated as a comparison operator in non-SET statements.
UPDATE:
Further to comments below, you may also do the following:
SET @user := 123456;
SELECT `group` FROM user LIMIT 1 INTO @group;
SELECT * FROM user WHERE `group` = @group;
I just used Gson
HashMap<String, Object> map = new Gson().fromJson(json.toString(), HashMap.class);
You could try:
$(this).closest(".column").prev().find(".inputQty").val();
Here is another approach.
class orbisius_custom_string {
/**
* The reverse of nl2br. Handles <br/> <br/> <br />
* usage: orbisius_custom_string::br2nl('Your buffer goes here ...');
* @param str $buff
* @return str
* @author Slavi Marinov | http://orbisius.com
*/
public static function br2nl($buff = '') {
$buff = preg_replace('#<br[/\s]*>#si', "\n", $buff);
$buff = trim($buff);
return $buff;
}
}
Finally I found A good css that works!!! Without position: absolute;
.
body {
display:table;
min-height: 100%;
}
.fixed-bottom {
display:table-footer-group;
}
I have been looking for this for a long time! Hope this helps.
The ones method is much faster than using repmat:
>> tic; for i = 1:1e6, x=5*ones(10,1); end; toc
Elapsed time is 3.426347 seconds.
>> tic; for i = 1:1e6, y=repmat(5,10,1); end; toc
Elapsed time is 20.603680 seconds.
And, in my opinion, makes for much more readable code.
In my case Mac OS High Sierra 10.13.6
brew -v
OutPut-
Homebrew 2.2.2
Homebrew/homebrew-core (git revision 71aa; last commit 2020-01-07)
Homebrew/homebrew-cask (git revision 84f00; last commit 2020-01-07)
Use execfile for Python 2:
>>> execfile('C:\\test.py')
Use exec for Python 3
>>> exec(open("C:\\test.py").read())
You have to use func setTitleColor(_ color: UIColor?, for state: UIControlState)
the same way you set the actual title text. Docs
isbeauty.setTitleColor(UIColorFromRGB("F21B3F"), for: .normal)
using
class httplib.HTTPSConnection
http://docs.python.org/library/httplib.html#httplib.HTTPSConnection
I was looking for a simple one-line solution to get the next month via math so I wouldn't have to look up the javascript date functions (mental laziness on my part). Quite strangely, I didn't find one here.
I overcame my brief bout of laziness, wrote one, and decided to share!
Solution:
(new Date().getMonth()+1)%12 + 1
Just to be clear why this works, let me break down the magic!
It gets the current month (which is in 0..11 format), increments by 1 for the next month, and wraps it to a boundary of 12 via modulus (11%12==11; 12%12==0). This returns the next month in the same 0..11 format, so converting to a format Date() will recognize (1..12) is easy: simply add 1 again.
Proof of concept:
> for(var m=0;m<=11;m++) { console.info( "next month for %i: %i", m+1, (m+1)%12 + 1 ) }
next month for 1: 2
next month for 2: 3
next month for 3: 4
next month for 4: 5
next month for 5: 6
next month for 6: 7
next month for 7: 8
next month for 8: 9
next month for 9: 10
next month for 10: 11
next month for 11: 12
next month for 12: 1
So there you have it.
You need to make your regex pattern 'non-greedy' by adding a '?' after the '.+'
By default, '*' and '+' are greedy in that they will match as long a string of chars as possible, ignoring any matches that might occur within the string.
Non-greedy makes the pattern only match the shortest possible match.
See Watch Out for The Greediness! for a better explanation.
Or alternately, change your regex to
\(([^\)]+)\)
which will match any grouping of parens that do not, themselves, contain parens.
I'm bubbling up my regular expression based answer from one I posted earlier in the comments of another answer. I think using re
is a clearer more explicit solution to this problem than str.rstrip
.
>>> import re
If you want to remove one or more trailing newline chars:
>>> re.sub(r'[\n\r]+$', '', '\nx\r\n')
'\nx'
If you want to remove newline chars everywhere (not just trailing):
>>> re.sub(r'[\n\r]+', '', '\nx\r\n')
'x'
If you want to remove only 1-2 trailing newline chars (i.e., \r
, \n
, \r\n
, \n\r
, \r\r
, \n\n
)
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r\n')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n')
'\nx'
I have a feeling what most people really want here, is to remove just one occurrence of a trailing newline character, either \r\n
or \n
and nothing more.
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n\n', count=1)
'\nx\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n\r\n', count=1)
'\nx\r\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n', count=1)
'\nx'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n', count=1)
'\nx'
(The ?:
is to create a non-capturing group.)
(By the way this is not what '...'.rstrip('\n', '').rstrip('\r', '')
does which may not be clear to others stumbling upon this thread. str.rstrip
strips as many of the trailing characters as possible, so a string like foo\n\n\n
would result in a false positive of foo
whereas you may have wanted to preserve the other newlines after stripping a single trailing one.)
You can convert type of plaintext
to string:
f.write(str(plaintext) + '\n')
A hook that allows for overriding copy events, could be used for doing the same with paste events. The input element cannot be display: none; or visibility: hidden; sadly
export const useOverrideCopy = () => {
const [copyListenerEl, setCopyListenerEl] = React.useState(
null as HTMLInputElement | null
)
const [, setCopyHandler] = React.useState<(e: ClipboardEvent) => void | null>(
() => () => {}
)
// appends a input element to the DOM, that will be focused.
// when using copy/paste etc, it will target focused elements
React.useEffect(() => {
const el = document.createElement("input")
// cannot focus a element that is not "visible" aka cannot use display: none or visibility: hidden
el.style.width = "0"
el.style.height = "0"
el.style.opacity = "0"
el.style.position = "fixed"
el.style.top = "-20px"
document.body.appendChild(el)
setCopyListenerEl(el)
return () => {
document.body.removeChild(el)
}
}, [])
// adds a event listener for copying, and removes the old one
const overrideCopy = (newOverrideAction: () => any) => {
setCopyHandler((prevCopyHandler: (e: ClipboardEvent) => void) => {
const copyHandler = (e: ClipboardEvent) => {
e.preventDefault()
newOverrideAction()
}
copyListenerEl?.removeEventListener("copy", prevCopyHandler)
copyListenerEl?.addEventListener("copy", copyHandler)
copyListenerEl?.focus() // when focused, all copy events will trigger listener above
return copyHandler
})
}
return { overrideCopy }
}
Used like this:
const customCopyEvent = () => {
console.log("doing something")
}
const { overrideCopy } = useOverrideCopy()
overrideCopy(customCopyEvent)
Every time you call overrideCopy it will refocus and call your custom event on copy.
I'm going to put in a vote for np.vectorize. It allows you to just shoot over x number of columns and not deal with the dataframe in the function, so it's great for functions you don't control or doing something like sending 2 columns and a constant into a function (i.e. col_1, col_2, 'foo').
import numpy as np
import pandas as pd
df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']
def get_sublist(sta,end):
return mylist[sta:end+1]
#df['col_3'] = df[['col_1','col_2']].apply(get_sublist,axis=1)
# expect above to output df as below
df.loc[:,'col_3'] = np.vectorize(get_sublist, otypes=["O"]) (df['col_1'], df['col_2'])
df
ID col_1 col_2 col_3
0 1 0 1 [a, b]
1 2 2 4 [c, d, e]
2 3 3 5 [d, e, f]
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
You can scroll by jQuery and JavaScript Just need two element jQuery and this JavaScript code :
$(function() {
// Generic selector to be used anywhere
$(".js-scroll-to-id").click(function(e) {
// Get the href dynamically
var destination = $(this).attr('href');
// Prevent href=“#” link from changing the URL hash (optional)
e.preventDefault();
// Animate scroll to destination
$('html, body').animate({
scrollTop: $(destination).offset().top
}, 1500);
});
});
$(function() {_x000D_
// Generic selector to be used anywhere_x000D_
$(".js-scroll-to-id").click(function(e) {_x000D_
_x000D_
// Get the href dynamically_x000D_
var destination = $(this).attr('href');_x000D_
_x000D_
// Prevent href=“#” link from changing the URL hash (optional)_x000D_
e.preventDefault();_x000D_
_x000D_
// Animate scroll to destination_x000D_
$('html, body').animate({_x000D_
scrollTop: $(destination).offset().top_x000D_
}, 1500);_x000D_
});_x000D_
});
_x000D_
#pane1 {_x000D_
background: #000;_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
}_x000D_
_x000D_
#pane2 {_x000D_
background: #ff0000;_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
}_x000D_
_x000D_
#pane3 {_x000D_
background: #ccc;_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul class="nav">_x000D_
<li>_x000D_
<a href="#pane1" class=" js-scroll-to-id">Item 1</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#pane2" class="js-scroll-to-id">Item 2</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#pane3" class=" js-scroll-to-id">Item 3</a>_x000D_
</li>_x000D_
</ul>_x000D_
<div id="pane1"></div>_x000D_
<div id="pane2"></div>_x000D_
<div id="pane3"></div>_x000D_
<!-- example of a fixed nav menu -->_x000D_
<ul class="nav">_x000D_
<li>_x000D_
<a href="#pane3" class="js-scroll-to-id">Item 1</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#pane2" class="js-scroll-to-id">Item 2</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#pane1" class="js-scroll-to-id">Item 3</a>_x000D_
</li>_x000D_
</ul>
_x000D_
Try choosing project -> clean. A simple clean may fix it up.
I find the below RE working fine for Date in the following format;
It can accept year from 2000-2099
Please do not forget to add $ at the end,if not it accept 14-11-201 or 20177
date="13-11-2017"
x=re.search("^([1-9] |1[0-9]| 2[0-9]|3[0-1])(.|-)([1-9] |1[0-2])(.|-|)20[0-9][0-9]$",date)
x.group()
output = '13-11-2017'
You can kind of do this. Unfortunately there's no way to use an inset on text-shadow, but you can fake it with colour and position. Take the blur right down and arrange the shadow along the top right. Something like this might do the trick:
background-color:#D7CFBA;
color:#38373D;
font-weight:bold;
text-shadow:1px 1px 0 #FFFFFF;
... but you'll need to be really, really careful about which colours you use otherwise it will look off. It is essentially an optical illusion so won't work in every context. It also doesn't really look great at smaller font sizes, so be aware of that too.
egrep -ir --include=*.{php,html,js} "(document.cookie|setcookie)" .
The r
flag means to search recursively (search subdirectories). The i
flag means case insensitive.
If you just want file names add the l
(lowercase L
) flag:
egrep -lir --include=*.{php,html,js} "(document.cookie|setcookie)" .
Not in Linux at the moment, so can't double check, but I think it's:
rpm -ql ffmpeg
That should list all the files installed as part of the ffmpeg package.
Set also android:gravity
parameter in TextView
to center
.
For testing the effects of different layout parameters I recommend to use different background color for every element, so you can see how your layout changes with parameters like gravity, layout_gravity or others.
0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.
There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.
I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException
and Application.ThreadException
, as appropriate.
For outputing String
as text/plain
use:
@RequestMapping(value="/foo", method=RequestMethod.GET, produces="text/plain")
@ResponseBody
public String foo() {
return "bar";
}
This post was helpful for my project hence I thought of sharing my experience as well. The essential thing to note is that the POST request is possible only with a form. I had a similar requirement as I was trying to render a page with ejs. I needed to render a navigation with a list of items that would essentially be hyperlinks and when user selects any one of them, the server responds with appropriate information.
so I basically created each of the navigation items as a form using a loop as follows:
<ul>_x000D_
begin loop..._x000D_
<li>_x000D_
<form action="/" method="post">_x000D_
<input type="hidden" name="country" value="India"/>_x000D_
<button type="submit" name="button">India</button>_x000D_
</form> _x000D_
</li>_x000D_
end loop._x000D_
</ul>
_x000D_
what it did is to create a form with hidden input with a value assigned same as the text on the button. So the end user will see only text from the button and when clicked, will send a post request to the server.
Note that the value parameter of the input box and the Button text are exactly same and were values passed using ejs that I have not shown in this example above to keep the code simple.
here is a screen shot of the navigation... enter image description here
To get the new Microsoft Edge based on a Mozilla core add:
else if ((verOffset=nAgt.indexOf("Edg"))!=-1) {
browserName = "Microsoft Edge";
fullVersion = nAgt.substring(verOffset+5);
}
before
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
Do you want to change database?
\l - to display databases
\c - connect to new database
Update.
I've read again your question. To display schemas
\dn - list of schemas
To change schema, you can try
SET search_path TO
Using param to name the parameters allows you to ignore the order of the parameters:
ParamEx.ps1
# Show how to handle command line parameters in Windows PowerShell
param(
[string]$FileName,
[string]$Bogus
)
write-output 'This is param FileName:'+$FileName
write-output 'This is param Bogus:'+$Bogus
ParaEx.bat
rem Notice that named params mean the order of params can be ignored
powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"
on ubuntu:
sudo apt-get install php-mysql
sudo service apache2 restart
If you want to use the GUI... click/double-click the table and select the Data
tab. Click in the column value you want to set to (null)
. Select the value and delete it. Hit the commit button (green check-mark button). It should now be null.
More info here:
How to use the SQL Worksheet in SQL Developer to Insert, Update and Delete Data
On Ubuntu with OpenJDK, it installed in /usr/lib/jvm/default-java/jre/lib/ext/jfxrt.jar
(technically its a symlink to /usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
, but it is probably better to use the default-java
link)
Have you tried adding the php_value error_log '/path/to/php_error_log
to your VirtualHost configuration?
There is no best IDE. You make it as good as you get used using it.
This is an Inequality operator.
Also,this might be helpful for future: Operators listed by Functionality
For anyone still coming to this post, the other option is to simply omit the parentheses:
Sub SomeOtherSub(Stattyp As String)
'Daty and the other variables are defined here
CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2
End Sub
The Call
keywords is only really in VBA for backwards compatibilty and isn't actually required.
If however, you decide to use the Call
keyword, then you have to change your syntax to suit.
'// With Call
Call Foo(Bar)
'// Without Call
Foo Bar
Both will do exactly the same thing.
That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call
keyword and the parentheses
Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener
see https://github.com/ArtNazarov/LazyJs
Sorry for my bad English
To get the checked state of your checkbox the path would be:
this.refs.complete.state.checked
The alternative is to get it from the event passed into the handleChange
method:
event.target.checked
%
(any host) (see manual for details)The current problem is the first one, but right after you resolve it you will likely get the second one.
In case if String position is not fixed then by below Select statement we can get the expected output.
Table Structure ID VARCHAR2(100 BYTE) CLIENT VARCHAR2(4000 BYTE)
Data-
ID CLIENT
1001 {"clientId":"con-bjp","clientName":"ABC","providerId":"SBS"}
1002
{"IdType":"AccountNo","Id":"XXXXXXXX3521","ToPricingId":"XXXXXXXX3521","clientId":"Test-Cust","clientName":"MFX"}
Requirement - Search "ClientId" string in CLIENT column and return the corresponding value. Like From "clientId":"con-bjp" --> con-bjp(Expected output)
select CLIENT,substr(substr(CLIENT,instr(CLIENT,'"clientId":"')+length('"clientId":"')),1,instr(substr(CLIENT,instr(CLIENT,'"clientId":"')+length('"clientId":"')),'"',1 )-1) cut_str from TEST_SC;
CLIENT cut_str ----------------------------------------------------------- ---------- {"clientId":"con-bjp","clientName":"ABC","providerId":"SBS"} con-bjp {"IdType":"AccountNo","Id":"XXXXXXXX3521","ToPricingId":"XXXXXXXX3521","clientId":"Test-Cust","clientName":"MFX"} Test-Cust
Follow the below steps to show the name of the branch of your GIT repo in ubuntu terminal:
step1: open terminal and edit .bashrc using the following command.
vi .bashrc
step2: add the following line at the end of the .bashrc file :
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/' }
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
step3: source .bashrc in the root (home) directory by doing:
/rootfolder:~$ source .bashrc
Step4: Restart and open the terminal and check the cmd. Navigate to your GIt repo directory path and you are done. :)
Well, it's too late to post an answer, but I feel my explanation will be easy to understand for beginners with Angular. The following is one of the examples that I give during my presentation.
Consider your angular Application as a building. A building can have N
number of apartments in it. An apartment is considered as a module. An Apartment can then have N
number of rooms which correspond to the building blocks of an Angular application named components.
Now each apartment (Module)` will have rooms (Components), lifts (Services) to enable larger movement in and out the apartments, wires (Pipes) to transform around and make it useful in the apartments.
You will also have places like swimming pool, tennis court which are being shared by all building residents. So these can be considered as components inside SharedModule.
Basically, the difference is as follows,
Follow my slides to understand the building blocks of an Angular application
Here is my session on Building Blocks of Angular for beginners
To determine the class of an object simply call:
someObject.getClass()
You can abbreviate this to someObject.class
in most cases. However, if you use this on a Map
it will try to retrieve the value with key 'class'. Because of this, I always use getClass()
even though it's a little longer.
If you want to check if an object implements a particular interface or extends a particular class (e.g. Date) use:
(somObject instanceof Date)
or to check if the class of an object is exactly a particular class (not a subclass of it), use:
(somObject.getClass() == Date)
You haven't defined struct stasher_file
by your first definition. What you have defined is an nameless struct type and a variable stasher_file
of that type. Since there's no definition for such type as struct stasher_file
in your code, the compiler complains about incomplete type.
In order to define struct stasher_file
, you should have done it as follows
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
Note where the stasher_file
name is placed in the definition.
To get records from the last 24 hours:
SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)
I used the timezone-js package.
var timezoneJS = require('timezone-js');
var tzdata = require('tzdata');
createDate(dateObj) {
if ( dateObj == null ) {
return null;
}
var nativeTimezoneOffset = new Date().getTimezoneOffset();
var offset = this.getTimeZoneOffset();
// use the native Date object if the timezone matches
if ( offset == -1 * nativeTimezoneOffset ) {
return dateObj;
}
this.loadTimeZones();
// FIXME: it would be better if timezoneJS.Date was an instanceof of Date
// tried jquery $.extend
// added hack to Fiterpickr to look for Dater.getTime instead of "d instanceof Date"
return new timezoneJS.Date(dateObj,this.getTimeZoneName());
},
Quite apart from the timing, this code you show is simply incorrect: you execute 100 connections (completely ignoring all but the last one), and then when you do the first execute call you pass it a local variable query_stmt
which you only initialize after the execute call.
First, make your code correct, without worrying about timing yet: i.e. a function that makes or receives a connection and performs 100 or 500 or whatever number of updates on that connection, then closes the connection. Once you have your code working correctly is the correct point at which to think about using timeit
on it!
Specifically, if the function you want to time is a parameter-less one called foobar
you can use timeit.timeit (2.6 or later -- it's more complicated in 2.5 and before):
timeit.timeit('foobar()', number=1000)
You'd better specify the number of runs because the default, a million, may be high for your use case (leading to spending a lot of time in this code;-).
HTML5 comes with File API spec, which allows you to create applications that let the user interact with files locally; That means you can load files and render them in the browser without actually having to upload the files. Part of the File API is the FileReader interface which lets web applications asynchronously read the contents of files .
Here's a quick example that makes use of the FileReader
class to read an image as DataURL and renders a thumbnail by setting the src
attribute of an image tag to a data URL:
The html code:
<input type="file" id="files" />
<img id="image" />
The JavaScript code:
document.getElementById("files").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
// get loaded data and render thumbnail.
document.getElementById("image").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
};
Here's a good article on using the File APIs in JavaScript.
The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:
function handleFileSelect(evt) {_x000D_
var files = evt.target.files;_x000D_
_x000D_
// Loop through the FileList and render image files as thumbnails._x000D_
for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
// Only process image files._x000D_
if (!f.type.match('image.*')) {_x000D_
continue;_x000D_
}_x000D_
_x000D_
var reader = new FileReader();_x000D_
_x000D_
// Closure to capture the file information._x000D_
reader.onload = (function(theFile) {_x000D_
return function(e) {_x000D_
// Render thumbnail._x000D_
var span = document.createElement('span');_x000D_
span.innerHTML = _x000D_
[_x000D_
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
e.target.result,_x000D_
'" title="', escape(theFile.name), _x000D_
'"/>'_x000D_
].join('');_x000D_
_x000D_
document.getElementById('list').insertBefore(span, null);_x000D_
};_x000D_
})(f);_x000D_
_x000D_
// Read in the image file as a data URL._x000D_
reader.readAsDataURL(f);_x000D_
}_x000D_
}_x000D_
_x000D_
document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
In my case, the option I used was:
var from = $("input.datepicker").datetimepicker({
format:'Y-m-d',
timepicker:false # <- HERE
});
I'm using this plugin https://xdsoft.net/jqplugins/datetimepicker/
I just want to add that orderby is way more useful.
Why? Because I can do this:
Dim thisAccountBalances = account.DictOfBalances.Values.ToList
thisAccountBalances.ForEach(Sub(x) x.computeBalanceOtherFactors())
thisAccountBalances=thisAccountBalances.OrderBy(Function(x) x.TotalBalance).tolist
listOfBalances.AddRange(thisAccountBalances)
Why complicated comparer? Just sort based on a field. Here I am sorting based on TotalBalance.
Very easy.
I can't do that with sort. I wonder why. Do fine with orderBy.
As for speed it's always O(n).
Use the set()
method: see doc
arraylist.set(index,newvalue);
For AngularJS developers I use from the solution:
var element = $window.document.getElementById("export-button");
if (element){
element.blur();
}
Remember to inject $window.
The code bellow allows the user to un-/check the checkboxes in the DataGridView, if the Cells are created in code
private void gvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)gvData.Rows[e.RowIndex].Cells[0];
if (chk.Value == chk.TrueValue)
{
gvData.Rows[e.RowIndex].Cells[0].Value = chk.FalseValue;
}
else
{
gvData.Rows[e.RowIndex].Cells[0].Value = chk.TrueValue;
}
}
if you want to change color by hovering in the element, try this:
path:hover{
fill:red;
}
For Mac OS X Mojave and above
To Uninstall Homebrew, run following command:
sudo ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
To Install Homebrew, run following command:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
And if you run into Permission denied issue, try running this command followed by install command again:
sudo chown -R $(whoami):admin /usr/local/* && sudo chmod -R g+rwx /usr/local/*
Is there a way to get it via $event->getComposer()->getRepositoryManager()->getAllPackages()
Your attempt wasn't that bad. You have to do it with LIKE
, yes.
In the manual it says:
Use LIKE to create an empty table based on the definition of another table, including any column attributes and indexes defined in the original table.
So you do:
CREATE TABLE New_Users LIKE Old_Users;
Then you insert with
INSERT INTO New_Users SELECT * FROM Old_Users GROUP BY ID;
But you can not do it in one statement.
To use $this->input->post()
initialize the form helper. You could do that by default in config.
You can simply use:
mvn --settings YourOwnSettings.xml clean install
or
mvn -s YourOwnSettings.xml clean install
I think the problem is with the way you designed your data. To me in terms of semantics, it just doesn't make sense. What exactly is steps for?
Does it store the information of one company?
If that's the case steps should be an object (see KayakDave's answer) and each "step" should be an object property.
Does it store the information of multiple companies?
If that's the case, steps should be an array of objects.
$scope.steps=[{companyName: true, businessType: true},{companyName: false}]
In either case you can easily iterate through the data with one (two for 2nd case) ng-repeats.
Initially starting with a pyspark dataframes - I got type conversion errors (when converting to pandas df's and then appending to csv) given the schema/column types in my pyspark dataframes
Solved the problem by forcing all columns in each df to be of type string and then appending this to csv as follows:
with open('testAppend.csv', 'a') as f:
df2.toPandas().astype(str).to_csv(f, header=False)
Hi i used this solution works perfectly.No Need to check, just use https.
<script language="javascript" type="text/javascript">
document.location="https:" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
</script>
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
A regular expression for words would give you the most control. You would want to carefully consider how to deal with words with dashes or apostrophes, like "I'm".
for full url use
$('#imageContainerId').prop('src')
for relative image url use
$('#imageContainerId').attr('src')
function showImgUrl(){_x000D_
console.log('for full image url ' + $('#imageId').prop('src') );_x000D_
console.log('for relative image url ' + $('#imageId').attr('src'));_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<img id='imageId' src='images/image1.jpg' height='50px' width='50px'/>_x000D_
_x000D_
<input type='button' onclick='showImgUrl()' value='click to see the url of the img' />
_x000D_
I am surprised that nobody has mentioned CSS pseudo-classes, which are also a sort-of conditionals in CSS. You can do some pretty advanced things with this, without a single line of JavaScript.
Some pseudo-classes:
Example:
div { color: white; background: red }_x000D_
input:checked + div { background: green }
_x000D_
<input type=checkbox>Click me!_x000D_
<div>Red or green?</div>
_x000D_
For applications such as Squirrel SQL Client (http://squirrel-sql.sourceforge.net/) version 4 you can set "serverTimezone" under "driver properties" to GMT+1
(example of timezone "Europe/Vienna).
I have 4 solution to finish this task:
#circle1 {
background-color: #B90136;
width: 100px;
height: 100px;
border-radius: 50px;/* specify the radius */
}
#circle2 {
background-color: #B90136;
width: 100px;/* specify the radius */
height: 100px;/* specify the radius */
clip-path: circle();
}
#circle3::before {
content: "";
display: block;
width: 100px;
height: 100px;
border-radius: 50px;/* specify the radius */
background-color: #B90136;
}
#circle4 {
background-image: radial-gradient(#B90136 70%, transparent 30%);
height: 100px;/* specify the radius */
width: 100px;/* specify the radius */
}
_x000D_
<h3>1 border-radius</h3>
<div id="circle1"></div>
<hr/>
<h3>2 clip-path</h3>
<div id="circle2"></div>
<hr/>
<h3>3 pseudo element</h3>
<div id="circle3"></div>
<hr/>
<h3>4 radial-gradient</h3>
<div id="circle4"></div>
_x000D_
if you want to specifically find strings which ends with desired characters then this would help you...
select * from tablename where col_name like '%190'
$(document).ready(function(){
var response = '';
$.ajax({ type: "GET",
url: "Records.php",
async: false,
success : function(text)
{
response = text;
}
});
alert(response);
});
needs to be:
$(document).ready(function(){
$.ajax({ type: "GET",
url: "Records.php",
async: false,
success : function(text)
{
alert(text);
}
});
});
For PLSQL version 9.0.0.1601
At last, here I found the solution.
I added jdk path org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_144
to gradle.properties
file and did a rebuild. It works now.
After struggling for many days finally found a solution that works perfectly.
Mac OS open ~/Library folder (in your home directory) and delete the VirtulBox folder. This will remove all configurations and you can start the virtual box again!
Others look for .virtualbox folder in your home directory. Remove it and open VirtualBox should solve your issue.
Cheers!!
You don't have that kind of control with a bare a
tag. But you can hook up the tag's onclick
handler to call window.open(...)
with the right parameters. See here for examples:
https://developer.mozilla.org/En/DOM/Window.open
I still don't think you can force window over tab directly though-- that depends on the browser and the user's settings.
The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()
for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
{
write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}
Additionally foreach
allows you to iterate through a collection or array without needing to figure out the length.
Rewritten (and edited for compile) -
foreach ($Row in $ds.Tables[1].Rows)
{
write-host "value is : $($Row[0])"
}
On Unix you can use valgrind
to find issues. It's free and powerful. If you'd rather do it yourself you can overload the new
and delete
operators to set up a configuration where you have 1 byte with 0xDEADBEEF
before and after each new object. Then track what happens at each iteration. This can fail to catch everything (you aren't guaranteed to even touch those bytes) but it has worked for me in the past on a Windows platform.
Kotlin code:
if (file.exists()){
val bitmap = BitmapFactory.decodeFile(file.absolutePath)
val exif = ExifInterface(file.absoluteFile.toString())
val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
val matrix = Matrix()
when(orientation){
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90F)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180F)
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270F)
}
val rotatedBitmap = Bitmap.createBitmap(bitmap, 0,0 , bitmap.width, bitmap.height, matrix, true)
bitmap.recycle()
iv_capture.setImageBitmap(rotatedBitmap)
}