Since the OP was asking for using a custom compare function (and this is what led me to this question as well), I want to give a solid answer here:
Generally, you want to use the built-in sorted()
function which takes a custom comparator as its parameter. We need to pay attention to the fact that in Python 3 the parameter name and semantics have changed.
When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):
< 0
) when the left item should be sorted before the right item> 0
) when the left item should be sorted after the right item0
when both the left and the right item have the same weight and should be ordered "equally" without precedenceIn the particular case of the OP's question, the following custom compare function can be used:
def compare(item1, item2):
return fitness(item1) - fitness(item2)
Using the minus operation is a nifty trick because it yields to positive values when the weight of left item1
is bigger than the weight of the right item2
. Hence item1
will be sorted after item2
.
If you want to reverse the sort order, simply reverse the subtraction: return fitness(item2) - fitness(item1)
sorted(mylist, cmp=compare)
or:
sorted(mylist, cmp=lambda item1, item2: fitness(item1) - fitness(item2))
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(compare))
or:
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))
This works. A hackish way probably, but it works nicely. It was tested for responsive (Y).
.centered {
background-color: teal;
text-align: center;
}
I had exactly the same problem, where is wanted to copy a file into an external hard drive for backup purposes. If I wanted to copy a complete folder, then COPY was quite happy to create the destination folder and populate it with all the files. However, I wanted to copy a file once a day and add today's date to the file. COPY was happy to copy the file and rename it in the new format, but only as long as the destination folder already existed.
my copy command looked like this:
COPY C:\SRCFOLDER\MYFILE.doc D:\DESTFOLDER\MYFILE_YYYYMMDD.doc
Like you, I looked around for alternative switches or other copy type commands, but nothing really worked like I wanted it to. Then I thought about splitting out the two different requirements by simply adding a make directory ( MD or MKDIR ) command before the copy command.
So now i have
MKDIR D:\DESTFOLDER
COPY C:\SRCFOLDER\MYFILE.doc D:\DESTFOLDER\MYFILE_YYYYMMDD.doc
If the destination folder does NOT exist, then it creates it. If the destination folder DOES exist, then it generates an error message.. BUT, this does not stop the batch file from continuing on to the copy command.
The error message says: A subdirectory or file D:\DESTFOLDER already exists
As i said, the error message doesn't stop the batch file working and it is a really simple fix to the problem.
Hope that this helps.
Full Path for it is
System.Configuration.ConfigurationManager.AppSettings["KeyName"]
$("a[rel=popover]").each(function(){
var thisPopover=$(this);
var thisPopoverContent ='';
if('you want a data inside an html div tag') {
thisPopoverContent = $(thisPopover.attr('data-content-id')).html();
}elseif('you want ajax content') {
$.get(thisPopover.attr('href'),function(e){
thisPopoverContent = e;
});
}
$(this).attr( 'data-original-title',$(this).attr('title') );
thisPopover.popover({
content: thisPopoverContent
})
.click(function(e) {
e.preventDefault()
});
});
note that I used the same href tag and made it so that it doesn't change pages when clicked, this is a good thing for SEO and also if user doesn't have javascript!
A StreamReader is for text, not plain bytes. Don't use a StreamReader, and instead read directly from the underlying stream.
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\wsdl.exe
(via this question: Where can I find WSDL.exe?)
Use your subquery to return the correct grouping, because you're halfway there.
Try this:
select
a.*
from
messages a
inner join
(select name, max(id) as maxid from messages group by name) as b on
a.id = b.maxid
If it's not id
you want the max of:
select
a.*
from
messages a
inner join
(select name, max(other_col) as other_col
from messages group by name) as b on
a.name = b.name
and a.other_col = b.other_col
This way, you avoid correlated subqueries and/or ordering in your subqueries, which tend to be very slow/inefficient.
You have set #slider
as absolute
, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content
div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.
You can read about CSS positioning here
If you set both to relative
, the divs will be one after the other, as shown here:
#slider {
position:relative;
left:0;
height:400px;
border-style:solid;
border-width:5px;
}
#slider img {
width:100%;
}
#content {
position:relative;
}
#content #text {
position:relative;
width:950px;
height:215px;
color:red;
}
You need an scp client. Putty is not one. You can use WinSCP or PSCP. Both are free software.
@Chaibi Alaa, To make the user able to add only once, and move the marker; You can set the marker on first click and then just change the position on subsequent clicks.
var marker;
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
if (marker == null)
{
marker = new google.maps.Marker({
position: location,
map: map
});
}
else
{
marker.setPosition(location);
}
}
As these answers are old, I found this alternative. It is very clean and works with just java annotations:
To fix it, create a “none static setter” to assign the injected value for the static variable. For example :
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GlobalValue {
public static String DATABASE;
@Value("${mongodb.db}")
public void setDatabase(String db) {
DATABASE = db;
}
}
https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/
You can use this command to find the package names installed on a device:
adb shell pm list packages -3 -f
Reference: http://www.aftvnews.com/how-to-determine-the-package-name-of-an-android-app/
To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length
.
double sum = 0.0;
int length = 0;
for( double number : numbers ) {
sum += number;
length++;
}
return sum/length;
Variance is calculated similarly. Standard deviation is simply the square root of the variance:
double stddev = Math.sqrt( variance );
Regarding IP addresses, it appears that there is some debate on whether to include leading zeros. It was once the common practice and is generally accepted, so I would argue that they should be flagged as valid regardless of the current preference. There is also some ambiguity over whether text before and after the string should be validated and, again, I think it should. 1.2.3.4 is a valid IP but 1.2.3.4.5 is not and neither the 1.2.3.4 portion nor the 2.3.4.5 portion should result in a match. Some of the concerns can be handled with this expression:
grep -E '(^|[^[:alnum:]+)(([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.){3}([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])([^[:alnum:]]|$)'
The unfortunate part here is the fact that the regex portion that validates an octet is repeated as is true in many offered solutions. Although this is better than for instances of the pattern, the repetition can be eliminated entirely if subroutines are supported in the regex being used. The next example enables those functions with the -P
switch of grep
and also takes advantage of lookahead and lookbehind functionality. (The function name I selected is 'o' for octet. I could have used 'octet' as the name but wanted to be terse.)
grep -P '(?<![\d\w\.])(?<o>([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]))(\.\g<o>){3}(?![\d\w\.])'
The handling of the dot might actually create a false negatives if IP addresses are in a file with text in the form of sentences since the a period could follow without it being part of the dotted notation. A variant of the above would fix that:
grep -P '(?<![\d\w\.])(?<x>([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]))(\.\g<x>){3}(?!([\d\w]|\.\d))'
Assuming here you're referring to the javax.inject.Inject
annotation. @Inject
is part of the Java CDI (Contexts and Dependency Injection) standard introduced in Java EE 6 (JSR-299), read more. Spring has chosen to support using the @Inject
annotation synonymously with their own @Autowired
annotation.
So, to answer your question, @Autowired
is Spring's own annotation. @Inject
is part of a Java technology called CDI that defines a standard for dependency injection similar to Spring. In a Spring application, the two annotations works the same way as Spring has decided to support some JSR-299 annotations in addition to their own.
If one is using storyboard and overriding UICollectionViewDelegateFlowLayout then in swift 5 and Xcode 11 also set Estimate size to None
I just tried with with Eclipse Neon.1 and Gradle:
------------------------------------------------------------
Gradle 3.2.1
------------------------------------------------------------
Build time: 2016-11-22 15:19:54 UTC
Revision: 83b485b914fd4f335ad0e66af9d14aad458d2cc5
Groovy: 2.4.7
Ant: Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM: 1.8.0_112 (Oracle Corporation 25.112-b15)
OS: Windows 10 10.0 amd64
On windows 10 with Java Version:
C:\FDriveKambiz\repo\gradle-gen-project>java -version
java version "1.8.0_112"
Java(TM) SE Runtime Environment (build 1.8.0_112-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.112-b15, mixed mode)
And it failed miserably as you can see in Eclipse. But sailed like a soaring eagle in Intellij...I dont know Intellij, and a huge fan of eclipse, but common dudes, this means NO ONE teste Neon.1 for the simplest of use cases...to import a gradle project. That is not good enough. I am switching to Intellij for gradle projects:
In a servlet based artifact, such as @WebServlet
, @WebFilter
and @WebListener
, you can grab a "plain vanilla" JSF @ManagedBean @RequestScoped
by:
Bean bean = (Bean) request.getAttribute("beanName");
and @ManagedBean @SessionScoped
by:
Bean bean = (Bean) request.getSession().getAttribute("beanName");
and @ManagedBean @ApplicationScoped
by:
Bean bean = (Bean) getServletContext().getAttribute("beanName");
Note that this prerequires that the bean is already autocreated by JSF beforehand. Else these will return null
. You'd then need to manually create the bean and use setAttribute("beanName", bean)
.
If you're able to use CDI @Named
instead of the since JSF 2.3 deprecated @ManagedBean
, then it's even more easy, particularly because you don't anymore need to manually create the beans:
@Inject
private Bean bean;
Note that this won't work when you're using @Named @ViewScoped
because the bean can only be identified by JSF view state and that's only available when the FacesServlet
has been invoked. So in a filter which runs before that, accessing an @Inject
ed @ViewScoped
will always throw ContextNotActiveException
.
Only when you're inside @ManagedBean
, then you can use @ManagedProperty
:
@ManagedProperty("#{bean}")
private Bean bean;
Note that this doesn't work inside a @Named
or @WebServlet
or any other artifact. It really works inside @ManagedBean
only.
If you're not inside a @ManagedBean
, but the FacesContext
is readily available (i.e. FacesContext#getCurrentInstance()
doesn't return null
), you can also use Application#evaluateExpressionGet()
:
FacesContext context = FacesContext.getCurrentInstance();
Bean bean = context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
which can be convenienced as follows:
@SuppressWarnings("unchecked")
public static <T> T findBean(String beanName) {
FacesContext context = FacesContext.getCurrentInstance();
return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
}
and can be used as follows:
Bean bean = findBean("bean");
Raymond Chen has a few ideas:
https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573
Quoted here in full because MSDN archives tend to be somewhat unreliable:
The easy way is to use the
%CD%
pseudo-variable. It expands to the current working directory.
set OLDDIR=%CD%
.. do stuff ..
chdir /d %OLDDIR% &rem restore current directory
(Of course, directory save/restore could more easily have been done with
pushd
/popd
, but that's not the point here.)The
%CD%
trick is handy even from the command line. For example, I often find myself in a directory where there's a file that I want to operate on but... oh, I need to chdir to some other directory in order to perform that operation.
set _=%CD%\curfile.txt
cd ... some other directory ...
somecommand args %_% args
(I like to use
%_%
as my scratch environment variable.)Type
SET /?
to see the other pseudo-variables provided by the command processor.
Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):
http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741
This covers the use of %~dp0:
If you want to know where the batch file lives:
%~dp0
%0
is the name of the batch file.~dp
gives you the drive and path of the specified argument.
A list is a chain of spaces that can be indexed by (0, 1, 2 .... etc). So if players was a list, players[0] or players[1] would have worked. If players is a dictionary, players["name"] would have worked.
This should work with any div
or screen size:
.center-screen {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
text-align: center;_x000D_
min-height: 100vh;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<div class="center-screen">_x000D_
I'm in the center_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
See more details about flex
here. This should work on most of the browsers, see compatibility matrix here.
Update: If you don't want the scroll bar, make min-height
smaller, for example min-height: 95vh;
Just make option#1 Select Language:
Could you please try this ?
Create another item in post such as post.link then assign the link to it before send post to the render function.
post.link = '/posts/+ id.toString();
So, the above render function should be following instead.
return <li key={post.id}><a href={post.link}>{post.title}</a></li>
You can set this using the Sys.setenv()
function. My R session defaults to English, so I'll set it to French and then back again:
> Sys.setenv(LANG = "fr")
> 2 + x
Erreur : objet 'x' introuvable
> Sys.setenv(LANG = "en")
> 2 + x
Error: object 'x' not found
A list of the abbreviations can be found here.
Sys.getenv()
gives you a list of all the environment variables that are set.
From my experience, once you include the chartjs-plugin-datalabels plugin (make sure to place the <script>
tag after the chart.js tag on your page), your charts begin to display values.
If you then choose you can customize it to fit your needs. The customization is clearly documented here but basically, the format is like this hypothetical example:
var myBarChart = new Chart(ctx, {
type: 'bar',
data: yourDataObject,
options: {
// other options
plugins: {
datalabels: {
anchor :'end',
align :'top',
// and if you need to format how the value is displayed...
formatter: function(value, context) {
return GetValueFormatted(value);
}
}
}
}
});
import numpy as np
hist, bin_edges = np.histogram([1, 1, 2, 2, 2, 2, 3], bins = range(5))
Below, hist
indicates that there are 0 items in bin #0, 2 in bin #1, 4 in bin #3, 1 in bin #4.
print(hist)
# array([0, 2, 4, 1])
bin_edges
indicates that bin #0 is the interval [0,1), bin #1 is [1,2), ...,
bin #3 is [3,4).
print (bin_edges)
# array([0, 1, 2, 3, 4]))
Play with the above code, change the input to np.histogram
and see how it works.
But a picture is worth a thousand words:
import matplotlib.pyplot as plt
plt.bar(bin_edges[:-1], hist, width = 1)
plt.xlim(min(bin_edges), max(bin_edges))
plt.show()
If you want to be able to configure it through xml without any modification in java code you may find this idea helpful. Simply you call init from constructor and set the text as html
public class HTMLTextView extends TextView {
... constructors calling init...
private void init(){
setText(Html.fromHtml(getText().toString()));
}
}
xml:
<com.package.HTMLTextView
android:text="@string/about_item_1"/>
Basically "delete" sends a query directly to the database to delete the record. In that case Rails doesn't know what attributes are in the record it is deleting nor if there are any callbacks (such as before_destroy
).
The "destroy" method takes the passed id, fetches the model from the database using the "find" method, then calls destroy on that. This means the callbacks are triggered.
You would want to use "delete" if you don't want the callbacks to be triggered or you want better performance. Otherwise (and most of the time) you will want to use "destroy".
You are supposed to add the javascript code in a $(document).ready(function() {});
block.
i.e.
$(document).ready(function() {
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
});
As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"
If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?
And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful http://git-scm.com/book/en/Git-Tools-Rewriting-History
Since WordPress already uses jQuery you can try something like this:
var POST=<?php echo json_encode($_POST); ?>;
for(k in POST){
$("#"+k).val(POST[k]);
}
Selection
is its own object within VBA. It functions much like a Range
object.
Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.
Dim myRange as Range
Set myRange = Selection
For further reading, check out the MSDN article.
Think of the ?
as to mean "unknown"
. Thus, "ArrayList<? extends Object>"
is to say "an unknown type that (or as long as it)extends Object". Therefore, needful to say, arrayList.add(3)
would be putting something you know, into an unknown. I.e 'Forgetting'.
A small correction to Thepeer's answer: To override save()
function in model classes, better add arguments to it:
from django.utils.text import slugify
def save(self, *args, **kwargs):
if not self.id:
self.s = slugify(self.q)
super(test, self).save(*args, **kwargs)
Otherwise, test.objects.create(q="blah blah blah")
will result in a force_insert
error (unexpected argument).
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
Check this out .... it works
http://www.aspnettutorials.com/tutorials/email/email-aspnet2-csharp/
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
MailMessage message = new MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);
emailClient.Send(message);
litStatus.Text = "Message Sent";
}
catch (Exception ex)
{
litStatus.Text=ex.ToString();
}
}
}
You can read a CSV file with headers into a NumPy structured array with np.genfromtxt. For example:
import numpy as np
csv_fname = 'file.csv'
with open(csv_fname, 'w') as fp:
fp.write("""\
"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
""")
# Read the CSV file into a Numpy record array
r = np.genfromtxt(csv_fname, delimiter=',', names=True, case_sensitive=True)
print(repr(r))
which looks like this:
array([(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111196e+12),
(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111311e+12),
(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29112065e+12)],
dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8'), ('E', '<f8'), ('F', '<f8'), ('timestamp', '<f8')])
You can access a named column like this r['E']
:
array([1715.37476, 1715.37476, 1715.37476])
Note: this answer previously used np.recfromcsv to read the data into a NumPy record array. While there was nothing wrong with that method, structured arrays are generally better than record arrays for speed and compatibility.
Maybe this can help
string input = "hello123world";
bool isDigitPresent = input.Any(c => char.IsDigit(c));
answer from msdn.
Please try Npcap: https://github.com/nmap/npcap, it is based on WinPcap and supports loopback traffic capturing on Windows. Npcap is a subproject of Nmap (http://nmap.org/), so please report any issues on Nmap's development list (http://seclists.org/nmap-dev/).
You can also use the filter function from the dplyr package which returns rows with matching conditions.
> library(dplyr)
> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2
This Blog article explains the internals of ODEX files:
WHAT IS AN ODEX FILE?
In Android file system, applications come in packages with the extension .apk. These application packages, or APKs contain certain .odex files whose supposed function is to save space. These ‘odex’ files are actually collections of parts of an application that are optimized before booting. Doing so speeds up the boot process, as it preloads part of an application. On the other hand, it also makes hacking those applications difficult because a part of the coding has already been extracted to another location before execution.
i think this is a best mode to cast to int
public int ByteToint(Byte B){
String comb;
int out=0;
comb=B+"";
salida= Integer.parseInt(comb);
out=out+128;
return out;
}
first comvert byte to String
comb=B+"";
next step is comvert to a int
out= Integer.parseInt(comb);
but byte is in rage of -128 to 127 for this reasone, i think is better use rage 0 to 255 and you only need to do this:
out=out+256;
▲
is the Unicode black up-pointing triangle (?) while ▼
is the black down-pointing triangle (?).
You can just plug the characters (copied from the web) into this site for a lookup.
You can easily Use this command:
// Question : name of Model
// take 10 rows from DB In shuffle records...
$questions = Question::orderByRaw('RAND()')->take(10)->get();
Also if you use NHibernate you can turn on and setup second level cache for queries and add to queries scope and timeout. And there is kick ass profiler for EF, L2S and NHibernate - http://hibernatingrhinos.com/products/UberProf. It will help to tune your queries.
Instant.now() // Capture the current moment in UTC.
.atZone( ZoneId.systemDefault() ) // Adjust into the JVM's current default time zone. Same moment, different wall-clock time. Produces a `ZonedDateTime` object.
.toInstant() // Extract a `Instant` (always in UTC) object from the `ZonedDateTime` object.
.atZone( ZoneId.of( "Europe/Paris" ) ) // Adjust the `Instant` into a specific time zone. Renders a `ZonedDateTime` object. Same moment, different wall-clock time.
.toInstant() // And back to UTC again.
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes (Date
, Calendar
, etc.).
Your use of the word "local" contradicts the usage in the java.time class. In java.time, "local" means any locality or all localities, but not any one particular locality. The java.time classes with names starting with "Local…" all lack any concept of time zone or offset-from-UTC. So they do not represent a specific moment, they are not a point on the timeline, whereas your Question is all about moments, points on the timeline viewed through various wall-clock times.
Get the current system time (local time)
If you want to capture the current moment in UTC, use Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Adjust into a time zone by applying a ZoneId
to get a ZonedDateTime
. Same moment, same point on the timeline, different wall-clock time.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
As a shortcut, you can skip the usage of Instant
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Convert Local time to UTC // Works Fine Till here
You can adjust from the zoned date-time to UTC by extracting an Instant
from a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Instant instant = zdt.toInstant() ;
Reverse the UTC time, back to local time.
As shown above, apply a ZoneId
to adjust the same moment into another wall-clock time used by the people of a certain region (a time zone).
Instant instant = Instant.now() ; // Capture current moment in UTC.
ZoneId zDefault = ZoneId.systemDefault() ; // The JVM's current default time zone.
ZonedDateTime zdtDefault = instant.atZone( zDefault ) ;
ZoneId zTunis = ZoneId.of( "Africa/Tunis" ) ; // The JVM's current default time zone.
ZonedDateTime zdtTunis = instant.atZone( zTunis ) ;
ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" ) ; // The JVM's current default time zone.
ZonedDateTime zdtAuckland = instant.atZone( zAuckland ) ;
Going back to UTC from a zoned date-time, call ZonedDateTime::toInstant
. Think of it conceptually as: ZonedDateTime = Instant + ZoneId.
Instant instant = zdtAuckland.toInstant() ;
All of these objects, the Instant
and the three ZonedDateTime
objects all represent the very same simultaneous moment, the same point in history.
Followed 3 different approaches (listed below) but all the 3 approaches retains the time in UTC only.
Forget about trying to fix code using those awful Date
, Calendar
, and GregorianCalendar
classes. They are a wretched mess of bad design and flaws. You need never touch them again. If you must interface with old code not yet updated to java.time, you can convert back-and-forth via new conversion methods added to the old classes.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Efficient way to iterate your ArrayList
followed by this link. This type will improve the performance of looping during iteration
int size = list.size();
for(int j = 0; j < size; j++) {
System.out.println(list.get(i));
}
I post the solution that worked for me !
var form = $('#checkboxList input[type="checkbox"]').map(function() {
return { name: this.name, value: this.checked ? this.value : "false" };
}).get();
var data = JSON.stringify(form);
data value is : "[{"name":"cb1","value":"false"},{"name":"cb2","value":"true"},{"name":"cb3","value":"false"},{"name":"cb4","value":"true"}]"
Here's how do to it with the SSDB catalog that was introduced with SQL Server 2012...
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.IntegrationServices;
public List<string> ExecutePackage(string folder, string project, string package)
{
// Connection to the database server where the packages are located
SqlConnection ssisConnection = new SqlConnection(@"Data Source=.\SQL2012;Initial Catalog=master;Integrated Security=SSPI;");
// SSIS server object with connection
IntegrationServices ssisServer = new IntegrationServices(ssisConnection);
// The reference to the package which you want to execute
PackageInfo ssisPackage = ssisServer.Catalogs["SSISDB"].Folders[folder].Projects[project].Packages[package];
// Add a parameter collection for 'system' parameters (ObjectType = 50), package parameters (ObjectType = 30) and project parameters (ObjectType = 20)
Collection<PackageInfo.ExecutionValueParameterSet> executionParameter = new Collection<PackageInfo.ExecutionValueParameterSet>();
// Add execution parameter (value) to override the default asynchronized execution. If you leave this out the package is executed asynchronized
executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "SYNCHRONIZED", ParameterValue = 1 });
// Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)
executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "LOGGING_LEVEL", ParameterValue = 3 });
// Add a project parameter (value) to fill a project parameter
executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 20, ParameterName = "MyProjectParameter", ParameterValue = "some value" });
// Add a project package (value) to fill a package parameter
executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 30, ParameterName = "MyPackageParameter", ParameterValue = "some value" });
// Get the identifier of the execution to get the log
long executionIdentifier = ssisPackage.Execute(false, null, executionParameter);
// Loop through the log and do something with it like adding to a list
var messages = new List<string>();
foreach (OperationMessage message in ssisServer.Catalogs["SSISDB"].Executions[executionIdentifier].Messages)
{
messages.Add(message.MessageType + ": " + message.Message);
}
return messages;
}
The code is a slight adaptation of http://social.technet.microsoft.com/wiki/contents/articles/21978.execute-ssis-2012-package-with-parameters-via-net.aspx?CommentPosted=true#commentmessage
There is also a similar article at http://domwritescode.com/2014/05/15/project-deployment-model-changes/
This is difficult to achieve, but the cookie expiration date can be set in another cookie. This cookie can then be read later to get the expiration date. Maybe there is a better way, but this is one of the methods to solve your problem.
pip install opencv-python
or
pip install opencv-python3
will definately works fine
A simple way to see the Git commit short version and the Git commit message is:
git log --oneline
Note that this is shorthand for
git log --pretty=oneline --abbrev-commit
In TortiseSVN settings
right-click menu >> settings >> Saved data >> Authentication data [Clear]
The side effect is that it clears out all authentication data and you have to re-enter your own username/password.
I test on a lot of Markdown implementations. The non-breaking space ASCII character
(followed by a blank line) would give a blank line. Repeating this pair would do the job. So far I haven't failed any.
For example:
Hello
world!
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
Some of the following was gleaned off of this site. This is what I did to duplicate a record in a table with any number of fields:
This also assumes you have an AI field at the beginning of the table
function duplicateRow( $id = 1 ){
dbLink();//my db connection
$qColumnNames = mysql_query("SHOW COLUMNS FROM table") or die("mysql error");
$numColumns = mysql_num_rows($qColumnNames);
for ($x = 0;$x < $numColumns;$x++){
$colname[] = mysql_fetch_row($qColumnNames);
}
$sql = "SELECT * FROM table WHERE tableId = '$id'";
$row = mysql_fetch_row(mysql_query($sql));
$sql = "INSERT INTO table SET ";
for($i=1;$i<count($colname)-4;$i++){//i set to 1 to preclude the id field
//we set count($colname)-4 to avoid the last 4 fields (good for our implementation)
$sql .= "`".$colname[$i][0]."` = '".$row[$i]. "', ";
}
$sql .= " CreateTime = NOW()";// we need the new record to have a new timestamp
mysql_query($sql);
$sql = "SELECT MAX(tableId) FROM table";
$res = mysql_query($sql);
$row = mysql_fetch_row($res);
return $row[0];//gives the new ID from auto incrementing
}
Simpy It was working for me after restarting the Android studio.
Because theoretically Animal animal
can be a dog:
Animal animal = new Dog();
Generally, downcasting is not a good idea. You should avoid it. If you use it, you better include a check:
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
}
The csv.writer
writerow
method takes an iterable as an argument. Your result set has to be a list (rows) of lists (columns).
csvwriter.writerow(row)
Write the row parameter to the writer’s file object, formatted according to the current dialect.
Do either:
import csv
RESULTS = [
['apple','cherry','orange','pineapple','strawberry']
]
with open('output.csv','wb') as result_file:
wr = csv.writer(result_file, dialect='excel')
wr.writerows(RESULTS)
or:
import csv
RESULT = ['apple','cherry','orange','pineapple','strawberry']
with open('output.csv','wb') as result_file:
wr = csv.writer(result_file, dialect='excel')
wr.writerow(RESULT)
Tried many things but found solution by added below line in my.ini and restarting mysql service.
innodb_strict_mode = 0
The previous answers still leave room for improvement because of the possibilities, the intuitiveness of the code, and the use of id
versus name
. One can get a read-out of three data of a selected option -- its index number, its value and its text. This simple, cross-browser code does all three:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo GetSelectOptionData</title>
</head>
<body>
<form name="demoForm">
<select name="demoSelect" onchange="showData()">
<option value="zilch">Select:</option>
<option value="A">Option 1</option>
<option value="B">Option 2</option>
<option value="C">Option 3</option>
</select>
</form>
<p id="firstP"> </p>
<p id="secondP"> </p>
<p id="thirdP"> </p>
<script>
function showData() {
var theSelect = demoForm.demoSelect;
var firstP = document.getElementById('firstP');
var secondP = document.getElementById('secondP');
var thirdP = document.getElementById('thirdP');
firstP.innerHTML = ('This option\'s index number is: ' + theSelect.selectedIndex + ' (Javascript index numbers start at 0)');
secondP.innerHTML = ('Its value is: ' + theSelect[theSelect.selectedIndex].value);
thirdP.innerHTML = ('Its text is: ' + theSelect[theSelect.selectedIndex].text);
}
</script>
</body>
</html>
Live demo: http://jsbin.com/jiwena/1/edit?html,output .
id
should be used for make-up purposes. For functional form purposes, name
is still valid, also in HTML5, and should still be used. Lastly, mind the use of square versus round brackets in certain places. As was explained before, only (older versions of) Internet Explorer will accept round ones in all places.
Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:
public ActionResult GetImages(string artistName, string apiKey)
MVC will auto-populate the parameters when given a URL like:
/Artist/GetImages/?artistName=cher&apiKey=XXX
One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:
public ActionResult GetImages(string id, string apiKey)
would be populated correctly with a URL like the following:
/Artist/GetImages/cher?apiKey=XXX
In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
If you wanted to support a url like
/Artist/GetImages/cher/api-key
you could add a route like:
routes.MapRoute(
"ArtistImages", // Route name
"{controller}/{action}/{artistName}/{apikey}", // URL with parameters
new { controller = "Home", action = "Index", artistName = "", apikey = "" } // Parameter defaults
);
and a method like the first example above.
Let me help you understand it with an example of "codaddict's algorithm"
'Dictionary in C#' is 'Hashmap in Java' in parallel universe.
Some implementations are different. See the example below to understand better.
Declaring Java HashMap:
Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
Declaring C# Dictionary:
Dictionary<int, int> Pairs = new Dictionary<int, int>();
Getting a value from a location:
pairs.get(input[i]); // in Java
Pairs[input[i]]; // in C#
Setting a value at location:
pairs.put(k - input[i], input[i]); // in Java
Pairs[k - input[i]] = input[i]; // in C#
An Overall Example can be observed from below Codaddict's algorithm.
codaddict's algorithm in Java:
import java.util.HashMap;
public class ArrayPairSum {
public static void printSumPairs(int[] input, int k)
{
Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
for (int i = 0; i < input.length; i++)
{
if (pairs.containsKey(input[i]))
System.out.println(input[i] + ", " + pairs.get(input[i]));
else
pairs.put(k - input[i], input[i]);
}
}
public static void main(String[] args)
{
int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
printSumPairs(a, 10);
}
}
Codaddict's algorithm in C#
using System;
using System.Collections.Generic;
class Program
{
static void checkPairs(int[] input, int k)
{
Dictionary<int, int> Pairs = new Dictionary<int, int>();
for (int i = 0; i < input.Length; i++)
{
if (Pairs.ContainsKey(input[i]))
{
Console.WriteLine(input[i] + ", " + Pairs[input[i]]);
}
else
{
Pairs[k - input[i]] = input[i];
}
}
}
static void Main(string[] args)
{
int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
//method : codaddict's algorithm : O(n)
checkPairs(a, 10);
Console.Read();
}
}
If you want to translate your resources, just download MAT (Multilingual App Toolkit) for Visual Studio. https://marketplace.visualstudio.com/items?itemName=MultilingualAppToolkit.MultilingualAppToolkit-18308 This is the way to go to translate your projects in Visual Studio. https://blogs.msdn.microsoft.com/matdev/
This solution worked for me
;(function($){ // your code })(jQuery);
Move your code inside the closure and use $ instead of jQuery
I found the above solution in https://magento.stackexchange.com/questions/33348/uncaught-typeerror-undefined-is-not-a-function-when-using-a-jquery-plugin-in-ma
after seraching too much
Basically:
$lastDate = date("Y-m-t", strtotime($query_d));
Date t parameter return days number in current month.
Please find below the working solution for Windows: It worked for me. 1 Open Control Panel from the Start menu. 2 Select User Accounts. 3 Select the "Credential Manager". 4 Click on "Manage Windows Credentials". 5 Delete any credentials related to Git or GitHub. 6 Once you deleted all then try to clone again.
Try this: parseInt(jQuery.offset().top, 10)
In lollipop and up:
Add to mainfest:
<uses-permission android:name="android.permission.GET_TASKS" />
And do something like this:
if( mTaskId < 0 )
{
List<AppTask> tasks = mActivityManager.getAppTasks();
if( tasks.size() > 0 )
mTaskId = tasks.get( 0 ).getTaskInfo().id;
}
Here is how to get the Guid's programmatically! You can then use these guids/filepaths with an above answer to add the reference!
Reference: http://www.vbaexpress.com/kb/getarticle.php?kb_id=278
Sub ListReferencePaths()
'Lists path and GUID (Globally Unique Identifier) for each referenced library.
'Select a reference in Tools > References, then run this code to get GUID etc.
Dim rw As Long, ref
With ThisWorkbook.Sheets(1)
.Cells.Clear
rw = 1
.Range("A" & rw & ":D" & rw) = Array("Reference","Version","GUID","Path")
For Each ref In ThisWorkbook.VBProject.References
rw = rw + 1
.Range("A" & rw & ":D" & rw) = Array(ref.Description, _
"v." & ref.Major & "." & ref.Minor, ref.GUID, ref.FullPath)
Next ref
.Range("A:D").Columns.AutoFit
End With
End Sub
Here is the same code but printing to the terminal if you don't want to dedicate a worksheet to the output.
Sub ListReferencePaths()
'Macro purpose: To determine full path and Globally Unique Identifier (GUID)
'to each referenced library. Select the reference in the Tools\References
'window, then run this code to get the information on the reference's library
On Error Resume Next
Dim i As Long
Debug.Print "Reference name" & " | " & "Full path to reference" & " | " & "Reference GUID"
For i = 1 To ThisWorkbook.VBProject.References.Count
With ThisWorkbook.VBProject.References(i)
Debug.Print .Name & " | " & .FullPath & " | " & .GUID
End With
Next i
On Error GoTo 0
End Sub
If you want to read that file from inside your application use:
InputStream input = getClass().getResourceAsStream("/classpath/to/my/file");
The path starts with "/", but that is not the path in your file-system, but in your classpath. So if your file is at the classpath "org.xml" and is called myxml.xml your path looks like "/org/xml/myxml.xml".
The InputStream reads the content of your file. You can wrap it into an Reader, if you want.
I hope that helps.
Child can ask kernel to deliver SIGHUP
(or other signal) when parent dies by specifying option PR_SET_PDEATHSIG
in prctl()
syscall like this:
prctl(PR_SET_PDEATHSIG, SIGHUP);
See man 2 prctl
for details.
Edit: This is Linux-only
Check it out this code, it works for me
// Slide up animation
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:toXDelta="0" />
</set>
// Slide dowm animation
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="0%p"
android:interpolator="@android:anim/accelerate_interpolator"
android:toYDelta="100%p" />
</set>
// Style
<style name="DialogAnimation">
<item name="android:windowEnterAnimation">@anim/slide_up</item>
<item name="android:windowExitAnimation">@anim/slide_down</item>
</style>
// Inside Dialog Fragment
@Override
public void onActivityCreated(Bundle arg0) {
super.onActivityCreated(arg0);
getDialog().getWindow()
.getAttributes().windowAnimations = R.style.DialogAnimation;
}
for WORDPRESS:
global $wpdb;
$your_table = $wpdb->prefix. 'My_Table_Name';
$your_column = 'My_Column_Name';
if (!in_array($your_column, $wpdb->get_col( "DESC " . $your_table, 0 ) )){ $result= $wpdb->query(
"ALTER TABLE $your_table ADD $your_column VARCHAR(100) CHARACTER SET utf8 NOT NULL " //you can add positioning phraze: "AFTER My_another_column"
);}
v. community 5.0.4 (linux): File -> Settings -> Editor -> General -> Appearance -> now check 'Show line numbers', confirm w. OK an voila :)
Three steps to implement your function:
Step#1 You can specify a string, including the chars A-Z and 0-9.
Like.
String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
Step#2 Then if you would like to generate a random char from this candidate string. You can use
candidateChars.charAt(random.nextInt(candidateChars.length()));
Step#3 At last, specify the length of random string to be generated (in your description, it is 17). Writer a for-loop and append the random chars generated in step#2 to StringBuilder object.
Based on this, here is an example public class RandomTest {
public static void main(String[] args) {
System.out.println(generateRandomChars(
"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 17));
}
/**
*
* @param candidateChars
* the candidate chars
* @param length
* the number of random chars to be generated
*
* @return
*/
public static String generateRandomChars(String candidateChars, int length) {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(candidateChars.charAt(random.nextInt(candidateChars
.length())));
}
return sb.toString();
}
}
I did this:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AutoDealer</title>
<style>
.container{
width: 860px;
height: 1074px;
margin-right: auto;
margin-left: auto;
border: 1px solid red;
}
.nav{
}
.wrapper{
display: block;
overflow: hidden;
border: 1px solid green;
}
.otherWrapper{
display: block;
overflow: hidden;
border: 1px solid green;
float:left;
}
.left{
width: 399px;
float: left;
background-color: pink;
}
.bottom{
clear: both;
width: 399px;
background-color: yellow;
}
.right{
height:350px;
width: 449px;
overflow: hidden;
background-color: blue;
overflow: hidden;
float:right;
}
</style>
</head>
<body>
<div class="container">
<div class="nav"></div>
<div class="wrapper">
<div class="otherWrapper">
<div class="left">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies aliquet tellus sit amet ultrices. Sed faucibus, nunc vitae accumsan laoreet, enim metus varius nulla, ac ultricies felis ante venenatis justo. In hac habitasse platea dictumst. In cursus enim nec urna molestie, id mattis elit mollis. In sed eros eget nibh congue vehicula. Nunc vestibulum enim risus, sit amet suscipit dui auctor et. Morbi orci magna, accumsan at turpis a, scelerisque congue eros. Morbi non mi vel nibh varius blandit sed et urna.</p>
</div>
<div class="bottom">
<p>ucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesq</p></div>
</div>
<div class="right">
<p>Quisque vulputate mi id turpis luctus, quis laoreet nisi vestibulum. Morbi facilisis erat vitae augue ornare convallis. Fusce sit amet magna rutrum, hendrerit purus vitae, congue justo. Nam non mi eget purus ultricies lacinia. Fusce ante nisl, efficitur venenatis urna ut, pellentesque egestas nisl. In ut faucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesque maximus. Quisque a tempus lectus.</p>
</div>
</div>
</div>
</body>
So basically I just made another div to wrap the pink and yellow, and I make that div have a float:left on it. The blue div has a float:right on it.
I you only want to apply the change only for one field, you could try serializing the field
class MyModel < ActiveRecord::Base
serialize :content
attr_accessible :content, :title
end
if you insist on using Bootstrap, use d-inline-block
like below
<div class="row d-inline-block">
<form class="form-inline">
<div class="form-group d-inline-block">
<input type="email" aria-expanded="false" class="form-control mr-2"
placeholder="Enter your email">
<button type="button" class="btn btn-danger">submit</button>
</div>
</form>
</div>
At times you do not want to simply remove the characters, but just remove the accents. I came up with the following utility class which I use in my Java REST web projects whenever I need to include a String in an URL:
import java.text.Normalizer;
import java.text.Normalizer.Form;
import org.apache.commons.lang.StringUtils;
/**
* Utility class for String manipulation.
*
* @author Stefan Haberl
*/
public abstract class TextUtils {
private static String[] searchList = { "Ä", "ä", "Ö", "ö", "Ü", "ü", "ß" };
private static String[] replaceList = { "Ae", "ae", "Oe", "oe", "Ue", "ue",
"sz" };
/**
* Normalizes a String by removing all accents to original 127 US-ASCII
* characters. This method handles German umlauts and "sharp-s" correctly
*
* @param s
* The String to normalize
* @return The normalized String
*/
public static String normalize(String s) {
if (s == null)
return null;
String n = null;
n = StringUtils.replaceEachRepeatedly(s, searchList, replaceList);
n = Normalizer.normalize(n, Form.NFD).replaceAll("[^\\p{ASCII}]", "");
return n;
}
/**
* Returns a clean representation of a String which might be used safely
* within an URL. Slugs are a more human friendly form of URL encoding a
* String.
* <p>
* The method first normalizes a String, then converts it to lowercase and
* removes ASCII characters, which might be problematic in URLs:
* <ul>
* <li>all whitespaces
* <li>dots ('.')
* <li>(semi-)colons (';' and ':')
* <li>equals ('=')
* <li>ampersands ('&')
* <li>slashes ('/')
* <li>angle brackets ('<' and '>')
* </ul>
*
* @param s
* The String to slugify
* @return The slugified String
* @see #normalize(String)
*/
public static String slugify(String s) {
if (s == null)
return null;
String n = normalize(s);
n = StringUtils.lowerCase(n);
n = n.replaceAll("[\\s.:;&=<>/]", "");
return n;
}
}
Being a German speaker I've included proper handling of German umlauts as well - the list should be easy to extend for other languages.
HTH
EDIT: Note that it may be unsafe to include the returned String in an URL. You should at least HTML encode it to prevent XSS attacks.
This kind of depends on what you want to do with the results. If you're just after the numbers, a set-based option would be a numbers table - which comes in handy for all sorts of things.
For MSSQL 2005+, you can use a recursive CTE to generate a numbers table inline:
;WITH Numbers (N) AS (
SELECT 1 UNION ALL
SELECT 1 + N FROM Numbers WHERE N < 500
)
SELECT N FROM Numbers
OPTION (MAXRECURSION 500)
No you can't use case
and in
like this. But you can do
SELECT * FROM Product P
WHERE @Status='published' and P.Status IN (1,3)
or @Status='standby' and P.Status IN (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)
BTW you can reduce that to
SELECT * FROM Product P
WHERE @Status='standby' and P.Status IN (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)
since or P.Status IN (1,3)
gives you also all records of @Status='published' and P.Status IN (1,3)
As Peter and Amro illustrate, you have to convert numeric values to formatted strings first in order to display them or concatenate them with other character strings. You can do this using the functions FPRINTF, SPRINTF, NUM2STR, and INT2STR.
With respect to getting ans = 3
as an output, it is probably because you are not assigning the output from answer
to a variable. If you want to get all of the output values, you will have to call answer
in the following way:
[out1,out2,out3] = answer(1,2);
This will place the value d
in out1
, the value e
in out2
, and the value f
in out3
. When you do the following:
answer(1,2)
MATLAB will automatically assign the first output d
(which has the value 3 in this case) to the default workspace variable ans
.
With respect to suggesting a good resource for learning MATLAB, you shouldn't underestimate the value of the MATLAB documentation. I've learned most of what I know on my own using it. You can access it online, or within your copy of MATLAB using the functions DOC, HELP, or HELPWIN.
Generated Column is one of the good approach for MySql version which is 5.7.6 and above.
There are two kinds of Generated Columns:
Both types can have NOT NULL restrictions, but only a stored Generated Column can be a part of an index.
For current case, we are going to use stored generated column. To implement I have considered that both of the values required for calculation are present in table
CREATE TABLE order_details (price DOUBLE, quantity INT, amount DOUBLE AS (price * quantity));
INSERT INTO order_details (price, quantity) VALUES(100,1),(300,4),(60,8);
amount will automatically pop up in table and you can access it directly, also please note that whenever you will update any of the columns, amount will also get updated.
It's a limitation of the language. In section 6.7.8/4:
All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
In section 6.6, the spec defines what must considered a constant expression. No where does it state that a const variable must be considered a constant expression. It is legal for a compiler to extend this (6.6/10 - An implementation may accept other forms of constant expressions
) but that would limit portability.
If you can change my_foo
so it does not have static storage, you would be okay:
int main()
{
foo_t my_foo = foo_init;
return 0;
}
With React 16.6.3 and @Material UI 3.5.1, I am using arrays in className like className={[classes.tableCell, classes.capitalize]}
Try something like the following in your case.
class Pill extends React.Component {
render() {
return (
<button className={['pill', this.props.styleName]}>{this.props.children}</button>
);
}
}
NSDate *today = [NSDate date]; // it will give you current date
NSDate *newDate = [NSDate dateWithString:@"xxxxxx"]; // your date
NSComparisonResult result;
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
result = [today compare:newDate]; // comparing two dates
if(result==NSOrderedAscending)
NSLog(@"today is less");
else if(result==NSOrderedDescending)
NSLog(@"newDate is less");
else
NSLog(@"Both dates are same");
There are other ways that you may use to compare an NSDate objects. Each of the methods will be more efficient at certain tasks. I have chosen the compare method because it will handle most of your basic date comparison needs.
I've made this code in VB.NET but you can translate. Well pretend you have the variable Client as a TcpClient
Dim ClientRemoteIP As String = Client.Client.RemoteEndPoint.ToString.Remove(Client.Client.RemoteEndPoint.ToString.IndexOf(":"))
Hope it helps! Cheers.
If you restructured your date format into YYYY/MM/DD then you can use this simple string ordering to achieve the formating you need.
Alternatively, using the SUBSTR(store_name,start,length) command you should be able to restructure the sorting term into the above format
perhaps using the following
SELECT *
FROM vw_view
ORDER BY SUBSTR(EventDate,6,4) + SUBSTR(EventDate, 0, 5) DESC
@Liem Vo's answer is correct if you are using android.widget.Button without any overriding. If you are overriding your theme using MaterialComponents, this will not solve the issue.
So if you are
Use app:icon parameter.
<Button
android:id="@+id/bSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="Search"
android:textSize="24sp"
app:icon="@android:drawable/ic_menu_search" />
Take a look at anchor tags. You can create an anchor with
<div id="anchor-name">Heading Text</div>
and refer to it later with
<a href="http://server/page.html#anchor-name">Link text</a>
from within the vscode terminal,
git remote set-url origin https://<your github username>:<your password>@github.com/<your github username>/<your github repository name>.git
for the quickest, but not so encouraged way.
One way to get unbuffered output would be to use sys.stderr
instead of sys.stdout
or to simply call sys.stdout.flush()
to explicitly force a write to occur.
You could easily redirect everything printed by doing:
import sys; sys.stdout = sys.stderr
print "Hello World!"
Or to redirect just for a particular print
statement:
print >>sys.stderr, "Hello World!"
To reset stdout you can just do:
sys.stdout = sys.__stdout__
Sharing a few functions which I created for dates:
Please note that I wanted to get time for a particular location (not just UTC time). If you want UTC time, just remove loc variable and .In(loc) function call.
func GetTimeStamp() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
t := time.Now().In(loc)
return t.Format("20060102150405")
}
func GetTodaysDate() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("2006-01-02")
}
func GetTodaysDateTime() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("2006-01-02 15:04:05")
}
func GetTodaysDateTimeFormatted() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("Jan 2, 2006 at 3:04 PM")
}
func GetTimeStampFromDate(dtformat string) string {
form := "Jan 2, 2006 at 3:04 PM"
t2, _ := time.Parse(form, dtformat)
return t2.Format("20060102150405")
}
I find the solution in spring.io,like this:
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
I just discovered the Hmisc package:
Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.
library(Hmisc)
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th
Here's the VB.Net solution that I've used.
First make a class to compare dates:
Private Class DateComparer
Implements System.Collections.IComparer
Public Function Compare(ByVal info1 As Object, ByVal info2 As Object) As Integer Implements System.Collections.IComparer.Compare
Dim FileInfo1 As System.IO.FileInfo = DirectCast(info1, System.IO.FileInfo)
Dim FileInfo2 As System.IO.FileInfo = DirectCast(info2, System.IO.FileInfo)
Dim Date1 As DateTime = FileInfo1.CreationTime
Dim Date2 As DateTime = FileInfo2.CreationTime
If Date1 > Date2 Then Return 1
If Date1 < Date2 Then Return -1
Return 0
End Function
End Class
Then use the comparer while sorting the array:
Dim DirectoryInfo As New System.IO.DirectoryInfo("C:\")
Dim Files() As System.IO.FileInfo = DirectoryInfo.GetFiles()
Dim comparer As IComparer = New DateComparer()
Array.Sort(Files, comparer)
function my_simple_crypt( $string, $action = 'e' ) {
// you may change these values to your own
$secret_key = 'my_simple_secret_key';
$secret_iv = 'my_simple_secret_iv';
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hash( 'sha256', $secret_key );
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
if( $action == 'e' ) {
$output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
}
else if( $action == 'd' ){
$output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
}
return $output;
}
Unit testing simply verifies that individual units of code (mostly functions) work as expected. Usually you write the test cases yourself, but some can be automatically generated.
The output from a test can be as simple as a console output, to a "green light" in a GUI such as NUnit, or a different language-specific framework.
Performing unit tests is designed to be simple, generally the tests are written in the form of functions that will determine whether a returned value equals the value you were expecting when you wrote the function (or the value you will expect when you eventually write it - this is called Test Driven Development when you write the tests first).
Imagine a very simple function that you would like to test:
int CombineNumbers(int a, int b) {
return a+b;
}
The unit test code would look something like this:
void TestCombineNumbers() {
Assert.IsEqual(CombineNumbers(5, 10), 15); // Assert is an object that is part of your test framework
Assert.IsEqual(CombineNumbers(1000, -100), 900);
}
When you run the tests, you will be informed that these tests have passed. Now that you've built and run the tests, you know that this particular function, or unit, will perform as you expect.
Now imagine another developer comes along and changes the CombineNumbers()
function for performance, or some other reason:
int CombineNumbers(int a, int b) {
return a * b;
}
When the developer runs the tests that you have created for this very simple function, they will see that the first Assert
fails, and they now know that the build is broken.
They should be done as often as possible. When you are performing tests as part of the development process, your code is automatically going to be designed better than if you just wrote the functions and then moved on. Also, concepts such as Dependency Injection are going to evolve naturally into your code.
The most obvious benefit is knowing down the road that when a change is made, no other individual units of code were affected by it if they all pass the tests.
CMD:
reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
reg query HKEY_CURRENT_USER\Environment
PowerShell:
Get-Item "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Get-Item HKCU:\Environment
Powershell/.NET: (see EnvironmentVariableTarget Enum)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::Machine)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::User)
I agree with Int.TryParse but as an alternative you could use Regex.
Regex nonNumericRegex = new Regex(@"\D");
if (nonNumericRegex.IsMatch(txtEvDistance.Text))
{
//Contains non numeric characters.
return false;
}
If no other driver package worked for your obscure device go read how to make a truly universal abd and fastboot driver out of Google's USB driver. The trick is to use CompatibleID
instead of HardwareID
in the driver's INF Models section
Use #include "stdafx.h"
& system("pause");
just like the code down below.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
std::cout << "hello programmer!\n\nEnter 2 numbers: ";
int x, y;
std::cin >> x >> y;
int w = x*y;
std::cout <<"\nyour answer is: "<< w << endl;
system("pause");
}
My rule is
1, Always use class;
2, If there is any performance issue, I try to change some class to struct depending on the rules which @IAbstract mentioned, and then do a test to see if these changes can improve performance.
You can do that by storing cookies on client side.
JsonObjectRequest
actually accepts JSONObject
as body.
From this blog article,
final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{\"type\":\"example\"}");
new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });
Here is the source code and JavaDoc (@param jsonRequest
):
/**
* Creates a new request.
* @param method the HTTP method to use
* @param url URL to fetch the JSON from
* @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
Another easy way to do it without using if/else condition (works for both positive and negative numbers):
int n = 8;
List<String> messages = Arrays.asList("even", "odd");
System.out.println(messages.get(Math.abs(n%2)));
For an Odd no., the expression will return '1' as remainder, giving
messages.get(1) = 'odd' and hence printing 'odd'
else, 'even' is printed when the expression comes up with result '0'
Here's Microsoft's write up on using SET IDENTITY_INSERT, which might be helpful to others seeing this post if they, like me, found this post when trying to recreate deleted records while maintaining the original identity column value.
to recreate deleted records with original identity column value: http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx
Either store it in the gridview datakeys collection, or store it in a hidden field inside the same cell, or join the values together. That is the only way. You can't store two values in one link.
declare @RangeWidth int
set @RangeWidth = 10
select
Floor(Score/@RangeWidth) as LowerBound,
Floor(Score/@RangeWidth)+@RangeWidth as UpperBound,
Count(*)
From
ScoreTable
group by
Floor(Score/@RangeWidth)
What is Predicate Delegate?
1) Predicate is a feature that returns true or false.This concept has come in .net 2.0 framework.
2) It is being used with lambda expression (=>). It takes generic type as an argument.
3) It allows a predicate function to be defined and passed as a parameter to another function.
4) It is a special case of a Func
, in that it takes only a single parameter and always returns a bool.
In C# namespace:
namespace System
{
public delegate bool Predicate<in T>(T obj);
}
It is defined in the System namespace.
Where should we use Predicate Delegate?
We should use Predicate Delegate in the following cases:
1) For searching items in a generic collection. e.g.
var employeeDetails = employees.Where(o=>o.employeeId == 1237).FirstOrDefault();
2) Basic example that shortens the code and returns true or false:
Predicate<int> isValueOne = x => x == 1;
now, Call above predicate:
Console.WriteLine(isValueOne.Invoke(1)); // -- returns true.
3) An anonymous method can also be assigned to a Predicate delegate type as below:
Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
bool result = isUpper("Hello Chap!!");
Any best practices about predicates?
Use Func, Lambda Expressions and Delegates instead of Predicates.
One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.
I am just going to show as a static example which you can accommodate in your real world.
On each of your <tr>
's add a data attribute for id
(i.e. data-id
) with the corresponding id value and specify a data-target
, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal
to make this a trigger for modal.
<tr data-toggle="modal" data-id="1" data-target="#orderModal">
<td>1</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-toggle="modal" data-id="2" data-target="#orderModal">
<td>2</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-toggle="modal" data-id="3" data-target="#orderModal">
<td>3</td>
<td>24234234</td>
<td>A</td>
</tr>
And now in the javascript just set up the modal just once and event listen to its events so you can do your work.
$(function(){
$('#orderModal').modal({
keyboard: true,
backdrop: "static",
show:false,
}).on('show', function(){ //subscribe to show method
var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
//make your ajax call populate items or what even you need
$(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow + '</b>'))
});
});
Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.
Alternative ways here:
Another quick lookup table is available at this github page
Note : This does not consider all the containers such as, unordered_map etc. but is still great to look at. It is just a cleaner version of this
One good system is Basic4Android - great for anyone familiar with Basic,
Mind you that this is a highly opinion based question, so I stopped making fjords and made a quick table
Now library comparison is hard because on many parameters, all the four pretty much do the same thing, except possibly for Fresco because there is a whole bunch of new memory level optimizations in it.So let me know if certain parameters you'd like to see a comparison for based on my experience.
Having used Fresco the least, the answer might evolve as I continue to use and understand it for current exploits. The used personally
is having used the library atleast once in a completed app.
*Note - Fresco now supports GIF as well as WebP animations
I used this one because I like the customisation of the border-radius and size.
Material( // pause button (round)
borderRadius: BorderRadius.circular(50), // change radius size
color: Colors.blue, //button colour
child: InkWell(
splashColor: Colors.blue[900], // inkwell onPress colour
child: SizedBox(
width: 35,height: 35, //customisable size of 'button'
child: Icon(Icons.pause,color: Colors.white,size: 16,),
),
onTap: () {}, // or use onPressed: () {}
),
),
Material( // eye button (customised radius)
borderRadius: BorderRadius.only(
topRight: Radius.circular(10.0),
bottomLeft: Radius.circular(50.0),),
color: Colors.blue,
child: InkWell(
splashColor: Colors.blue[900], // inkwell onPress colour
child: SizedBox(
width: 40, height: 40, //customisable size of 'button'
child: Icon(Icons.remove_red_eye,color: Colors.white,size: 16,),),
onTap: () {}, // or use onPressed: () {}
),
),
This is my code: (work for PHP7)
private function closeConnection()
{
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
ignore_user_abort(true);
set_time_limit(0);
ob_start();
// do initial processing here
echo json_encode(['ans' => true]);
header('Connection: close');
header('Content-Length: ' . ob_get_length());
ob_end_flush();
ob_flush();
flush();
}
As others said wc -l
is the best solution, but for future reference you can use Perl:
perl -lne 'END { print $. }'
$.
contains line number and END
block will execute at the end of script.
The only way UTF-8 affects std::string
is that size()
, length()
, and all the indices are measured in bytes, not characters.
And, as sbi points out, incrementing the iterator provided by std::string
will step forward by byte, not by character, so it can actually point into the middle of a multibyte UTF-8 codepoint. There's no UTF-8-aware iterator provided in the standard library, but there are a few available on the 'Net.
If you remember that, you can put UTF-8 into std::string
, write it to a file, etc. all in the usual way (by which I mean the way you'd use a std::string
without UTF-8 inside).
You may want to start your file with a byte order mark so that other programs will know it is UTF-8.
netifaces is available via pip and easy_install. (I know, it's not in base, but it could be worth the install.)
netifaces does have some oddities across platforms:
Here's some netifaces code to play with:
import netifaces
PROTO = netifaces.AF_INET # We want only IPv4, for now at least
# Get list of network interfaces
# Note: Can't filter for 'lo' here because Windows lacks it.
ifaces = netifaces.interfaces()
# Get all addresses (of all kinds) for each interface
if_addrs = [netifaces.ifaddresses(iface) for iface in ifaces]
# Filter for the desired address type
if_inet_addrs = [addr[PROTO] for addr in if_addrs if PROTO in addr]
iface_addrs = [s['addr'] for a in if_inet_addrs for s in a if 'addr' in s]
# Can filter for '127.0.0.1' here.
The above code doesn't map an address back to its interface name (useful for generating ebtables/iptables rules on the fly). So here's a version that keeps the above information with the interface name in a tuple:
import netifaces
PROTO = netifaces.AF_INET # We want only IPv4, for now at least
# Get list of network interfaces
ifaces = netifaces.interfaces()
# Get addresses for each interface
if_addrs = [(netifaces.ifaddresses(iface), iface) for iface in ifaces]
# Filter for only IPv4 addresses
if_inet_addrs = [(tup[0][PROTO], tup[1]) for tup in if_addrs if PROTO in tup[0]]
iface_addrs = [(s['addr'], tup[1]) for tup in if_inet_addrs for s in tup[0] if 'addr' in s]
And, no, I'm not in love with list comprehensions. It's just the way my brain works these days.
The following snippet will print it all out:
from __future__ import print_function # For 2.x folks
from pprint import pprint as pp
print('\nifaces = ', end='')
pp(ifaces)
print('\nif_addrs = ', end='')
pp(if_addrs)
print('\nif_inet_addrs = ', end='')
pp(if_inet_addrs)
print('\niface_addrs = ', end='')
pp(iface_addrs)
Enjoy!
Since Java 7 you can use java.util.Objects.equals(Object a, Object b):
These utilities include null-safe or null-tolerant methods
Long id1 = null;
Long id2 = 0l;
Objects.equals(id1, id2));
The rule is as following :
A B
B as a descendant of A
A > B
B as a child of A
So
div.dropdown *
and not
div.dropdown > *
One more thing I found is that some websites uses a platform that checks the User Agent. If the value contains: "HeadlessChrome" the behavior can be weird when using headless mode.
The workaround for that will be to override the user agent value, for example in Java:
chromeOptions.addArguments("--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36");
Preferred string type in C++ is string
, defined in namespace std
, in header <string>
and you can initialize it like this for example:
#include <string>
int main()
{
std::string str1("Some text");
std::string str2 = "Some text";
}
Try the tarlog plugin. You can change the font through Ctrl++ and Ctrl-- commands with it. A very convenient thing.
SELECT * From tbl WHERE col LIKE '[0-9,a-z]%';
simply use this condition of like in sql and you will get your desired answer
You can use the strtok()
function to split a string (and specify the delimiter to use). Note that strtok()
will modify the string passed into it. If the original string is required elsewhere make a copy of it and pass the copy to strtok()
.
EDIT:
Example (note it does not handle consecutive delimiters, "JAN,,,FEB,MAR" for example):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
int main()
{
char months[] = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
char** tokens;
printf("months=[%s]\n\n", months);
tokens = str_split(months, ',');
if (tokens)
{
int i;
for (i = 0; *(tokens + i); i++)
{
printf("month=[%s]\n", *(tokens + i));
free(*(tokens + i));
}
printf("\n");
free(tokens);
}
return 0;
}
Output:
$ ./main.exe
months=[JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC]
month=[JAN]
month=[FEB]
month=[MAR]
month=[APR]
month=[MAY]
month=[JUN]
month=[JUL]
month=[AUG]
month=[SEP]
month=[OCT]
month=[NOV]
month=[DEC]
All previous answers are correct, here is one more and easy way to do it. For example, create a Dict data structure to serialize and deserialize an object
(Notice None is Null in python and I'm intentionally using this to demonstrate how you can store null and convert it to json null)
import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)
For example, like this:
const querystring = require('querystring');
const https = require('https');
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'posttestserver.com',
port: 443,
path: '/post.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(postData);
req.end();
Using the CSS white-space property is probably the best solution. Use Firebug or Chrome Developer Tools to identify the source of the extra padding you were seeing.
We can use a not famous built-in function; divmod:
>>> s = 1234.5678
>>> i, d = divmod(s, 1)
>>> i
1234.0
>>> d
0.5678000000000338
This will replace all ?
with '
:
UPDATE dbo.authors
SET city = replace(city, '?', '''')
WHERE city LIKE '%?%'
If you need to update more than one column, you can either change city
each time you execute to a different column name, or list the columns like so:
UPDATE dbo.authors
SET city = replace(city, '?', '''')
,columnA = replace(columnA, '?', '''')
WHERE city LIKE '%?%'
OR columnA LIKE '%?%'
meda's answer is completely legit, but when I copied the code I got an error!
Somewhere in the "php://input"
there's an invalid character (maybe one of the quotes?).
When I typed the "php://input"
code manually, it worked.
Took me a while to figure out!
What worked for me:
Go to config.inc.php.
Change
$cfg['Servers'][$i]['AllowNoPassword'] = true;
to
$cfg['Servers'][$i]['AllowNoPassword'] = false;
Change
$cfg['Servers'][$i]['password'] = '';
to
$cfg['Servers'][$i]['password'] = ' ';
Change
$cfg['Servers'][$i]['auth_type'] = 'config';
to
$cfg['Servers'][$i]['auth_type'] = 'http';
Reload the page http://localhost/phpmyadmin
Type : root
pass : (empty)
Now you have access to it. :)
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
You can use the EXACT
Function for exact string comparisons.
=IF(EXACT(A1, "ENG"), 1, 0)
All the above works, and here is another way if you just want to number of days/time back rather a entering date
select * from *table_name* where *datetime_column* BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
After installing openjdk with brew and runnning brew info openjdk
I got this
And from that I got this command here, and after running it I got Java working
sudo ln -sfn /usr/local/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk
Suppose you have a tree like this:
dd2e86 - 946992 - 9143a9 - a6fd86 - 5a6057 [master]
First, checkout
a temp branch:
git checkout -b temp
On temp
branch, reset --hard
to a commit that you want to change its message (for example, that commit is 946992
):
git reset --hard 946992
Use amend
to change the message:
git commit --amend -m "<new_message>"
After that the tree will look like this:
dd2e86 - 946992 - 9143a9 - a6fd86 - 5a6057 [master]
\
b886a0 [temp]
Then, cherry-pick
all the commit that is ahead of 946992
from master
to temp
and commit them, use amend
if you want to change their messages as well:
git cherry-pick 9143a9
git commit --amend -m "<new_message>
...
git cherry-pick 5a6057
git commit --amend -m "<new_message>
The tree now looks like this:
dd2e86 - 946992 - 9143a9 - a6fd86 - 5a6057 [master]
\
b886a0 - 41ab2c - 6c2a3s - 7c88c9 [temp]
Now force push the temp branch to remote:
git push --force origin temp:master
The final step, delete branch master
on local, git fetch origin
to pull branch master
from the server, then switch to branch master
and delete branch temp
.
Now both your local and remote will have all the messages updated.
This problem can occur not only due to permissions, but also due to event source key missing because it wasn't registered successfully (you need admin privileges to do it - if you just open Visual Studio as usual and run the program normally it won't be enough). Make sure that your event source "MyApp" is actually registered, i.e. that it appears in the registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application
.
From MSDN EventLog.CreateEventSource():
To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges.
So you must either run the event source registration code as an admin (also, check if the source already exists before - see the above MSDN example) or you can manually add the key to the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\MyApp
;EventMessageFile
and set its value to e.g. C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll
First you have to install a module call Serial. To do that go to the folder call Scripts which is located in python installed folder. If you are using Python 3 version it's normally located in location below,
C:\Python34\Scripts
Once you open that folder right click on that folder with shift key. Then click on 'open command window here'. After that cmd
will pop up. Write the below code in that cmd
window,
pip install PySerial
and press enter.after that PySerial module will be installed. Remember to install the module u must have an INTERNET connection.
after successfully installed the module open python IDLE and write down the bellow code and run it.
import serial
# "COM11" is the port that your Arduino board is connected.set it to port that your are using
ser = serial.Serial("COM11", 9600)
while True:
cc=str(ser.readline())
print(cc[2:][:-5])
Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":
void xyz();
or declare an incomplete type:
class klass;
struct ztruct;
and last but not least, to declare an object:
int x;
It is described, in the C++ standard, at §3.1/1 as:
A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.
A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:
int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };
Specifically the C++ standard defines it, at §3.1/1, as:
A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).
Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T
, it's often in the form:
T x = i;
but in C++ it can be:
T x(i);
or even:
T x {i};
with C++11.
So does it mean definition equals declaration plus initialization?
It depends. On what you are talking about. If you are talking about an object, for example:
int x;
This is a definition without initialization. The following, instead, is a definition with initialization:
int x = 0;
In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.
So, the answer is no: definition does not automatically mean declaration plus initialization.
Use the response contained within the exception. Here is an example:
import boto3
from botocore.exceptions import ClientError
try:
iam = boto3.client('iam')
user = iam.create_user(UserName='fred')
print("Created user: %s" % user)
except ClientError as e:
if e.response['Error']['Code'] == 'EntityAlreadyExists':
print("User already exists")
else:
print("Unexpected error: %s" % e)
The response dict in the exception will contain the following:
['Error']['Code']
e.g. 'EntityAlreadyExists' or 'ValidationError'['ResponseMetadata']['HTTPStatusCode']
e.g. 400['ResponseMetadata']['RequestId']
e.g. 'd2b06652-88d7-11e5-99d0-812348583a35'['Error']['Message']
e.g. "An error occurred (EntityAlreadyExists) ..."['Error']['Type']
e.g. 'Sender'For more information see:
[Updated: 2018-03-07]
The AWS Python SDK has begun to expose service exceptions on clients (though not on resources) that you can explicitly catch, so it is now possible to write that code like this:
import botocore
import boto3
try:
iam = boto3.client('iam')
user = iam.create_user(UserName='fred')
print("Created user: %s" % user)
except iam.exceptions.EntityAlreadyExistsException:
print("User already exists")
except botocore.exceptions.ParamValidationError as e:
print("Parameter validation error: %s" % e)
except botocore.exceptions.ClientError as e:
print("Unexpected error: %s" % e)
Unfortunately, there is currently no documentation for these exceptions but you can get a list of them as follows:
import botocore
import boto3
dir(botocore.exceptions)
Note that you must import both botocore and boto3. If you only import botocore then you will find that botocore has no attribute named exceptions
. This is because the exceptions are dynamically populated into botocore by boto3.
I needed to run two versions of tfjs-core and found that both needed to be built after being installed.
package.json:
"dependencies": {
"tfjs-core-0.14.3": "git://github.com/tensorflow/tfjs-core#bb0a830b3bda1461327f083ceb3f889117209db2",
"tfjs-core-1.1.0": "git://github.com/tensorflow/tfjs-core#220660ed8b9a252f9d0847a4f4e3c76ba5188669"
}
Then:
cd node_modules/tfjs-core-0.14.3 && yarn install && yarn build-npm && cd ../../
cd node_modules/tfjs-core-1.1.0 && yarn install && yarn build-npm && cd ../../
And finally, to use the libraries:
import * as tf0143 from '../node_modules/tfjs-core-0.14.3/dist/tf-core.min.js';
import * as tf110 from '../node_modules/tfjs-core-1.1.0/dist/tf-core.min.js';
This worked great but is most certainly #hoodrat
I have tested your example, and while Request.QueryString is not convertible to a string neither implicit nor explicit still the .ToString() method returns the correct result.
Further more when concatenating with a string using the "+" operator as in your example it will also return the correct result (because this behaves as if .ToString() was called).
As such there is nothing wrong with your code, and I would suggest that your issue was because of a typo in your code writing "Querystring" instead of "QueryString".
And this makes more sense with your error message since if the problem is that QueryString is a collection and not a string it would have to give another error message.
The following bash script returns the Name of your current ec2 instance (the value of the "Name" tag). Modify TAG_NAME to your specific case.
TAG_NAME="Name"
INSTANCE_ID="`wget -qO- http://instance-data/latest/meta-data/instance-id`"
REGION="`wget -qO- http://instance-data/latest/meta-data/placement/availability-zone | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"
TAG_VALUE="`aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=$TAG_NAME" --region $REGION --output=text | cut -f5`"
To install the aws cli
sudo apt-get install python-pip -y
sudo pip install awscli
In case you use IAM instead of explicit credentials, use these IAM permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [ "ec2:DescribeTags"],
"Resource": ["*"]
}
]
}
From June 2018 Android officially support this feature for Android 4.0 (API level 14) and higher.
With Android 8.0 (API level 26) and higher:
setAutoSizeTextTypeUniformWithConfiguration(int autoSizeMinTextSize, int autoSizeMaxTextSize,
int autoSizeStepGranularity, int unit);
Android versions prior to Android 8.0 (API level 26):
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(TextView textView,
int autoSizeMinTextSize, int autoSizeMaxTextSize, int autoSizeStepGranularity, int unit)
Check out my detail answer.
$("div.clickable").click(
function(event)
{
window.location = $(this).attr("url");
event.preventDefault();
});
Slightly different from what you described, but I think this might be what you actually need:
svn blame filename
It will print the file with each line prefixed by the time and author of the commit that last changed it.
To increase the phpMyAdmin Session Timeout, open config.inc.php in the root phpMyAdmin directory and add this setting (anywhere).
$cfg['LoginCookieValidity'] = <your_new_timeout>;
Where is some number larger than 1800.
Note:
Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.
On submitting, you would get an array as if created like this:
$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );
However, I would suggest changing your form names to this format instead:
name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...
Using that format, it's much easier to loop through the values.
if ( isset( $_POST['diameters'] ) )
{
echo '<table>';
foreach ( $_POST['diameters'] as $diam )
{
// here you have access to $diam['top'] and $diam['bottom']
echo '<tr>';
echo ' <td>', $diam['top'], '</td>';
echo ' <td>', $diam['bottom'], '</td>';
echo '</tr>';
}
echo '</table>';
}
There are several methods to find kafka version
Method 1 simple:-
ps -ef|grep kafka
it will displays all running kafka clients in the console... Ex:- /usr/hdp/current/kafka-broker/bin/../libs/kafka-clients-0.10.0.2.5.3.0-37.jar we are using 0.10.0.2.5.3.0-37 version of kafka
Method 2:- go to
cd /usr/hdp/current/kafka-broker/libs
ll |grep kafka
Ex:- kafka_2.10-0.10.0.2.5.3.0-37.jar kafka-clients-0.10.0.2.5.3.0-37.jar
same result as method 1 we can find the version of kafka using in kafka libs.
I'd avoid eval.
To solve this problem, you should know these things about JavaScript.
.
rather than square brackets []
, or vice versa.Your problem is a result of considering the dot manner of reference rather than the square bracket manner.
So, why not something like,
window["functionName"]();
That's assuming your function lives in the global space. If you've namespaced, then:
myNameSpace["functionName"]();
Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.
try this
<div id="login_div" runat="server">
and on the code behind.
login_div.Style.Add("display", "none");
parseInt((new Date('2012.08.10').getTime() / 1000).toFixed(0))
It's important to add the toFixed(0)
to remove any decimals when dividing by 1000 to convert from milliseconds to seconds.
The .getTime()
function returns the timestamp in milliseconds, but true unix timestamps are always in seconds.
To select the database query below :
use DatabaseName
Now
SELECT * FROM INFORMATION_SCHEMA.TABLES
Now you can see the created tables below in console .
PFA.
Indeed, just as commented by Tim Williams, the way to make it work is pre-formatting as text. Thus, to do it all via VBA, just do that:
Cells(1, 1).NumberFormat = "@"
Cells(1, 1).Value = "1234,56"
Another way to look at this. Check out the details of the exception:
In [49]: try:
...: open('file.DNE.txt')
...: except Exception as e:
...: print(dir(e))
...:
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']
There are lots of "things" to access using the 'as e' syntax.
This code was solely meant to show the details of this instance.
Here's how I do file upload in react using axios
import React from 'react'
import axios, { post } from 'axios';
class SimpleReactFileUpload extends React.Component {
constructor(props) {
super(props);
this.state ={
file:null
}
this.onFormSubmit = this.onFormSubmit.bind(this)
this.onChange = this.onChange.bind(this)
this.fileUpload = this.fileUpload.bind(this)
}
onFormSubmit(e){
e.preventDefault() // Stop form submit
this.fileUpload(this.state.file).then((response)=>{
console.log(response.data);
})
}
onChange(e) {
this.setState({file:e.target.files[0]})
}
fileUpload(file){
const url = 'http://example.com/file-upload';
const formData = new FormData();
formData.append('file',file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return post(url, formData,config)
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h1>File Upload</h1>
<input type="file" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)
}
}
export default SimpleReactFileUpload
As it was said here before Rails (ActiveSupport) have a handy blank? method and it is implemented like this:
class Object
def blank?
respond_to?(:empty?) ? empty? : !self
end
end
Pretty easy to add to any ruby-based project.
The beauty of this solution is that it works auto-magicaly not only for Strings but also for Arrays and other types.
You can use purrr
as well, which is similar to apply
family functions:
as.data.frame(purrr::map_chr(mtcars, class))
purrr::map_df(mtcars, class)
The easiest is
as @greggo pointed out
string="mystring";
string[:-1]
A restart of the machine worked for me. None of the solutions provided so far worked for me.
Env Windows 10 + Git Bash
EDIT: I see the same solution was here: git index.lock File exists when I try to commit, but cannot delete the file
To answer your other question. The size of a pointer and the size of what it points to are not related. A good analogy is to consider them like postal addresses. The size of the address of a house has no relationship to the size of the house.
I've just noticed something common to most of the answers here, and confirmed on my fresh install. It's actually obvious if you look at the recommendations to run mysqladmin -u root
without -p
.
There is no password.
Brew sets mysql up with just a root user and no password at all. This makes sense, I guess, but the post-install Caveats don't mention it at all.
The difference between die()
and exit()
in PHP is their origin.
exit()
is from exit()
in C.die()
is from die
in Perl.die()
and exit()
are equivalent functions.
PHP Manual for die
:
This language construct is equivalent to
exit()
.
PHP Manual for exit
:
Note: This language construct is equivalent to
die()
.
PHP Manual for List of Function Aliases:
die()
and exit()
are different in other languages but in PHP they are identical.
From Yet another PHP rant:
...As a C and Perl coder, I was ready to answer, "Why, exit() just bails off the program with a numeric exit status, while die() prints out the error message to stderr and exits with EXIT_FAILURE status." But then I remembered we're in messy-syntax-land of PHP.
In PHP, exit() and die() are identical.
The designers obviously thought "Hmm, let's borrow exit() from C. And Perl folks probably will like it if we take die() as is from Perl too. Oops! We have two exit functions now! Let's make it so that they both can take a string or integer as an argument and make them identical!"
The end result is that this didn't really make things any "easier", just more confusing. C and Perl coders will continue to use exit() to toss an integer exit value only, and die() to toss an error message and exit with a failure. Newbies and PHP-as-a-first-language people will probably wonder "umm, two exit functions, which one should I use?" The manual doesn't explain why there's exit() and die().
In general, PHP has a lot of weird redundancy like this - it tries to be friendly to people who come from different language backgrounds, but while doing so, it creates confusing redundancy.
Here's a pretty solid solution that incorporates the best ideas so far as well as includes my solution to a problem highlighted with Offerein's. No javascript is used.
If you care about backwards compatibility with IE (and even Edge 13), you can't use the form="your-form"
attribute.
Use a standard submit input with display none and add a label for it outside the form:
<form id="your-form">
<input type="submit" id="your-form-submit" style="display: none;">
</form>
Note the use of display: none;
. This is intentional. Using bootstrap's .hidden
class conflicts with jQuery's .show()
and .hide()
, and has since been deprecated in Bootstrap 4.
Now simply add a label for your submit, (styled for bootstrap):
<label for="your-form-submit" role="button" class="btn btn-primary" tabindex="0">
Submit
</label>
Unlike other solutions, I'm also using tabindex - set to 0 - which means that we are now compatible with keyboard tabbing. Adding the role="button"
attribute gives it the CSS style cursor: pointer
. Et voila. (See this fiddle).
I was looking for an answer on what |=
does in Groovy and although answers above are right on they did not help me understand a particular piece of code I was looking at.
In particular, when applied to a boolean variable "|=" will set it to TRUE the first time it encounters a truthy expression on the right side and will HOLD its TRUE value for all |= subsequent calls. Like a latch.
Here a simplified example of this:
groovy> boolean result
groovy> //------------
groovy> println result //<-- False by default
groovy> println result |= false
groovy> println result |= true //<-- set to True and latched on to it
groovy> println result |= false
Output:
false
false
true
true
Edit: Why is this useful?
Consider a situation where you want to know if anything has changed on a variety of objects and if so notify some one of the changes. So, you would setup a hasChanges
boolean and set it to |= diff (a,b)
and then |= dif(b,c)
etc.
Here is a brief example:
groovy> boolean hasChanges, a, b, c, d
groovy> diff = {x,y -> x!=y}
groovy> hasChanges |= diff(a,b)
groovy> hasChanges |= diff(b,c)
groovy> hasChanges |= diff(true,false)
groovy> hasChanges |= diff(c,d)
groovy> hasChanges
Result: true
If you "require" 'exampleDirective' from another directive + your logic is in 'exampleDirective's' controller (let's say 'exampleCtrl'):
app.directive('exampleDirective', function () {
return {
restrict: 'A',
scope: false,
bindToController: {
myCallback: '&exampleFunction'
},
controller: 'exampleCtrl',
controllerAs: 'vm'
};
});
app.controller('exampleCtrl', function () {
var vm = this;
vm.myCallback();
});
Some formats, like PNG which is lossless, will ignore the quality setting.
In case of array like
result = [ '2015', '2014', '2013', '2011' ],
it gets tricky if you are using escape sequence like:
result = [ \'2015\', \'2014\', \'2013\', \'2011\' ].
Instead, good way to do it is to wrap the array with single quotes as follows:
result = "'"+result+"'";
This is the hacky way that I am getting around this, at least it works in all current browsers (on Windows, I don't own a Mac):
if (navigator.geolocation) {
var location_timeout = setTimeout("geolocFail()", 10000);
navigator.geolocation.getCurrentPosition(function(position) {
clearTimeout(location_timeout);
var lat = position.coords.latitude;
var lng = position.coords.longitude;
geocodeLatLng(lat, lng);
}, function(error) {
clearTimeout(location_timeout);
geolocFail();
});
} else {
// Fallback for no geolocation
geolocFail();
}
This will also work if someone clicks the close or chooses no or chooses the Never Share option on Firefox.
Clunky, but it works.
in addition, one of the differences can come from provider of the library, and what they code. for example here i'm using cordova platform in combination with mobile angular ui, and while input/div/etc tags work well with ng-click, the button can cause Visual Studio debugger to crash, surely by differences, that the programmer caused; note that MattC answer point to the same issue, the jQuery is just a lib, and the provider didn't think of some functionality on one element, that s/he provides on another. so when you are using a library, you may face an issue with one element, which you won't face with another. and simply the popular one like input
, will mostly be the fixed one, just because it's more popular.
If you want to use #include <myheader.hpp>
inside your cpp files you can use:
g++ *.cpp -I. -o out
On a high level, you have no other choice than to walk through the whole Dictionary and look at each value.
Maybe this helps: http://bytes.com/forum/thread563638.html Copy/Pasting from John Timney:
Dictionary<string, string> s = new Dictionary<string, string>();
s.Add("1", "a Item");
s.Add("2", "c Item");
s.Add("3", "b Item");
List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(s);
myList.Sort(
delegate(KeyValuePair<string, string> firstPair,
KeyValuePair<string, string> nextPair)
{
return firstPair.Value.CompareTo(nextPair.Value);
}
);
If None
is a valid data value then you need to the variable another way. You could use:
var = object()
This sentinel is suggested by Nick Coghlan.
Since your local repository is few commits ahead, git tries to merge your remote to your local repo. This can be handled via merge, but in your case, perhaps you are looking for rebase, i.e. add your commit to the top. You can do this with
git rebase
or git pull --rebase
Here is a good article explaining the difference between git pull
& git pull --rebase
.
https://www.derekgourlay.com/blog/git-when-to-merge-vs-when-to-rebase/
In some cases you can not filter by process id. For example, in my case i needed to sniff traffic from one process. But I found in its config target machine IP-address, added filter ip.dst==someip
and voila. It won't work in any case, but for some it's useful.
As it is not stated anywhere in the current answers, the fastest solution if you are not embedding js into your template is:
Put <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script>
before your reference to script.js file in your template, then add csrfmiddlewaretoken
into your data
dictionary in your js file:
$.ajax({
type: 'POST',
url: somepathname + "do_it/",
data: {csrfmiddlewaretoken: window.CSRF_TOKEN},
success: function() {
console.log("Success!");
}
})
values = new float[] { 0.1f, 0.2f, 0.3f };
Ideally, there should only be two scenarios of when an iOS application would need to accept an un-trusted certificate.
Scenario A: You are connected to a test environment which is using a self-signed certificate.
Scenario B: You are Proxying HTTPS
traffic using a MITM Proxy like Burp Suite, Fiddler, OWASP ZAP, etc.
The Proxies will return a certificate signed by a self-signed CA so that the proxy is able to capture HTTPS
traffic.
Production hosts should never use un-trusted certificates for obvious reasons.
If you need to have the iOS simulator accept an un-trusted certificate for testing purposes it is highly recommended that you do not change application logic in order disable the built in certificate validation provided by the NSURLConnection
APIs. If the application is released to the public without removing this logic, it will be susceptible to man-in-the-middle attacks.
The recommended way to accept un-trusted certificates for testing purposes is to import the Certificate Authority(CA) certificate which signed the certificate onto your iOS Simulator or iOS device. I wrote up a quick blog post which demonstrates how to do this which an iOS Simulator at:
I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch
, then remove them manually, but this will not work well if there are a lot.
Here is a solution that utilizes bash arrays to capture all files.
# Build bash array of the file names
while read -r file; do
rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)
git rm –-cached "${rmlist[@]}"
git commit -m 'ignore update'
I used below code and it's working fine for me. :
let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
do {
dictonary = try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
if let myDictionary = dictonary
{
print(" User name is: \(myDictionary["userName"]!)")
}
} catch let error as NSError {
print(error)
}
}
Ok, I have two ideas for you. Hopefully one of them will get you where you need to go. Note that the first one ignores the request to do this as a formula since that solution is not pretty. I figured I make sure the easy way really wouldn't work for you ;^).
This solution will work with the following caveats:
Here is the summary of the solution:
And here is a step by step example:
Hope this helps....
rootLayout.findFocus().clearFocus();
<?
ob_start(); // ensures anything dumped out will be caught
// do stuff here
$url = 'http://example.com/thankyou.php'; // this can be set based on whatever
// clear out the output buffer
while (ob_get_status())
{
ob_end_clean();
}
// no redirect
header( "Location: $url" );
?>
Another way:
if (s.size > 5) s.reverse.substring(5).reverse
BTW, this is Scala code. May need brackets to work in Java.
The given code given will work absolutely fine if we run from console. and there is no package name in the class
You have to make sure where you have your ".class" file. because, if package name is given for the class, you have to make sure to keep the ".class" file inside the specified folder. For example, my package name is "src.main.code" , I have to create a code folder,inside main folder, inside src folder and put Test.class in code folder. then it will work perfectly.
This syntax is documented only in log4j 2.X so make sure you are using the correct version.
<Appenders>
<File name="file" fileName="${env:LOG_PATH}">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
</PatternLayout>
</File>
</Appenders>
http://logging.apache.org/log4j/2.x/manual/lookups.html#EnvironmentLookup
$.each(result, function(key, value) {
console.log(key+ ':' + value);
});
Method 1 ( for multiserver )
First , lets make a backup of original config.
sudo cp /etc/phpmyadmin/config.inc.php ~/
Now in /usr/share/doc/phpmyadmin/examples/ you will see a file config.manyhosts.inc.php. Just copy in to /etc/phpmyadmin/ using command bellow:
sudo cp /usr/share/doc/phpmyadmin/examples/config.manyhosts.inc.php \
/etc/phpmyadmin/config.inc.php
Edit the config.inc.php
sudo nano /etc/phpmyadmin/config.inc.php
Search for :
$hosts = array (
"foo.example.com",
"bar.example.com",
"baz.example.com",
"quux.example.com",
);
And add your ip or hostname array save ( in nano CTRL+X press Y ) and exit . Done
Method 2 ( single server ) Edit the config.inc.php
sudo nano /etc/phpmyadmin/config.inc.php
Search for :
/* Server parameters */
if (empty($dbserver)) $dbserver = 'localhost';
$cfg['Servers'][$i]['host'] = $dbserver;
if (!empty($dbport) || $dbserver != 'localhost') {
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['port'] = $dbport;
}
And replace with:
$cfg['Servers'][$i]['host'] = '192.168.1.100';
$cfg['Servers'][$i]['port'] = '3306';
Remeber to replace 192.168.1.100 with your own mysql ip server.
Sorry for my bad English ( google translate have the blame :D )
Depending on why you are doing this, using a std::set might be a better idea than std::vector.
It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial. The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.
This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.
I've been looking for a solution that i can use on bootstrap 4 navbars and other groups of links.
For one reason or another most solutions didn't work especially the ones that try to add 'active' to links onclick because of course once the link is clicked if it takes you to another page then the 'active' you added won't be there because the DOM has changed. Many of the other solutions didn't work either because they often did not match the link or they matched more than one.
This elegant solution is fine for links that are different ie: about.php, index.php, etc...
$(function() {
$('nav a[href^="' + location.pathname.split("/")[2] + '"]').addClass('active');
});
However when it came to the same links with different query strings such as index.php?tag=a, index.php?tag=b, index.php?tag=c it would set all of them to active whichever was clicked as it's matching the pathname not the query as well.
So i tried this code which matched the pathname and the query string and it worked on all the links with query strings but when a link like index.php was clicked it would set the similar query string links active as well. This is because my function is returning an empty string if there is no query string in the link, again just matching the pathname.
$(function() {
$('nav a[href^="' + location.pathname.split("/")[2] + returnQueryString(location.href.split("?")[1]) + '"]').addClass('active');
});
/** returns a query string if there, else an empty string */
function returnQueryString (element) {
if (element === undefined)
return "";
else
return '?' + element;
}
So in the end i abandoned this route and kept it simple and wrote this.
$('.navbar a').each(function(index, element) {
//console.log(index+'-'+element.href);
//console.log(location.href);
/** look at each href in the navbar
* if it matches the location.href then set active*/
if (element.href === location.href){
//console.log("---------MATCH ON "+index+" --------");
$(element).addClass('active');
}
});
It works on all links with or without query strings because element.href and location.href both return the full path. For other menus etc you can simply change the parent class selector (navbar) for another ie:
$('.footer a').each(function(index, element)...
One last thing which also seems important and that is the js & css library's you are using however that's another post perhaps. I hope this helps and contributes.
Or if you want to avoid lambda and have a generator instead of a list:
(sorted(col)[1] for col in lst)
I think the true answer is that jQuery was developed long before querySelector/querySelectorAll
became available in all major browsers.
Initial release of jQuery was in 2006. In fact, even jQuery was not the first which implemented CSS selectors.
IE was the last browser to implement querySelector/querySelectorAll
. Its 8th version was released in 2009.
So now, DOM elements selectors is not the strongest point of jQuery anymore. However, it still has a lot of goodies up its sleeve, like shortcuts to change element's css and html content, animations, events binding, ajax.