Databases are heavily optimized for common usage scenarios (and LIKE is one of those).
You won't find a faster way of doing your search if you want to stay on the DB-level.
Here is my solution which uses JQuery in your header, and works on Mobile.
On mobile the top links require two taps: one to dropdown the menu and one to go to its link.
$(function(){_x000D_
$('.dropdown-toggle').click(_x000D_
function(){_x000D_
if ($(this).next().is(':visible')) {_x000D_
location.href = $(this).attr('href');;_x000D_
}_x000D_
});_x000D_
});_x000D_
});
_x000D_
// CMakeLists.txt : release
set(CMAKE_CONFIGURATION_TYPES "Release" CACHE STRING "" FORCE)
// CMakeLists.txt : debug
set(CMAKE_CONFIGURATION_TYPES "Debug" CACHE STRING "" FORCE)
PHP errors can be displayed by any of below methods:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
For more details:
git checkout -b "Branch_name" [ B means Create local branch]
git branch --all
git checkout -b "Your Branch name"
git branch
successfully checkout from the master branch to dev branch
To change tab settings, click the text area right to the Ln/Col text in the status bar on the bottom right of vscode window.
The name can be Tab Size
or Spaces
.
A menu will pop up with all available actions and settings.
update
table1 t1
set
(
t1.column1,
t1.column2
) = (
select
t2.column1,
t2.column2
from
table2 t2
where
t2.column1 = t1.column1
)
where exists (
select
null
from
table2 t2
where
t2.column1 = t1.column1
);
Or this (if t2.column1 <=> t1.column1 are many to one and anyone of them is good):
update
table1 t1
set
(
t1.column1,
t1.column2
) = (
select
t2.column1,
t2.column2
from
table2 t2
where
t2.column1 = t1.column1
and
rownum = 1
)
where exists (
select
null
from
table2 t2
where
t2.column1 = t1.column1
);
In your model,
class Contact
self.email_providers = %w[Gmail Yahoo MSN]
validates :email_provider, :inclusion => email_providers
end
In your form,
<%= f.select :email_provider,
options_for_select(Contact.email_providers, @contact.email_provider) %>
the second arg of the options_for_select will have any current email_provider selected.
This code works for me:
public void Run()
{
Dog myDog = new Dog();
myDog.Name= "Foo";
myDog.Color = DogColor.Brown;
System.Console.WriteLine("{0}", myDog.ToString());
MemoryStream stream = SerializeToStream(myDog);
Dog newDog = (Dog)DeserializeFromStream(stream);
System.Console.WriteLine("{0}", newDog.ToString());
}
Where the types are like this:
[Serializable]
public enum DogColor
{
Brown,
Black,
Mottled
}
[Serializable]
public class Dog
{
public String Name
{
get; set;
}
public DogColor Color
{
get;set;
}
public override String ToString()
{
return String.Format("Dog: {0}/{1}", Name, Color);
}
}
and the utility methods are:
public static MemoryStream SerializeToStream(object o)
{
MemoryStream stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, o);
return stream;
}
public static object DeserializeFromStream(MemoryStream stream)
{
IFormatter formatter = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
object o = formatter.Deserialize(stream);
return o;
}
Try to configure the setting of your projects, it is usually due to x86/x64 architecture problems:
Go and set your choice as shown:
<Window x:Class="HTA.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
mc:Ignorable="d"
ResizeMode="NoResize"
WindowStartupLocation="CenterScreen"
Width="1024" Height="768"
WindowState="Maximized" WindowStyle="None">
Window state to Maximized and window style to None
In case anyone has the same problem in the future:
$ adb shell
$ su
# mount -o rw,remount /system
Both adb remount
and adb root
don't work on a production build without altering ro.secure, but you can still remount /system by opening a shell, asking for root permissions and typing the mount command.
Your data types are mismatched when you are retrieving the field values. Check your code and ensure that for each field that you are retrieving that the java object matches that type. For example, retrieving a date into and int. If you are doing a select * then it is possible a change in the fields of the table has happened causing this error to occur. Your SQL should only select the fields you specifically want in order to avoid this error.
Hope this helps.
To get list of all keys
using System.Linq;
List<String> myKeys = myDict.Keys.ToList();
System.Linq is supported in .Net framework 3.5 or above. See the below links if you face any issue in using System.Linq
I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc
Option 1
Create Procedure [Test] AS
DECLARE @StartDate varchar(10)
DECLARE @EndDate varchar(10)
Set @StartDate = '201620' --Define start YearWeek
Set @EndDate = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))
SELECT
*
FROM
(SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)
Option 2
Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS
SELECT
*
FROM
(SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)
Then run exec test '2016-01-01','2016-01-25'
I've found a solution for me with Spring and jackson
First specify the filter name in the entity
@Entity
@Table(name = "SECTEUR")
@JsonFilter(ModelJsonFilters.SECTEUR_FILTER)
public class Secteur implements Serializable {
/** Serial UID */
private static final long serialVersionUID = 5697181222899184767L;
/**
* Unique ID
*/
@Id
@JsonView(View.SecteurWithoutChildrens.class)
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@JsonView(View.SecteurWithoutChildrens.class)
@Column(name = "code", nullable = false, length = 35)
private String code;
/**
* Identifiant du secteur parent
*/
@JsonView(View.SecteurWithoutChildrens.class)
@Column(name = "id_parent")
private Long idParent;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "id_parent")
private List<Secteur> secteursEnfants = new ArrayList<>(0);
}
Then you can see the constants filters names class with the default FilterProvider used in spring configuration
public class ModelJsonFilters {
public final static String SECTEUR_FILTER = "SecteurFilter";
public final static String APPLICATION_FILTER = "ApplicationFilter";
public final static String SERVICE_FILTER = "ServiceFilter";
public final static String UTILISATEUR_FILTER = "UtilisateurFilter";
public static SimpleFilterProvider getDefaultFilters() {
SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAll();
return new SimpleFilterProvider().setDefaultFilter(theFilter);
}
}
Spring configuration :
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "fr.sodebo")
public class ApiRootConfiguration extends WebMvcConfigurerAdapter {
@Autowired
private EntityManagerFactory entityManagerFactory;
/**
* config qui permet d'éviter les "Lazy loading Error" au moment de la
* conversion json par jackson pour les retours des services REST<br>
* on permet à jackson d'acceder à sessionFactory pour charger ce dont il a
* besoin
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
// config d'hibernate pour la conversion json
mapper.registerModule(getConfiguredHibernateModule());//
// inscrit les filtres json
subscribeFiltersInMapper(mapper);
// config du comportement de json views
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
converter.setObjectMapper(mapper);
converters.add(converter);
}
/**
* config d'hibernate pour la conversion json
*
* @return Hibernate5Module
*/
private Hibernate5Module getConfiguredHibernateModule() {
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
Hibernate5Module module = new Hibernate5Module(sessionFactory);
module.configure(Hibernate5Module.Feature.FORCE_LAZY_LOADING, true);
return module;
}
/**
* inscrit les filtres json
*
* @param mapper
*/
private void subscribeFiltersInMapper(ObjectMapper mapper) {
mapper.setFilterProvider(ModelJsonFilters.getDefaultFilters());
}
}
Endly I can specify a specific filter in restConstoller when i need....
@RequestMapping(value = "/{id}/droits/", method = RequestMethod.GET)
public MappingJacksonValue getListDroits(@PathVariable long id) {
LOGGER.debug("Get all droits of user with id {}", id);
List<Droit> droits = utilisateurService.findDroitsDeUtilisateur(id);
MappingJacksonValue value;
UtilisateurWithSecteurs utilisateurWithSecteurs = droitsUtilisateur.fillLists(droits).get(id);
value = new MappingJacksonValue(utilisateurWithSecteurs);
FilterProvider filters = ModelJsonFilters.getDefaultFilters().addFilter(ModelJsonFilters.SECTEUR_FILTER, SimpleBeanPropertyFilter.serializeAllExcept("secteursEnfants")).addFilter(ModelJsonFilters.APPLICATION_FILTER,
SimpleBeanPropertyFilter.serializeAllExcept("services"));
value.setFilters(filters);
return value;
}
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param
to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
This makes sure that redirects work for all combinations of intransparent proxies.
This includes the case client <http> proxy <https> webserver.
# behind proxy
RewriteCond %{HTTP:X-FORWARDED-PROTO} ^http$
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
# plain
RewriteCond %{HTTP:X-FORWARDED-PROTO} ^$
RewriteCond %{REQUEST_SCHEME} ^http$ [NC,OR]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
For a one-liner you can use the pingouin.linear_regression function (disclaimer: I am the creator of Pingouin), which works with uni/multi-variate regression using NumPy arrays or Pandas DataFrame, e.g:
import pingouin as pg
# Using a Pandas DataFrame `df`:
lm = pg.linear_regression(df[['x', 'z']], df['y'])
# Using a NumPy array:
lm = pg.linear_regression(X, y)
The output is a dataframe with the beta coefficients, standard errors, T-values, p-values and confidence intervals for each predictor, as well as the R^2 and adjusted R^2 of the fit.
As a JavaScript/HTML/CSS obfuscator/compressor you can also try Patu Digua.
This helped me get close to what I needed and I will throw this out there for anyone else who needs it.
If you are looking for the value in the first cell in the selected column, you can try this. (I chose the first column, since you are asking for it to return "3", but you can change the number after Cells to get whichever column you need. Remember it is zero-based.)
This will copy the result to the clipboard:
Clipboard.SetDataObject(Me.DataGridView1.CurrentRow.Cells(0).Value)
This will find the index of the N'th smallest or largest value in the input numeric vector x. Set bottom=TRUE in the arguments if you want the N'th from the bottom, or bottom=FALSE if you want the N'th from the top. N=1 and bottom=TRUE is equivalent to which.min, N=1 and bottom=FALSE is equivalent to which.max.
FindIndicesBottomTopN <- function(x=c(4,-2,5,-77,99),N=1,bottom=FALSE)
{
k1 <- rank(x)
if(bottom==TRUE){
Nindex <- which(k1==N)
Nindex <- Nindex[1]
}
if(bottom==FALSE){
Nindex <- which(k1==(length(x)+1-N))
Nindex <- Nindex[1]
}
return(Nindex)
}
I think most people want their placeholder text to be in grey and appear only once, so this is what I did:
Set your color in viewDidLoad()
(not in IB)
commentsTextView.textColor = UIColor.darkGray
Implement UITextViewDelegate
to your controller
add function to your controller
func textViewDidBeginEditing(_ textView: UITextView) {
if (commentsTextView.textColor == UIColor.darkGray) {
commentsTextView.text = ""
commentsTextView.textColor = UIColor.black
}
}
This solution is simple.
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
In our case it was Windows-integrated authentication specified in the app's web.config
BUT the windows-auth module was not installed on the IIS machine at all.
Just adding another possible reason.
The problem I was having is my css media queries and my IF statement in Jquery clashing. They were both set to 700px but one would think it's hit 700px before the other.
To get around this I created a empty Div right at the top of my HTML(outside my main container)
<div id="max-width"></div>
In css I set this div to display none
#max-width {
display: none;
}
In my JS created a function
var hasSwitched = function () {
var maxWidth = parseInt($('#max-width').css('max-width'), 10);
return !isNaN(maxWidth);
};
So in my IF statement instead of saying if (hasSwitched<700) perform the following code, I did the following
if (!hasSwitched()) { Your code
}
else{ your code
}
By doing this CSS tells Jquery when it's hit 700px. So css and jquery are both synchronized... rather than having a couple of pixels difference. Do give this a try peeps it shall definitely not disappoint.
To get this same logic working for IE8 I used the Respond.js plugin(which also definitely works) It lets you use media queries for IE8. Only thing that wasn't supported was the viewport width and viewport height... hence my reason to try get my css and JS working together. Hope this helps you guys
You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html
geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.
ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()
Try to handler 'mousewheel' event on all nodes except one
$('body').on({
'mousewheel': function(e) {
if (e.target.id == 'el') return;
e.preventDefault();
e.stopPropagation();
}
})
Try this:
$("#" + newcol).attr("checked", "checked");
I've had issues with attr("checked", true)
, so I tend to use the above instead.
Also, if you have the ID then you don't need that other stuff for selection. An ID is unique.
I used a variant of Mateo's solution. I'm using this in Rmd files written in github flavored markdown (gfm) for a Jekyll powered website but the same Rmd files are being used to produce pdfs in various contexts. The Rmd files are math heavy and the math is displayed with MathJax on the website. So I needed a solution that works with gfm that is processed via Jekyll, works with pandoc->pdflatex, and is compatible with MathJax.
snippet from Rmd file (which is gfm)
Here is a paragraph with an footnote <span id="a1">[[1]](#f1)</span>.
Footnotes
=========
1. <span id="f1"></span> This is a footnote. [$\hookleftarrow$](#a1)
$\hookleftarrow$
is latex, which works for me since I always have MathJax enabled. I use that to make sure it shows up correctly in my pdfs. I put my footnotes in square brackets because superscript is confusing if I am putting a footnote on some inline math.
Here it is in action: https://eeholmes.github.io/posts/2016-5-18-FI-recursion-1/
These notes can be put anywhere in the Rmd. I am putting in a list at the end so they are technically endnotes.
There is a close() function for InfoWindows. Just keep track of the last opened window, and call the close function on it when a new window is created.
You can also use brackets <> on the URL of the view definition and this input will go into your view function arguments
@app.route('/<name>')
def my_view_func(name):
return name
Don't think it is supported yet. Take a look at this JIRA issue "Add delete topic support".
To delete manually:
log.dir
attribute in kafka config file ) as well the zookeeper dataFor any given topic what you can do is
/tmp/kafka-logs/MyTopic-0
where /tmp/kafka-logs
is specified by the log.dir
attributeThis is NOT
a good and recommended approach but it should work.
In the Kafka broker config file the log.retention.hours.per.topic
attribute is used to define The number of hours to keep a log file before deleting it for some specific topic
Also, is there a way the messages gets deleted as soon as the consumer reads it?
From the Kafka Documentation :
The Kafka cluster retains all published messages—whether or not they have been consumed—for a configurable period of time. For example if the log retention is set to two days, then for the two days after a message is published it is available for consumption, after which it will be discarded to free up space. Kafka's performance is effectively constant with respect to data size so retaining lots of data is not a problem.
In fact the only metadata retained on a per-consumer basis is the position of the consumer in in the log, called the "offset". This offset is controlled by the consumer: normally a consumer will advance its offset linearly as it reads messages, but in fact the position is controlled by the consumer and it can consume messages in any order it likes. For example a consumer can reset to an older offset to reprocess.
For finding the start offset to read in Kafka 0.8 Simple Consumer example they say
Kafka includes two constants to help,
kafka.api.OffsetRequest.EarliestTime()
finds the beginning of the data in the logs and starts streaming from there,kafka.api.OffsetRequest.LatestTime()
will only stream new messages.
You can also find the example code there for managing the offset at your consumer end.
public static long getLastOffset(SimpleConsumer consumer, String topic, int partition,
long whichTime, String clientName) {
TopicAndPartition topicAndPartition = new TopicAndPartition(topic, partition);
Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>();
requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(whichTime, 1));
kafka.javaapi.OffsetRequest request = new kafka.javaapi.OffsetRequest(requestInfo, kafka.api.OffsetRequest.CurrentVersion(),clientName);
OffsetResponse response = consumer.getOffsetsBefore(request);
if (response.hasError()) {
System.out.println("Error fetching data Offset Data the Broker. Reason: " + response.errorCode(topic, partition) );
return 0;
}
long[] offsets = response.offsets(topic, partition);
return offsets[0];
}
library(lubridate)
if your date format is like this '04/24/2017 05:35:00'then change it like below
prods.all$Date2<-gsub("/","-",prods.all$Date2)
then change the date format
parse_date_time(prods.all$Date2, orders="mdy hms")
Well, this is a terribly late answer but I think I'll still put my two cents in... I could have posted this as a comment because this answer doesn't essentially add any new solution but it does add value to the post as yet another alternative. But in a comment I wouldn't be able to give all the details because of character limit.
NOTE: This needs an edit to bootstrap CSS file - move style definitions for .badge
above .label-default
. Couldn't find any practical side effects due to the change in my limited testing.
While broc.seib's solution is probably the best way to achieve the requirement of OP with minimal addition to CSS, it is possible to achieve the same effect without any extra CSS at all just like Jens A. Koch's solution or by using .label-xxx
contextual classes because they are easy to remember compared to progress-bar-xxx
classes. I don't think that .alert-xxx
classes give the same effect.
All you have to do is just use .badge
and .label-xxx
classes together (but in this order). Don't forget to make the changes mentioned in NOTE above.
<a href="#">Inbox <span class="badge label-warning">42</span></a>
looks like this:
IMPORTANT: This solution may break your styles if you decide to upgrade and forget to make the changes in your new local CSS file. My solution for this challenge was to copy all .label-xxx
styles in my custom CSS file and load it after all other CSS files. This approach also helps when I use a CDN for loading BS3.
**P.S: ** Both the top rated answers have their pros and cons. It's just the way you prefer to do your CSS because there is no "only correct way" to do it.
For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 Now Just go Project under Project settings and select the project SDK.
HEAD is just a special pointer that points to the local branch you’re currently on.
From the Pro Git book, chapter 3.1 Git Branching - Branches in a Nutshell, in the section Creating a New Branch:
What happens if you create a new branch? Well, doing so creates a new pointer for you to move around. Let’s say you create a new branch called testing. You do this with the git branch command:
$ git branch testing
This creates a new pointer at the same commit you’re currently on
How does Git know what branch you’re currently on? It keeps a special pointer called HEAD. Note that this is a lot different than the concept of HEAD in other VCSs you may be used to, such as Subversion or CVS. In Git, this is a pointer to the local branch you’re currently on. In this case, you’re still on master. The git branch command only created a new branch — it didn’t switch to that branch.
Here's a dplyr
option:
library(dplyr)
# across all columns:
df %>% filter_all(any_vars(. %in% c('M017', 'M018')))
# or in only select columns:
df %>% filter_at(vars(col1, col2), any_vars(. %in% c('M017', 'M018')))
You can get the "search" part of the location object - and then parse it out.
var matches = /param1=([^&#=]*)/.exec(window.location.search);
var param1 = matches[1];
<td align="center" valign="center">textgoeshere</td>
Is the only correct answer imho, since your working with tables which is old functionality most common used for e-mail formatting. So your best bet is to not use just style but inline style and known table tags.
In practice, about methods:
protected - accessible for inherited classes, otherwise private.
internal - public only for classes inside the assembly, otherwise private.
protected internal - means protected or internal - methods become accessible for inherited classes and for any classes inside the assembly.
It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:
insert into errortable (dateupdated, table1id)
values (sysdate, 1083);
It seems silly to convert the system date to a string just to convert it back to a date.
If you want to see the full date, then you can do:
select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;
My descriptions for the three:
position: absolute
descendents)position: absolute
ones) without scrolling.Then there is also:
Check official git documentation:
If you use the SSH transport for connecting to remotes, it’s possible for you to have a key without a passphrase, which allows you to securely transfer data without typing in your username and password. However, this isn’t possible with the HTTP protocols – every connection needs a username and password. This gets even harder for systems with two-factor authentication, where the token you use for a password is randomly generated and unpronounceable.
Fortunately, Git has a credentials system that can help with this. Git has a few options provided in the box:
The default is not to cache at all. Every connection will prompt you for your username and password.
The “cache” mode keeps credentials in memory for a certain period of time. None of the passwords are ever stored on disk, and they are purged from the cache after 15 minutes.
The “store” mode saves the credentials to a plain-text file on disk, and they never expire. This means that until you change your password for the Git host, you won’t ever have to type in your credentials again. The downside of this approach is that your passwords are stored in cleartext in a plain file in your home directory.
If you’re using a Mac, Git comes with an “osxkeychain” mode, which caches credentials in the secure keychain that’s attached to your system account. This method stores the credentials on disk, and they never expire, but they’re encrypted with the same system that stores HTTPS certificates and Safari auto-fills.
If you’re using Windows, you can install a helper called “Git Credential Manager for Windows.” This is similar to the “osxkeychain” helper described above, but uses the Windows Credential Store to control sensitive information. It can be found at https://github.com/Microsoft/Git-Credential-Manager-for-Windows.
You can choose one of these methods by setting a Git configuration value:
$ git config --global credential.helper cache
$ git config --global credential.helper store
Sometimes it takes longer to figure out the regex than to just write it out in python:
import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
s = s.replace(char, ' ')
If you need other characters you can change it to use a white-list or extend your black-list.
Sample white-list:
whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
if char in whitelist:
new_s += char
else:
new_s += ' '
Sample white-list using a generator-expression:
whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)
Building on Alex's answer, here is a more generic function:
applyToGivenRow = @(func, matrix) @(row) func(matrix(row, :));
newApplyToRows = @(func, matrix) arrayfun(applyToGivenRow(func, matrix), 1:size(matrix,1), 'UniformOutput', false)';
takeAll = @(x) reshape([x{:}], size(x{1},2), size(x,1))';
genericApplyToRows = @(func, matrix) takeAll(newApplyToRows(func, matrix));
Here is a comparison between the two functions:
>> % Example
myMx = [1 2 3; 4 5 6; 7 8 9];
myFunc = @(x) [mean(x), std(x), sum(x), length(x)];
>> genericApplyToRows(myFunc, myMx)
ans =
2 1 6 3
5 1 15 3
8 1 24 3
>> applyToRows(myFunc, myMx)
??? Error using ==> arrayfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.
Error in ==> @(func,matrix)arrayfun(applyToGivenRow(func,matrix),1:size(matrix,1))'
Here is my solution:
axios({
method: "POST",
url: "https://URL.com/api/services/fetchQuizList",
headers: {
"x-access-key": data,
"x-access-token": token,
},
data: {
quiz_name: quizname,
},
})
.then(res => {
console.log("res", res.data.message);
})
.catch(err => {
console.log("error in request", err);
});
This should help
Jon Skeets answer is right and has deserved my upvote, just adding this slightly different solution for completeness:
import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.withDayOfMonth(1);
LocalDate end = initial.with(lastDayOfMonth());
Something to be careful about when designing a RESTful API is the conflation of GET and POST, as if they were the same thing. It's easy to make this mistake with Django's function-based views and CherryPy's default dispatcher, although both frameworks now provide a way around this problem (class-based views and MethodDispatcher, respectively).
HTTP-verbs are very important in REST, and unless you're very careful about this, you'll end up falling into a REST anti-pattern.
Some frameworks that get it right are web.py, Flask and Bottle. When combined with the mimerender library (full disclosure: I wrote it), they allow you to write nice RESTful webservices:
import web
import json
from mimerender import mimerender
render_xml = lambda message: '<message>%s</message>'%message
render_json = lambda **args: json.dumps(args)
render_html = lambda message: '<html><body>%s</body></html>'%message
render_txt = lambda message: message
urls = (
'/(.*)', 'greet'
)
app = web.application(urls, globals())
class greet:
@mimerender(
default = 'html',
html = render_html,
xml = render_xml,
json = render_json,
txt = render_txt
)
def GET(self, name):
if not name:
name = 'world'
return {'message': 'Hello, ' + name + '!'}
if __name__ == "__main__":
app.run()
The service's logic is implemented only once, and the correct representation selection (Accept header) + dispatch to the proper render function (or template) is done in a tidy, transparent way.
$ curl localhost:8080/x
<html><body>Hello, x!</body></html>
$ curl -H "Accept: application/html" localhost:8080/x
<html><body>Hello, x!</body></html>
$ curl -H "Accept: application/xml" localhost:8080/x
<message>Hello, x!</message>
$ curl -H "Accept: application/json" localhost:8080/x
{'message':'Hello, x!'}
$ curl -H "Accept: text/plain" localhost:8080/x
Hello, x!
Update (April 2012): added information about Django's class-based views, CherryPy's MethodDispatcher and Flask and Bottle frameworks. Neither existed back when the question was asked.
Try this regex:
^(\+?\d{1,4}[\s-])?(?!0+\s+,?$)\d{10}\s*,?$
Explanation of the regex using Perl's YAPE is as below:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
( group and capture to \1 (optional
(matching the most amount possible)):
----------------------------------------------------------------------
\+? '+' (optional (matching the most amount
possible))
----------------------------------------------------------------------
\d{1,4} digits (0-9) (between 1 and 4 times
(matching the most amount possible))
----------------------------------------------------------------------
[\s-] any character of: whitespace (\n, \r,
\t, \f, and " "), '-'
----------------------------------------------------------------------
)? end of \1 (NOTE: because you are using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in \1)
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
0+ '0' (1 or more times (matching the most
amount possible))
----------------------------------------------------------------------
\s+ whitespace (\n, \r, \t, \f, and " ") (1
or more times (matching the most amount
possible))
----------------------------------------------------------------------
,? ',' (optional (matching the most amount
possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of
the string
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
\d{10} digits (0-9) (10 times)
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
,? ',' (optional (matching the most amount
possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
To remove spaces from left/right, use LTRIM/RTRIM. What you had
UPDATE *tablename*
SET *columnname* = LTRIM(RTRIM(*columnname*));
would have worked on ALL the rows. To minimize updates if you don't need to update, the update code is unchanged, but the LIKE expression in the WHERE clause would have been
UPDATE [tablename]
SET [columnname] = LTRIM(RTRIM([columnname]))
WHERE 32 in (ASCII([columname]), ASCII(REVERSE([columname])));
Note: 32 is the ascii code for the space character.
You can compile with either Cygwin's g++
or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll
(and others) PATH to the system Windows PATH, before any cygwin style paths.
Thus add: ;C:\cygwin64\bin
to the end of your Windows system PATH
variable.
Also, to compile for use in CMD or PowerShell, you may need to use:
x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe
(This invokes the cross-compiler, if installed.)
The "pause" command was a function button underneath my right shift key, so the below combination of keys did the trick for me.
Ctrl + Fn + Shift
I know I'm late to the party, but try this...
SELECT
`Train`,
`Dest`,
SUBSTRING_INDEX(GROUP_CONCAT(`Time` ORDER BY `Time` DESC), ",", 1) AS `Time`
FROM TrainTable
GROUP BY Train;
Src: Group Concat Documentation
Edit: fixed sql syntax
Use FCPATH instead of BASEPATH for more check this link.
Codeigniter - dynamically getting relative/absolute path outside of application folder
How about
sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub
Try this
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Range("A" & i & ":" & "Z" & i)
Else
Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
IF you want to delete the entire row then use this code
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Rows(i)
Else
Set DelRange = Union(DelRange, Rows(i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
git reset --soft commit_id
git stash save "message"
git reset --hard commit_id
git stash apply stash stash@{0}
git push --force
In ActiveForm
just use:
<?=
$form->field($model, 'state_id')
->dropDownList(['prompt' => '---- Select State ----'])
->label('State')
?>
It seemed quite hard to find this information, but eventually, I came across this question
You have to look at the 'System' event log, and filter by the WAS source.
Here is more info about the WAS (Windows Process Activation Service)
I just found this error., while using GETDATE() [i.e outer reference] in the group by clause in a select query.
When replaced it with date column from the respective table it cleared.
Thought to share as a simple example. cheers ;)
No. The method for appending an entire sequence is list.extend()
.
>>> L = [1, 2]
>>> L.extend((3, 4, 5))
>>> L
[1, 2, 3, 4, 5]
This function found here, works fine for me
function jsonRemoveUnicodeSequences($struct) {
return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}
You can get it by XMLHttpRequest.responseText
in XMLHttpRequest.onreadystatechange
when XMLHttpRequest.readyState
equals to XMLHttpRequest.DONE
.
Here's an example (not compatible with IE6/7).
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.
$.get('http://example.com', function(responseText) {
alert(responseText);
});
Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.
You have two options; either handle the exception or test the length:
if len(dlist) > 1:
newlist.append(dlist[1])
continue
or
try:
newlist.append(dlist[1])
except IndexError:
pass
continue
Use the first if there often is no second item, the second if there sometimes is no second item.
&
) to the beginning of the entry. Why not use a new Scanner for every reading? Like below. With this approach you will not confront your problem.
int i = new Scanner(System.in).nextInt();
$('#timePicker').datetimepicker({
// dateFormat: 'dd-mm-yy',
format:'DD/MM/YYYY HH:mm:ss',
minDate: getFormattedDate(new Date())
});
function getFormattedDate(date) {
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear().toString().slice(2);
return day + '-' + month + '-' + year;
}
You need to pass datepicker() the date formatted correctly.
To add a new directory all you have to do is create a new folder in your local repository. Create a new folder, and add a file in it.
Now go to your terminal and add it like you add the normal files in Git. Push them into the repository, and check the status to make sure you have created a directory.
I use the code to increase the default limit globally:
require('events').EventEmitter.prototype._maxListeners = 100;
You can use the default traceroute
command for this purpose, then there will be nothing to install.
traceroute -T -p 9100 <IP address/hostname>
The -T
argument is required so that the TCP protocol is used instead of UDP.
In the rare case when traceroute
isn't available, you can also use ncat
.
nc -Czvw 5 <IP address/hostname> 9100
The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:
import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square')
plt.xlabel('x')
plt.ylabel('y')
plt.xticks(xi, x)
plt.title('compare')
plt.legend()
plt.show()
SQL Developer Version 4.1.0.19
Step 1: Go to Tools -> Preferences
Step 2: Select Database -> NLS
Step 3: Go to Date Format and Enter DD-MON-RR HH24: MI: SS
Step 4: Click OK.
If you specify the disabled
attribute then the value you give it must be disabled
. (In HTML 5 you may leave off everything except the attribute value. In HTML 4 you may leave off everything except the attribute name.)
If you do not want the control to be disabled then do not specify the attribute at all.
Disabled:
<input type="checkbox" disabled>
<input type="checkbox" disabled="disabled">
Enabled:
<input type="checkbox">
Invalid (but usually error recovered to be treated as disabled):
<input type="checkbox" disabled="1">
<input type="checkbox" disabled="true">
<input type="checkbox" disabled="false">
So, without knowing your template language, I guess you are looking for:
<td><input type="checkbox" name="repriseCheckBox" {checkStat == 1 ? disabled : }/></td>
You need to publish the app before it becomes available for testing.
if you publish the app and the apk is only in "alpha testing" section then it is NOT available to general public, only for activated testers in the alpha section.
EDIT: One additional note: "normal" users will not find your app on Google Play, but also the activated tester can not find the application by using the search box.
Only the direct link to the application package will work. (only for the activated testers).
I feel the performance characteristics change from one DBMS to another. It's all on how they choose to implement it. Since I have worked extensively on Oracle, I'll tell from that perspective.
COUNT(*)
- Fetches entire row into result set before passing on to the count function, count function will aggregate 1 if the row is not null
COUNT(1)
- Will not fetch any row, instead count is called with a constant value of 1 for each row in the table when the WHERE
matches.
COUNT(PK)
- The PK in Oracle is indexed. This means Oracle has to read only the index. Normally one row in the index B+ tree is many times smaller than the actual row. So considering the disk IOPS rate, Oracle can fetch many times more rows from Index with a single block transfer as compared to entire row. This leads to higher throughput of the query.
From this you can see the first count is the slowest and the last count is the fastest in Oracle.
This solution is similar to walid2mi (thank you for inspiration), but allows the standard console input by the Read-Host cmdlet.
pros:
cons:
Commented and runable example of batch-ps-script.cmd:
<# : Begin batch (batch script is in commentary of powershell v2.0+)
@echo off
: Use local variables
setlocal
: Change current directory to script location - useful for including .ps1 files
cd %~dp0
: Invoke this file as powershell expression
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
: Restore environment variables present before setlocal and restore current directory
endlocal
: End batch - go to end of file
goto:eof
#>
# here start your powershell script
# example: include another .ps1 scripts (commented, for quick copy-paste and test run)
#. ".\anotherScript.ps1"
# example: standard input from console
$variableInput = Read-Host "Continue? [Y/N]"
if ($variableInput -ne "Y") {
Write-Host "Exit script..."
break
}
# example: call standard powershell command
Get-Item .
Snippet for .cmd file:
<# : batch script
@echo off
setlocal
cd %~dp0
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
endlocal
goto:eof
#>
# here write your powershell commands...
Action
is a Type of Delegate provided by the .NET framework. The Action
points to a method with no parameters and does not return a value.
() =>
is lambda expression syntax. Lambda expressions are not of Type Delegate
. Invoke requires Delegate
so Action
can be used to wrap the lambda expression and provide the expected Type
to Invoke()
Invoke
causes said Action
to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions
. For example, if one tries to set the Rtf
property on a RichTextBox
when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid
exception will be thrown. Check Control.InvokeRequired
before calling Invoke.
BeginInvoke
is the Asynchronous version of Invoke
. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.
As RPM1984 refers to, this is mostly likely caused by the fact that your script is loading before jQuery is loaded.
There's also the function tags, a bit more flexible:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">
And here's the tag documentation.
Add this one to your html if you only have access to the html:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i, parameter = 0;
if (argc >= 2) {
/* there is 1 parameter (or more) in the command line used */
/* argv[0] may point to the program name */
/* argv[1] points to the 1st parameter */
/* argv[argc] is NULL */
parameter = atoi(argv[1]); /* better to use strtol */
if (parameter > 0) {
for (i = 0; i < parameter; i++) printf("%d ", i);
} else {
fprintf(stderr, "Please use a positive integer.\n");
}
}
return 0;
}
here's my solution with perl based on former answer, replaces environment variables:
perl -p -e 's/\$\{(\w+)\}/(exists $ENV{$1}?$ENV{$1}:"missing variable $1")/eg' < infile > outfile
I don't like all the solutions that use magic numbers like 97
or 36
.
const A = 'A'.charCodeAt(0);
let numberToCharacter = number => String.fromCharCode(A + number);
let characterToNumber = character => character.charCodeAt(0) - A;
this assumes uppercase letters and starts 'A' at 0.
As of Bootstrap 4, you can use the spacing utilities.
Add for instance px-2
in the classes of the nav-item
to increase the padding.
It's not print that does the formatting, It's a property of strings, so you can just use
newstring = "%.9f" % numvar
I used the Visual Studio 2008 Uninstall tool and it worked fine for me.
You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).
Found here, on the MSDN Forum: MSDN forum topic.
I found this answer here
Be sure you run the tool with admin-rights.
Please Install SQL Server Data Tools from link (SSDT)
You can also Install it when you are installing Visual Studio there is Option "Data Storage and Processing" you must be select while installing Visual Studio
I have used mpdf in my project. In Codeigniter-3, putted mpdf files under application/third_party and then used in this way:
/**
* This function is used to display data in PDF file.
* function is using mpdf api to generate pdf.
* @param number $id : This is unique id of table.
*/
function generatePDF($id){
require APPPATH . '/third_party/mpdf/vendor/autoload.php';
//$mpdf=new mPDF();
$mpdf = new mPDF('utf-8', 'Letter', 0, '', 0, 0, 7, 0, 0, 0);
$checkRecords = $this->user_model->getCheckInfo($id);
foreach ($checkRecords as $key => $value) {
$data['info'] = $value;
$filename = $this->load->view(CHEQUE_VIEWS.'index',$data,TRUE);
$mpdf->WriteHTML($filename);
}
$mpdf->Output(); //output pdf document.
//$content = $mpdf->Output('', 'S'); //get pdf document content's as variable.
}
reflect.DeepEqual
is often incorrectly used to compare two like structs, as in your question.
cmp.Equal
is a better tool for comparing structs.
To see why reflection is ill-advised, let's look at the documentation:
Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.
....
numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.
If we compare two time.Time
values of the same UTC time, t1 == t2
will be false if their metadata timezone is different.
go-cmp
looks for the Equal()
method and uses that to correctly compare times.
Example:
m1 := map[string]int{
"a": 1,
"b": 2,
}
m2 := map[string]int{
"a": 1,
"b": 2,
}
fmt.Println(cmp.Equal(m1, m2)) // will result in true
SomeVal=ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value
did not work. However the following code only worked for me.
SomeVal = ThisWorkbook.Sheets(2).cells(aRow,aCol).Value
I wrote template-colors-web https://github.com/icodeforlove/Console.js to allow us to do this a bit easier
console.log(c`red ${c`green ${'blue'.bold}.blue`}.green`.red);
The above would be extremely hard to do with the default console.log.
For a live interactive demo click here.
For SQL Server 2012 and later versions, the best method is @MajidBasirati's answer.
I also loved @CarlosToledo's answer, it's not limited to any SQL Server version but it's missing Order By Clauses. Without them, it may return wrong results.
For SQL Server 2008 and later I would use Common Table Expressions for better performance.
-- This example omits first 10 records and select next 5 records
;WITH MyCTE(Id) as
(
SELECT TOP (10) Id
FROM MY_TABLE
ORDER BY Id
)
SELECT TOP (5) *
FROM MY_TABLE
INNER JOIN MyCTE ON (MyCTE.Id <> MY_TABLE.Id)
ORDER BY Id
More accurately...
while IFS= read -r line ; do
printf "%s\n" "$line"
done < file
I managed to work out the answer by reading the manual :)
This extract from the MSDN
The code example avoids a deadlock condition by calling p.StandardOutput.ReadToEnd before p.WaitForExit. A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardOutput.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardOutput stream.
There is a similar issue when you read all text from both the standard output and standard error streams. For example, the following C# code performs a read operation on both streams.
Turns the code into this;
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "sqlplus";
p.StartInfo.Arguments = string.Format("xxx/xxx@{0} @{1}", in_database, s);
bool started = p.Start();
// important ... read stream input before waiting for exit.
// this avoids deadlock.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
if (p.ExitCode != 0)
{
Console.WriteLine( string.Format("*** Failed : {0} - {1}",s,p.ExitCode));
break;
}
Which now exits correctly.
Old style using ResultSet
@Transactional(readOnly=true)
public void accessUser() {
EntityManager em = this.getEntityManager();
org.hibernate.Session session = em.unwrap(org.hibernate.Session.class);
session.doWork(new Work() {
@Override
public void execute(Connection con) throws SQLException {
try (PreparedStatement stmt = con.prepareStatement(
"SELECT u.username, u.name, u.email, 'blabla' as passe, login_type as loginType FROM users u")) {
ResultSet rs = stmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rsmd.getColumnName(i) + " (" + rsmd.getColumnTypeName(i) + ") / ");
}
System.out.println("");
while (rs.next()) {
System.out.println("Found username " + rs.getString("USERNAME") + " name " + rs.getString("NAME") + " email " + rs.getString("EMAIL") + " passe " + rs.getString("PASSE") + " email " + rs.getInt("LOGIN_TYPE"));
}
}
}
});
}
For the purpose of comparing two objects, the simplest way to do this would be to add a unique property to one of the objects at the time you need to compare the objects, check if the property exists in the other and then remove it again. This saves overriding prototypes.
function isSameObject(objectA, objectB) {
unique_ref = "unique_id_" + performance.now();
objectA[unique_ref] = true;
isSame = objectB.hasOwnProperty(unique_ref);
delete objectA[unique_ref];
return isSame;
}
object1 = {something:true};
object2 = {something:true};
object3 = object1;
console.log(isSameObject(object1, object2)); //false
console.log(isSameObject(object1, object3)); //true
I also had this issue and what I did was create an AlertDialog and use the setItems() method along with the DialogInterface listener:
AlertDialog.Builder getImageFrom = new AlertDialog.Builder(Fotos.this);
getImageFrom.setTitle("Select:");
final CharSequence[] opsChars = {getResources().getString(R.string.takepic), getResources().getString(R.string.opengallery)};
getImageFrom.setItems(opsChars, new android.content.DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == 0){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}else
if(which == 1){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
getResources().getString(R.string.pickgallery)), SELECT_PICTURE);
}
dialog.dismiss();
}
});
For Python 3:
ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
ListOfStrings[idx] = "bar"
Calling p.plot
after setting the limits is why it is rescaling. You are correct in that turning autoscaling off will get the right answer, but so will calling xlim()
or ylim()
after your plot
command.
I use this quite a lot to invert the x axis, I work in astronomy and we use a magnitude system which is backwards (ie. brighter stars have a smaller magnitude) so I usually swap the limits with
lims = xlim()
xlim([lims[1], lims[0]])
Here is another way:
df[[i for i in list(df.columns) if i != '<your column>']]
You just pass all columns to be shown except of the one you do not want.
We can use paste0:
df$combField <- paste0(df$x, df$y)
If you do not want any padding space introduced in the concatenated field. This is more useful if you are planning to use the combined field as a unique id that represents combinations of two fields.
You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix
component is no longer included:
Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.
preg_replace("/[[:blank:]]+/"," ",$input)
ADD go /usr/local/
will copy the contents of your local go
directory in the /usr/local/
directory of your docker image.
To copy the go
directory itself in /usr/local/
use:
ADD go /usr/local/go
or
COPY go /usr/local/go
You installed java...
apt-get install default-jre
But not the JDK...
apt-get install default-jdk
Sampling randomizes, so just sample the entire data frame.
df.sample(frac=1)
Here is a bash script inspired by abarnert's answer which will unpack a package named MyPackage.pkg
into a subfolder named MyPackage_pkg
and then open the folder in Finder.
#!/usr/bin/env bash
filename="$*"
dirname="${filename/\./_}"
pkgutil --expand "$filename" "$dirname"
cd "$dirname"
tar xvf Payload
open .
Usage:
pkg-upack.sh MyPackage.pkg
Warning: This will not work in all cases, and will fail with certain files, e.g. the PKGs inside the OSX system installer. If you want to peek inside the pkg file and see what's inside, you can try SuspiciousPackage (free app), and if you need more options such as selectively unpacking specific files, then have a look at Pacifist (nagware).
I modified @kolbyjack code to make it work for
http://website1/service
http://website1/service/
with parameters
location ~ ^/service/?(.*) {
return 301 http://service_url/$1$is_args$args;
}
The GMaps Utility Library has a plugin called MapIconMaker that makes it easy to generate different marker styles on the fly. It uses Google Charts to draw the markers.
There's a good demo here that shows what kind of markers you can make with it.
You don't need to escape the '
character in a String (wrapped in "
), and you don't have to escape a "
character in a char (wrapped in '
).
Here is an alternative way that doesn't override the existing certificates: [bash fragment for linux systems]
certificateFile="MyCa.cert.pem"
certificateName="MyCA Name"
for certDB in $(find ~/.mozilla* ~/.thunderbird -name "cert8.db")
do
certDir=$(dirname ${certDB});
#log "mozilla certificate" "install '${certificateName}' in ${certDir}"
certutil -A -n "${certificateName}" -t "TCu,Cuw,Tuw" -i ${certificateFile} -d ${certDir}
done
You may find certutil in the libnss3-tools package (debian/ubuntu).
See also:
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/tools/NSS_Tools_certutil
Update your IDE with the latest PDT version for better code formatting. On the main menu click Help -> Install New Software and then add the following URL in the Work with field:
http://download.eclipse.org/tools/pdt/updates/4.0.1
When asked for the name, give it PDT4.0.1
and then move along with the update or install.
It will see if the appropriate PDT is already installed or if it is a lower version, which then would be updated.
After restarting or applying the changes go to Windows -> Preferences on the side bar and expand PHP -> Code Style. Here you will see an item named Formatter. Select it and choose the active profile for the code formating. Thats it.
The next time you format it, it will choose a format according to the chosen active profile.
Hope it helps.
[
These days, the unexpected [
array bracket is commonly seen on outdated PHP versions. The short array syntax is available since PHP >= 5.4. Older installations only support array()
.
$php53 = array(1, 2, 3);
$php54 = [1, 2, 3];
?
Array function result dereferencing is likewise not available for older PHP versions:
$result = get_whatever()["key"];
?
Reference - What does this error mean in PHP? - "Syntax error, unexpected \[
" shows the most common and practical workarounds.
Though, you're always better off just upgrading your PHP installation. For shared webhosting plans, first research if e.g. SetHandler php56-fcgi
can be used to enable a newer runtime.
See also:
BTW, there are also preprocessors and PHP 5.4 syntax down-converters if you're really clingy with older + slower PHP versions.
Other causes for Unexpected [
syntax errors
If it's not the PHP version mismatch, then it's oftentimes a plain typo or newcomer syntax mistake:
You can't use array property declarations/expressions in classes, not even in PHP 7.
protected $var["x"] = "Nope";
?
Confusing [
with opening curly braces {
or parentheses (
is a common oversight.
foreach [$a as $b)
?
Or even:
function foobar[$a, $b, $c] {
?
Or trying to dereference constants (before PHP 5.6) as arrays:
$var = const[123];
?
At least PHP interprets that const
as a constant name.
If you meant to access an array variable (which is the typical cause here), then add the leading $
sigil - so it becomes a $varname
.
You are trying to use the global
keyword on a member of an associative array. This is not valid syntax:
global $var['key'];
]
closing square bracketThis is somewhat rarer, but there are also syntax accidents with the terminating array ]
bracket.
Again mismatches with )
parentheses or }
curly braces are common:
function foobar($a, $b, $c] {
?
Or trying to end an array where there isn't one:
$var = 2];
Which often occurs in multi-line and nested array declarations.
$array = [1,[2,3],4,[5,6[7,[8],[9,10]],11],12]],15];
?
If so, use your IDE for bracket matching to find any premature ]
array closure. At the very least use more spacing and newlines to narrow it down.
Solution for Preact with preact-router
Works with refresh and direct access
For those discovering this via Google, here's a demo of preact-router + hash history:
const { h, Component, render } = preact; /** @jsx h */
const { Router } = preactRouter;
const { createHashHistory } = History;
const App = () => (
<div>
<AddressBar />
<Router history={createHashHistory()}>
<div path="/">
<p>
all paths in preact-router are still /normal/urls.
using hash history rewrites them to /#/hash/urls
</p>
Example: <a href="/page2">page 2</a>
</div>
<div path="/page2">
<p>Page Two</p>
<a href="/">back to home</a><br/>
</div>
</Router>
</div>
);
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"First",@"Second", nil];
NSMutableArray *copiedArray = [array mutableCopy];
NSMutableArray *retainedArray = [array retain];
[retainedArray addObject:@"Retained Third"];
[copiedArray addObject:@"Copied Third"];
NSLog(@"array = %@",array);
NSLog(@"Retained Array = %@",retainedArray);
NSLog(@"Copied Array = %@",copiedArray);
array = (
First,
Second,
"Retained Third"
)
Retained Array = (
First,
Second,
"Retained Third"
)
Copied Array = (
First,
Second,
"Copied Third"
)
I think Semaphore is what you are looking for, it will block the main process after counting down to 0. Sample code:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# simulate a time-consuming task by sleeping
time.sleep(5)
# `release` will add 1 to `sema`, allowing other
# processes blocked on it to continue
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
# once 20 processes are running, the following `acquire` call
# will block the main process since `sema` has been reduced
# to 0. This loop will continue only after one or more
# previously created processes complete.
sema.acquire()
p = Process(target=f, args=(i, sema))
all_processes.append(p)
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The following code is more structured since it acquires and releases sema
in the same function. However, it will consume too much resources if total_task_num
is very large:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# `sema` is acquired and released in the same
# block of code here, making code more readable,
# but may lead to problem.
sema.acquire()
time.sleep(5)
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
p = Process(target=f, args=(i, sema))
all_processes.append(p)
# the following line won't block after 20 processes
# have been created and running, instead it will carry
# on until all 1000 processes are created.
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The above code will create total_task_num
processes but only concurrency
processes will be running while other processes are blocked, consuming precious system resources.
Can try this too!
Create a dictionary of replacement values.
import pandas as pd
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
replace_dict= {0:'Female',1:'Male'}
print(replace_dict)
Use the map function for replacing values
data['sex']=data['sex'].map(replace_dict)
There are already many good answers to the part "what is uintptr_t data type". I will try to address the "what it can be used for?" part in this post.
Primarily for bitwise operations on pointers. Remember that in C++ one cannot perform bitwise operations on pointers. For reasons see Why can't you do bitwise operations on pointer in C, and is there a way around this?
Thus in order to do bitwise operations on pointers one would need to cast pointers to type unitpr_t and then perform bitwise operations.
Here is an example of a function that I just wrote to do bitwise exclusive or of 2 pointers to store in a XOR linked list so that we can traverse in both directions like a doubly linked list but without the penalty of storing 2 pointers in each node.
template <typename T>
T* xor_ptrs(T* t1, T* t2)
{
return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(t1)^reinterpret_cast<uintptr_t>(t2));
}
If you want to retrieve POST data:
first_name = request.form.get("firstname")
If you want to retrieve GET (query string) data:
first_name = request.args.get("firstname")
Or if you don't care/know whether the value is in the query string or in the post data:
first_name = request.values.get("firstname")
request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.
Map
is an interface; HashMap
is a particular implementation of that interface.
HashMap uses a collection of hashed key values to do its lookup. TreeMap will use a red-black tree as its underlying data store.
This is specific for each site. So if you type that once, you will only get through that site and all other sites will need a similar type-through.
It is also remembered for that site and you have to click on the padlock to reset it (so you can type it again):
Needless to say use of this "feature" is a bad idea and is unsafe - hence the name.
You should find out why the site is showing the error and/or stop using it until they fix it. HSTS specifically adds protections for bad certs to prevent you clicking through them. The fact it's needed suggests there is something wrong with the https connection - like the site or your connection to it has been hacked.
The chrome developers also do change this periodically. They changed it recently from badidea
to thisisunsafe
so everyone using badidea
, suddenly stopped being able to use it. You should not depend on it. As Steffen pointed out in the comments below, it is available in the code should it change again though they now base64 encode it to make it more obscure. The last time they changed they put this comment in the commit:
Rotate the interstitial bypass keyword
The security interstitial bypass keyword hasn't changed in two years and awareness of the bypass has been increased in blogs and social media. Rotate the keyword to help prevent misuse.
I think the message from the Chrome team is clear - you should not use it. It would not surprise me if they removed it completely in future.
If you are using this when using a self-signed certificate for local testing then why not just add your self-signed certificate certificate to your computer's certificate store so you get a green padlock and do not have to type this? Note Chrome insists on a SAN
field in certificates now so if just using the old subject
field then even adding it to the certificate store will not result in a green padlock.
If you leave the certificate untrusted then certain things do not work. Caching for example is completely ignored for untrusted certificates. As is HTTP/2 Push.
HTTPS is here to stay and we need to get used to using it properly - and not bypassing the warnings with a hack that is liable to change and doesn't work the same as a full HTTPS solution.
If you only need the time from the date, you can just use the feature of String.
Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );
This will automatically cut the time part of the String and save it inside the timeString
.
You could write a method to print a 2d array like this:
//Displays a 2d array in the console, one line per row.
static void printMatrix(int[][] grid) {
for(int r=0; r<grid.length; r++) {
for(int c=0; c<grid[r].length; c++)
System.out.print(grid[r][c] + " ");
System.out.println();
}
}
The Yahoo! Exceptional Performance team recommend placing scripts at the bottom of your page because of the way browsers download components.
Of course Levi's comment "just before you need it and no sooner" is really the correct answer, i.e. "it depends".
After further investigating on PSExec tool, I think I got the answer. I need to add -i option to tell PSExec to launch process on remote in interactive mode:
PSExec \\RPC001 -i -u myID -p myPWD PowerShell C:\script\StartPS.ps1 par1 par2
Without -i, powershell.exe is running on the remote in waiting mode. Interesting point is that if I run a simple bat (without PS in bat), it works fine. Maybe this is something special for PS case? Welcome comments and explanations.
The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.
If the URL of your website is: http://www.example.com/mywebsite/
then starting at the root level starts above the "mywebsite" folder path.
It seems that, according to the HTML5 spec, the value property of the textarea element should return '\r\n' for a newline:
The element's value is defined to be the element's raw value with the following transformation applied:
Replace every occurrence of a "CR" (U+000D) character not followed by a "LF" (U+000A) character, and every occurrence of a "LF" (U+000A) character not preceded by a "CR" (U+000D) character, by a two-character string consisting of a U+000D CARRIAGE RETURN "CRLF" (U+000A) character pair.
Following the link to 'value' makes it clear that it refers to the value property accessed in javascript:
Form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.
However, in all five major browsers (using Windows, 11/27/2015), if '\r\n' is written to a textarea, the '\r' is stripped. (To test: var e=document.createElement('textarea'); e.value='\r\n'; alert(e.value=='\n');) This is true of IE since v9. Before that, IE was returning '\r\n' and converting both '\r' and '\n' to '\r\n' (which is the HTML5 spec). So... I'm confused.
To be safe, it's usually enough to use '\r?\n' in regular expressions instead of just '\n', but if the newline sequence must be known, a test like the above can be performed in the app.
I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:
gcc -o exec main.o add.o
But my program is a C++ program. Using the g++
compiler solved my issue:
g++ -o exec main.o add.o
I was always under the impression that gcc
could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.
To use the environment virtualenv has created, you first need to source env/bin/activate
. After that, just install packages using pip install package-name
.
I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:
action="javascript:checkout()"
You try this?
Don't forget include the script reference in the html head.
I don't know cause of that works in firefox. Regards.
So after a half day on this and almost immediately after posting my question I found the answer. Bundler 1.5.0 has a bug where it doesn't recognize default gems as referenced here
The solution was to update to bundler 1.5.1 using gem install bundler -v '= 1.5.1'
I have found an excellent and relatively short explanation here.
A multipart request is a REST request containing several packed REST requests inside its entity.
=SUBSTITUTE(text, old_text, new_text)
if: a=!, b=@, c=#,... x=>, y=?, z=~, " "=" "
then: abcdefghijklmnopqrstuvwxyz ... try this out
equals: !@#$%^&*()-=+[]\{}|;:/<>?~ ... ;}? ;*(| ]:;
(1) text to substitute is in cell A1
(2) max 64 substitution levels (the formula below only has 27 levels [alphabet + space])
(2) "old_text" cannot also be a "new_text" (ie: if a=z .: z cannot be "old text")
---so if a=z,b=y,...y=b,z=a, then the result is
---abcdefghijklmnopqrstuvwxyz = zyxwvutsrqponnopqrstuvwxyz (and z changes to a then changes back to z) ... (pattern starts to fail after m=n, n=m... and n becomes n)
The formula is:
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"a","!"),"b","@"),"c","#"),"d","$"),"e","%"),"f","^"),"g","&"),"h","*"),"i","("),"j",")"),"k","-"),"l","="),"m","+"),"n","["),"o","]"),"p","\"),"q","{"),"r","}"),"s","|"),"t",";"),"u",":"),"v","/"),"w","<"),"x",">"),"y","?"),"z","~")," "," ")
I'm using Excel 2003 -
The problem with using conditional formatting here is that you can't reference another worksheet or workbook in your conditions. What you can to do is set some column on sheet 1 equal to the appropriate column on sheet 2 (in your example =Sheet2!B6). I used Column F in my example below. Then you can use conditional formatting. Select the cell at Sheet 1, row , column 1 and then go to the conditional formatting menu. Choose "Formula Is" from the drop down and set the condition to "=$F$6=4". Click on the format button and then choose the Patterns tab. Choose the color you want and you're done.
You can use the format painter tool to apply conditional formatting to other cells, but be aware that by default Excel uses absolute references in the conditions. If you want them to be relative you'll need to remove the dollar signs from the condition.
You can have up to 3 conditions applied to a cell (use the add >> button at the bottom of the Conditional formatting dialog) so if the last row is fixed (for example, you know that it will always be row 10) you can use it as a condition to set the background color to none. Assuming that the last value you care about is in row 10 then (still assuming that you've set column F on sheet1 to the corresponding cells on sheet 2) then set the 1st condition to Formula Is =$F$10="" and the pattern to None. Make it the first condition and it will override any following conflicting statements.
I also had the same problem. So I tried by installing a lesser version say jdk1.5 and running the netbeans installation from command prompt as: Linux: netbeans-5_5-linux.bin -is:javahome /usr/jdk/jdk1.5.0_06 Windows: netbeans-5_5-windows.exe -is:javahome "C:\Program Files\Java\jdk1.5.0_06"
Hope it helps
Nice you gave me something to play around with
Run
class Sample extends Creator {
}
$a = new Sample ();
$a->role->rolename = 'test';
echo $a->role->rolename , PHP_EOL;
$a->role->rolename->am->love->php = 'w00';
echo $a->role->rolename , PHP_EOL;
echo $a->role->rolename->am->love->php , PHP_EOL;
Output
test
test
w00
Class Used
abstract class Creator {
public function __get($name) {
if (! isset ( $this->{$name} )) {
$this->{$name} = new Value ( $name, null );
}
return $this->{$name};
}
public function __set($name, $value) {
$this->{$name} = new Value ( $name, $value );
}
}
class Value extends Creator {
private $name;
private $value;
function __construct($name, $value) {
$this->name = $name;
$this->value = $value;
}
function __toString()
{
return (string) $this->value ;
}
}
class Sample extends Creator {
}
$a = new Sample ();
$a->role = array (
"A",
"B",
"C"
);
$a->role[0]->nice = "OK" ;
print ($a->role[0]->nice . PHP_EOL);
$a->role[1]->nice->ok = array("foo","bar","die");
print ($a->role[1]->nice->ok[2] . PHP_EOL);
$a->role[2]->nice->raw = new stdClass();
$a->role[2]->nice->raw->name = "baba" ;
print ($a->role[2]->nice->raw->name. PHP_EOL);
Output
Ok die baba
Modified Class
abstract class Creator {
public function __get($name) {
if (! isset ( $this->{$name} )) {
$this->{$name} = new Value ( $name, null );
}
return $this->{$name};
}
public function __set($name, $value) {
if (is_array ( $value )) {
array_walk ( $value, function (&$item, $key) {
$item = new Value ( $key, $item );
} );
}
$this->{$name} = $value;
}
}
class Value {
private $name ;
function __construct($name, $value) {
$this->{$name} = $value;
$this->name = $value ;
}
public function __get($name) {
if (! isset ( $this->{$name} )) {
$this->{$name} = new Value ( $name, null );
}
if ($name == $this->name) {
return $this->value;
}
return $this->{$name};
}
public function __set($name, $value) {
if (is_array ( $value )) {
array_walk ( $value, function (&$item, $key) {
$item = new Value ( $key, $item );
} );
}
$this->{$name} = $value;
}
public function __toString() {
return (string) $this->name ;
}
}
This looks like it might be the answer to your question. It says it's using Spring, but I think that should still help you in your case. Let me inline the code here so it's more convenient:
import java.io.FileReader;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
public class Foo
{
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper();
MyClass myObject = mapper.readValue(new FileReader("input.json"), MyClass.class);
// this is Jackson 1.x API only:
ObjectWriter writer = mapper.defaultPrettyPrintingWriter();
// ***IMPORTANT!!!*** for Jackson 2.x use the line below instead of the one above:
// ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
System.out.println(writer.writeValueAsString(myObject));
}
}
class MyClass
{
String one;
String[] two;
MyOtherClass three;
public String getOne() {return one;}
void setOne(String one) {this.one = one;}
public String[] getTwo() {return two;}
void setTwo(String[] two) {this.two = two;}
public MyOtherClass getThree() {return three;}
void setThree(MyOtherClass three) {this.three = three;}
}
class MyOtherClass
{
String four;
String[] five;
public String getFour() {return four;}
void setFour(String four) {this.four = four;}
public String[] getFive() {return five;}
void setFive(String[] five) {this.five = five;}
}
You need to install opencv-contrib
pip install opencv-contrib-python
It should work after that.
To access "Host Manager" you have to configure "admin-gui" user inside the tomcat-users.xml
Just add the below lines[change username & pwd] :
<role rolename="admin-gui"/>
<user username="admin" password="password" roles="admin-gui"/>
Restart tomcat 7 server and you are done.
The usual way is to use zip()
:
for x, y in zip(a, b):
# x is from a, y is from b
This will stop when the shorter of the two iterables a
and b
is exhausted. Also worth noting: itertools.izip()
(Python 2 only) and itertools.izip_longest()
(itertools.zip_longest()
in Python 3).
It is not something obvious, but the caret
package has a function postResample()
that will calculate "A vector of performance estimates" according to the documentation. The "performance estimates" are
and have to be accessed from the vector like this
library(caret)
vect1 <- c(1, 2, 3)
vect2 <- c(3, 2, 2)
res <- caret::postResample(vect1, vect2)
rsq <- res[2]
However, this is using the correlation squared approximation for r-squared as mentioned in another answer. I'm not sure why Max Kuhn didn't just use the conventional 1-SSE/SST.
caret
also has an R2()
method, although it's hard to find in the documentation.
The way to implement the normal coefficient of determination equation is:
preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2)
tss <- sum((actual - mean(actual)) ^ 2)
rsq <- 1 - rss/tss
Not too bad to code by hand of course, but why isn't there a function for it in a language primarily made for statistics? I'm thinking I must be missing the implementation of R^2 somewhere, or no one cares enough about it to implement it. Most of the implementations, like this one, seem to be for generalized linear models.
The compiler complains on
var completionHandler: (Float)->Void = {}
because the right-hand side is not a closure of the appropriate signature, i.e. a closure taking a float argument. The following would assign a "do nothing" closure to the completion handler:
var completionHandler: (Float)->Void = {
(arg: Float) -> Void in
}
and this can be shortened to
var completionHandler: (Float)->Void = { arg in }
due to the automatic type inference.
But what you probably want is that the completion handler is initialized to nil
in the same way that an Objective-C instance variable is inititialized to nil
. In Swift
this can be realized with an optional:
var completionHandler: ((Float)->Void)?
Now the property is automatically initialized to nil
("no value").
In Swift you would use optional binding to check of a the
completion handler has a value
if let handler = completionHandler {
handler(result)
}
or optional chaining:
completionHandler?(result)
I am thinking about a solution for this. First I would make the string input as a list. Then I would replace the items of list. Then through using join command, I will return list as a string. The code can be like this:
def the_replacer(text):
test = []
for m in range(len(text)):
test.append(text[m])
if test[m]==','\
or test[m]=='!'\
or test[m]=='.'\
or test[m]=='\''\
or test[m]==';':
#....
test[n]=''
return ''.join(test)
This would remove anything from the string. What do you think about that?
Just wanted to share my solution using sqlalchemy and pandas in python 3. Perhaps, one would find it useful.
import sqlalchemy as sa
import pandas as pd
engine = sa.create_engine("postgresql://postgres:my_password@my_host:my_port/my_db")
values = [val1,val2,val3]
query = sa.text("""
SELECT *
FROM my_table
WHERE col1 IN :values;
""")
query = query.bindparams(values=tuple(values))
df = pd.read_sql(query, engine)
You have a basic answer here: Get city name using geolocation
But for what you are looking for, i'd recommend this way.
Only if you also need administrative_area_level_1,to store different things for Paris, Texas, US and Paris, Ile-de-France, France and provide a manual fallback:
--
There is a problem in Michal's way, in that it takes the first result, not a particular one. He uses results[0]. The way I see fit (I just modified his code) is to take ONLY the result whose type is "locality", which is always present, even in an eventual manual fallback in case the browser does not support geolocation.
His way: fetched results are different from using http://maps.googleapis.com/maps/api/geocode/json?address=bucharest&sensor=false than from using http://maps.googleapis.com/maps/api/geocode/json?latlng=44.42514,26.10540&sensor=false (searching by name / searching by lat&lng)
This way: same fetched results.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Reverse Geocoding</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//console.log(results);
if (results[1]) {
var indice=0;
for (var j=0; j<results.length; j++)
{
if (results[j].types[0]=='locality')
{
indice=j;
break;
}
}
alert('The good number is: '+j);
console.log(results[j]);
for (var i=0; i<results[j].address_components.length; i++)
{
if (results[j].address_components[i].types[0] == "locality") {
//this is the object you are looking for City
city = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "administrative_area_level_1") {
//this is the object you are looking for State
region = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "country") {
//this is the object you are looking for
country = results[j].address_components[i];
}
}
//city data
alert(city.long_name + " || " + region.long_name + " || " + country.short_name)
} else {
alert("No results found");
}
//}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
</body>
</html>
When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.
json_decode( html_entity_decode( stripslashes ($jsonString ) ) );
Thanks to @Thisguyhastwothumbs
$value = ( array_key_exists($key, $array) && !empty($array[$key]) )
? $array[$key]
: 'non-existant or empty value key';
None of the other solutions really fit my needs, and although Stefan Steiger's solution worked as I expected I found it a bit too verbose.
Following is my attempt:
/**_x000D_
* Highlight keywords inside a DOM element_x000D_
* @param {string} elem Element to search for keywords in_x000D_
* @param {string[]} keywords Keywords to highlight_x000D_
* @param {boolean} caseSensitive Differenciate between capital and lowercase letters_x000D_
* @param {string} cls Class to apply to the highlighted keyword_x000D_
*/_x000D_
function highlight(elem, keywords, caseSensitive = false, cls = 'highlight') {_x000D_
const flags = caseSensitive ? 'gi' : 'g';_x000D_
// Sort longer matches first to avoid_x000D_
// highlighting keywords within keywords._x000D_
keywords.sort((a, b) => b.length - a.length);_x000D_
Array.from(elem.childNodes).forEach(child => {_x000D_
const keywordRegex = RegExp(keywords.join('|'), flags);_x000D_
if (child.nodeType !== 3) { // not a text node_x000D_
highlight(child, keywords, caseSensitive, cls);_x000D_
} else if (keywordRegex.test(child.textContent)) {_x000D_
const frag = document.createDocumentFragment();_x000D_
let lastIdx = 0;_x000D_
child.textContent.replace(keywordRegex, (match, idx) => {_x000D_
const part = document.createTextNode(child.textContent.slice(lastIdx, idx));_x000D_
const highlighted = document.createElement('span');_x000D_
highlighted.textContent = match;_x000D_
highlighted.classList.add(cls);_x000D_
frag.appendChild(part);_x000D_
frag.appendChild(highlighted);_x000D_
lastIdx = idx + match.length;_x000D_
});_x000D_
const end = document.createTextNode(child.textContent.slice(lastIdx));_x000D_
frag.appendChild(end);_x000D_
child.parentNode.replaceChild(frag, child);_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
// Highlight all keywords found in the page_x000D_
highlight(document.body, ['lorem', 'amet', 'autem']);
_x000D_
.highlight {_x000D_
background: lightpink;_x000D_
}
_x000D_
<p>Hello world lorem ipsum dolor sit amet, consectetur adipisicing elit. Est vel accusantium totam, ipsum delectus et dignissimos mollitia!</p>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam, corporis._x000D_
<small>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium autem voluptas perferendis dolores ducimus velit error voluptatem, qui rerum modi?</small>_x000D_
</p>
_x000D_
I would also recommend using something like escape-string-regexp if your keywords can have special characters that would need to be escaped in regexes:
const keywordRegex = RegExp(keywords.map(escapeRegexp).join('|')), flags);
If the point is simply to make the text inside the element invisible, set the color attribute to have 0 opacity using a rgba value such as color:rgba(0,0,0,0);
clean and simple.
adb install <path_to_apk>
http://developer.android.com/guide/developing/tools/adb.html#move
You can do it using group by:
c_maxes = df.groupby(['A', 'B']).C.transform(max)
df = df.loc[df.C == c_maxes]
c_maxes
is a Series
of the maximum values of C
in each group but which is of the same length and with the same index as df
. If you haven't used .transform
then printing c_maxes
might be a good idea to see how it works.
Another approach using drop_duplicates
would be
df.sort('C').drop_duplicates(subset=['A', 'B'], take_last=True)
Not sure which is more efficient but I guess the first approach as it doesn't involve sorting.
EDIT:
From pandas 0.18
up the second solution would be
df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')
or, alternatively,
df.sort_values('C', ascending=False).drop_duplicates(subset=['A', 'B'])
In any case, the groupby
solution seems to be significantly more performing:
%timeit -n 10 df.loc[df.groupby(['A', 'B']).C.max == df.C]
10 loops, best of 3: 25.7 ms per loop
%timeit -n 10 df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')
10 loops, best of 3: 101 ms per loop
You mean two classes? "Chain" the selectors (no spaces between them):
.class1.class2 {
/* style here */
}
This selects all elements with class1
that also have class2
.
In your case:
li.left.ui-class-selector {
}
Official documentation : CSS2 class selectors.
As akamike points out a problem with this method in Internet Explorer 6 you might want to read this: Use double classes in IE6 CSS?
to implement this in algorithmic way, by not using any python inbuilt function . This can be implemented as
def find_pos(string,word):
for i in range(len(string) - len(word)+1):
if string[i:i+len(word)] == word:
return i
return 'Not Found'
string = "the dude is a cool dude"
word = 'dude1'
print(find_pos(string,word))
# output 4
First method
For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.
Steps:
type PowerShell in search area and click on "Windows PowerShell"
If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)
run the .bat file with following command
PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt
This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.
Second method
You can use file redirection (>, >>) as suggest by Bali C above.
I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.
Here is one more robust version from Protocol Buffer
char* string_as_array(string* str)
{
return str->empty() ? NULL : &*str->begin();
}
// test codes
std::string mystr("you are here");
char* pstr = string_as_array(&mystr);
cout << pstr << endl; // you are here
same from above example - if you are just looking for json (not an array of object) just use
function getJsonDetails() {
item = {}
item ["token1"] = token1val;
item ["token2"] = token1val;
return item;
}
console.log(JSON.stringify(getJsonDetails()))
this output ll print as (a valid json)
{
"token1":"samplevalue1",
"token2":"samplevalue2"
}
You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:
body{
min-width:1000px; /* Suppose you want minimum width of 1000px */
width: auto !important; /* Firefox will set width as auto */
width:1000px; /* As IE6 ignores !important it will set width as 1000px; */
}
Or:
body{
min-width:1000px; // Suppose you want minimum width of 1000px
_width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}
NestedScrollView is just like ScrollView, but in NestedScrollView we can put other scrolling views as child of it, e.g. RecyclerView.
But if we put RecyclerView inside NestedScrollView, RecyclerView's smooth scrolling is disturbed. So to bring back smooth scrolling there's trick:
ViewCompat.setNestedScrollingEnabled(recyclerView, false);
put above line after setting adapter for recyclerView.
replace "150x150" with 720x720 and remove /vp/ from the link.it should work.
@variable
is very useful if calling stored procedures from an application written in Java , Python etc.
There are ocassions where variable values are created in the first call and needed in functions of subsequent calls.
The advantage can be seen in Oracle PL/SQL where these variables have 3 different scopes:
I have developed an architecture in which the complete code is written in PL/SQL. These are called from a middle-ware written in Java. There are two types of middle-ware. One to cater calls from a client which is also written in Java. The other other one to cater for calls from a browser. The client facility is implemented 100 percent in JavaScript. A command set is used instead of HTML and JavaScript for writing application in PL/SQL.
I have been looking for the same facility to port the codes written in PL/SQL to another database. The nearest one I have found is Postgres. But all the variables have function scope.
@
in MySQLI am happy to see that at least this @
facility is there in MySQL. I don't think Oracle will build same facility available in PL/SQL to MySQL stored procedures since it may affect the sales of Oracle database.
In Html you can add your input field with a date picker like this
<input class="form-control date-picker fromDates" id="myDate" type="text">
and then in java script, initialize your datepicker and set your value to the date like this,
$('.fromDates').datepicker({
maxDate: '0',
dateFormat: "dd/mm/yy",
changeYear: true,
changeMonth: true,
yearRange: "-100:+0"
});
var myDateVal = moment('${value}').format('DD/MM/YYYY');
$('#myDate').datepicker().datepicker('setDate', myDateVal );
(In here fromdate attribute shows the previous dates of the current date)
The above works,(having an original document with mixed pages of 11' and 16' wide). However auto rotate needs to be off otherwise landscape pages are saved with page white top and bottom, so dont work in full screen view.
Solution is to re open the new PDF in acrobat and crop the first image (carefully to avoid white border), then select page range i.e. all, this then applies to all pages. job done !
I have the same needs and created the following function that download recursively the files.
The directories are created locally only if they contain files.
import boto3
import os
def download_dir(client, resource, dist, local='/tmp', bucket='your_bucket'):
paginator = client.get_paginator('list_objects')
for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dist):
if result.get('CommonPrefixes') is not None:
for subdir in result.get('CommonPrefixes'):
download_dir(client, resource, subdir.get('Prefix'), local, bucket)
for file in result.get('Contents', []):
dest_pathname = os.path.join(local, file.get('Key'))
if not os.path.exists(os.path.dirname(dest_pathname)):
os.makedirs(os.path.dirname(dest_pathname))
resource.meta.client.download_file(bucket, file.get('Key'), dest_pathname)
The function is called that way:
def _start():
client = boto3.client('s3')
resource = boto3.resource('s3')
download_dir(client, resource, 'clientconf/', '/tmp', bucket='my-bucket')
Depending on how you're using the list, it may be worth it to use a TreeSet and then use the toArray() method at the end. I had a case where I needed a sorted list, and I found that the TreeSet + toArray() was much faster than adding to an array and merge sorting at the end.
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
The TraceContext
object in ASP.NET writes to the DefaultTraceListener
which outputs to the host process’ standard output. Rather than using Console.Write()
, if you use Trace.Write
, output will go to the standard output of the process.
You could use the System.Diagnostics.Process
object to get the ASP.NET process for your site and monitor standard output using the OutputDataRecieved
event.
The current spec says this regarding flex: 1 1 auto
:
Sizes the item based on the
width
/height
properties, but makes them fully flexible, so that they absorb any free space along the main axis. If all items are eitherflex: auto
,flex: initial
, orflex: none
, any positive free space after the items have been sized will be distributed evenly to the items withflex: auto
.
http://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#flex-common
It sounds to me like if you say an element is 100px tall, it is treated more like a "suggested" size, not an absolute. Because it is allowed to shrink and grow, it takes up as much space as its allowed to. That's why adding this line to your "main" element works: height: 0
(or any other smallish number).
As documented in ?legend
you do this like so:
plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)
Line breaks are achieved with the new line character \n
. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.
Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).
// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();
To get a user Input :
set /p pathName=Enter The Value:%=%
@echo %pathName%
p.s. this is also valid :
set /p pathName=Enter The Value:
If your class performs all of its initialization in the constructor, then @PostConstruct
is indeed redundant.
However, if your class has its dependencies injected using setter methods, then the class's constructor cannot fully initialize the object, and sometimes some initialization needs to be performed after all the setter methods have been called, hence the use case of @PostConstruct
.
As already mentioned if you can use await
. If you need to run the code synchronously like you mention .GetAwaiter().GetResult()
, .Result
or .Wait()
is a risk for deadlocks as many have said in comments/answers. Since most of us like oneliners you can use these for .Net 4.5<
Acquiring a value via an async method:
var result = Task.Run(() => asyncGetValue()).Result;
Syncronously calling an async method
Task.Run(() => asyncMethod()).Wait();
No deadlock issues will occur due to the use of Task.Run
.
Source:
https://stackoverflow.com/a/32429753/3850405
Update:
Could cause a deadlock if the calling thread is from the threadpool. The following happens: A new task is queued to the end of the queue, and the threadpool thread which would eventually execute the Task is blocked until the Task is executed.
Source:
https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d
As a sidenote to this:
netsh http add urlacl url=http://vaidesg:8080/ user=everyone
This will only work on English versions of Windows. If you are using a localized version you have to replace "everyone" with something else, for example:
Otherwise you will get an error (Create SDDL failed, Error: 1332)
If this is an ASP.NET app why not use Server.HtmlEncode() ?
Try to add like this:
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
instead of having
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
If you set the return value of setInterval
to a variable, you can use clearInterval
to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
This will work too:
DateTime today = new DateTime.now();
String dateSlug ="${today.year.toString()}-${today.month.toString().padLeft(2,'0')}-${today.day.toString().padLeft(2,'0')}";
print(dateSlug);
if you want to encode or decode an array from or to JSON you can use these functions
$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);
json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string
with json_decode you can take the results from the API and only output what you want, for example:
echo $myArray['payload']['ign'];
The problem here is that your timer starts a thread and when it runs the callback function, the callback function ( updatelistview) is accessing controls on UI thread so this can not be done becuase of this
You can change the height of one.
Don't use height="500"
(Just an example number). Use the style.
You can use <style>
tag or just use this:
<!DOCTYPE html>
<html>
<body>
<select id="option" style="height: 100px;">
<option value="1">Option 1
<option value="2">Option 2
</select>
</body>
</html>
I spotlight the change:
<select id="option" style="height: 100px;">
And even better...
style="height: 100px;">
You see that?
Please up vote if it's helpful!
you can do it like that:
<td>
<div style="width: 100%; position: relative; float: left;">inner div</div>
</td>
To get the last item of a collection use LastOrDefault() and Last() extension methods
var lastItem = integerList.LastOrDefault();
OR
var lastItem = integerList.Last();
Remeber to add using System.Linq;
, or this method won't be available.
Try this code:
lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");
I make some changes to the code of daniel.gindi
This is all you need to make it work.
+ (void)putView:(UIView*)view insideShadowWithColor:(UIColor*)color andBlur: (CGFloat)blur andOffset:(CGSize)shadowOffset andOpacity:(CGFloat)shadowOpacity
{
CGRect shadowFrame = view.frame;
UIView * shadow = [[UIView alloc] initWithFrame:shadowFrame];
shadow.backgroundColor = [UIColor redColor];
shadow.userInteractionEnabled = YES; // Modify this if needed
shadow.layer.shadowColor = color.CGColor;
shadow.layer.shadowOffset = shadowOffset;
shadow.layer.shadowRadius = blur;
shadow.layer.cornerRadius = view.layer.cornerRadius;
shadow.layer.masksToBounds = NO;
shadow.clipsToBounds = NO;
shadow.layer.shadowOpacity = shadowOpacity;
[view.superview insertSubview:shadow belowSubview:view];
}
Unfortunately, the DateTime class doesn't have the convenience methods available in the Time class to do this. You can convert any DateTime object into UTC like this:
d = DateTime.now
d.new_offset(Rational(0, 24))
You can switch back from UTC to localtime using:
d.new_offset(DateTime.now.offset)
where d
is a DateTime object in UTC time. If you'd like these as convenience methods, then you can create them like this:
class DateTime
def localtime
new_offset(DateTime.now.offset)
end
def utc
new_offset(Rational(0, 24))
end
end
You can see this in action in the following irb session:
d = DateTime.now.new_offset(Rational(-4, 24))
=> #<DateTime: 106105391484260677/43200000000,-1/6,2299161>
1.8.7 :185 > d.to_s
=> "2012-08-03T15:42:48-04:00"
1.8.7 :186 > d.localtime.to_s
=> "2012-08-03T12:42:48-07:00"
1.8.7 :187 > d.utc.to_s
=> "2012-08-03T19:42:48+00:00"
As you can see above, the initial DateTime object has a -04:00 offset (Eastern Time). I'm in Pacific Time with a -07:00 offset. Calling localtime
as described previously properly converts the DateTime object into local time. Calling utc
on the object properly converts it to a UTC offset.
I don't think you can drop all tables in one hit but you can do the following to get the commands:
select 'drop table ' || name || ';' from sqlite_master
where type = 'table';
The output of this is a script that will drop the tables for you. For indexes, just replace table with index.
You can use other clauses in the where
section to limit which tables or indexes are selected (such as "and name glob 'pax_*'
" for those starting with "pax_").
You could combine the creation of this script with the running of it in a simple bash (or cmd.exe) script so there's only one command to run.
If you don't care about any of the information in the DB, I think you can just delete the file it's stored in off the hard disk - that's probably faster. I've never tested this but I can't see why it wouldn't work.
I like @Eduardo's answer and I liked the accepted answer. I like to get back a boolean from something like this, so I wrote it up for you guys.
CREATE FUNCTION dbo.DatabaseExists(@dbname nvarchar(128))
RETURNS bit
AS
BEGIN
declare @result bit = 0
SELECT @result = CAST(
CASE WHEN db_id(@dbname) is not null THEN 1
ELSE 0
END
AS BIT)
return @result
END
GO
Now you can use it like this:
select [dbo].[DatabaseExists]('master') --returns 1
select [dbo].[DatabaseExists]('slave') --returns 0
The javadoc for SocketException states that it is
Thrown to indicate that there is an error in the underlying protocol such as a TCP error
In your case it seems that the connection has been closed by the server end of the connection. This could be an issue with the request you are sending or an issue at their end.
To aid debugging you could look at using a tool such as Wireshark to view the actual network packets. Also, is there an alternative client to your Java code that you could use to test the web service? If this was successful it could indicate a bug in the Java code.
As you are using Commons HTTP Client have a look at the Common HTTP Client Logging Guide. This will tell you how to log the request at the HTTP level.
The simplest way is css transform:
.navbar-brand {
transform: translateX(-50%);
left: 50%;
position: absolute;
}
DEMO: http://codepen.io/candid/pen/dGPZvR
This way also works with dynamically sized background images for the logo and allows us to utilize the text-hide class:
CSS:
.navbar-brand {
background: url(http://disputebills.com/site/uploads/2015/10/dispute.png) center / contain no-repeat;
transform: translateX(-50%);
left: 50%;
position: absolute;
width: 200px; /* no height needed ... image will resize automagically */
}
HTML:
<a class="navbar-brand text-hide" href="http://disputebills.com">Brand Text
</a>
We can also use flexbox though. However, using this method we'd have to move navbar-brand
outside of navbar-header
. This way is great though because we can now have image and text side by side:
.brand-centered {
display: flex;
justify-content: center;
position: absolute;
width: 100%;
left: 0;
top: 0;
}
.navbar-brand {
display: flex;
align-items: center;
}
Demo: http://codepen.io/candid/pen/yeLZax
To only achieve these results on mobile simply wrap the above css inside a media query:
@media (max-width: 768px) {
}
@JayGuilford's answer is a good one, but if you don't want a JS dependency, you could use a submit element and simply hide it using display: none;
.
you need to give the path. Atleast you should give the path from the current directory. It will work for sure. ./filename
the previous answers didn't work out for me well. I had persisting problems by setting the marker. So i changed the code slightly.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ANSI" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 1500px; height: 1000px;"></div>
<script type="text/javascript">
var locations = [
['Goettingen', 51.54128040000001, 9.915803500000038, 'http://www.google.de'],
['Kassel', 51.31271139999999, 9.479746100000057,0, 'http://www.stackoverflow.com'],
['Witzenhausen', 51.33996819999999, 9.855564299999969,0, 'www.http://developer.mozilla.org.de']
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(51.54376, 9.910419999999931),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
url: locations[i][4]
});
google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
window.location.href = this.url;
}
})(marker, i));
}
</script>
</body>
</html>
This way worked out for me! You can create Google Maps routing links from your Datebase to to use it as an interactive routing map.
May be you are using this checking :
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
}
To resolve this you need to import android.provider.DocumentsContract
class.
To resolve this issue you'll need to set the build SDK version to 19 (4.4) or higher to have API level 19 symbols available while compiling.
First, use the SDK Manager to download API 19 if you don't have it yet. Then, configure your project to use API 19:
I found this answer from here
Thanks .
Try this:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// You may decide to prompt to user else just kill.
Process.GetCurrentProcess().Goose();
}
Thanks for the links, Chris. I've often wondered about the specific effects of privileges like "BypassTraverseChecking" but never bothered to look them up.
I was having interesting problems getting a service to run and discovered that it didn't have access to it's files after the initial installation had been done by the administrator. I was thinking it needed something in addition to Logon As A Service until I found the file issue.
During Take Ownership, it was necessary to disable inheritance of permissions from the parent directories and apply permissions recursively down the tree.
Wasn't able to find a "give ownership" option to avoid making the service account an administrator temporarily, though.
Anyway, thought I'd post this in case anyone else was going down the same road I was looking for security policy issues when it was really just filesystem rights.
Ok, here is a fetch DELETE
example too:
fetch('https://example.com/delete-item/' + id, {
method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))