I have faced the same issue. The error output window looks like this:
Following the steps resolved the issue:
Below Generic Credential, choose an entry of the git & update password.
Password should be same as windows(system) login password.
How about adding this to your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
I managed to fix it finally. The problem is not related to HikariCP.
The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional
or enveloping all the logic in a single call to transactional service method seem to solve the problem.
As @yigit mentioned, you need to override onMeasure(). Both @user2302510 and @DenisNek have good answers but if you want to support ItemDecoration you can use this custom layout manager.
And other answers cannot scroll when there are more items than can be displayed on the screen though. This one is using default implemantation of onMeasure() when there are more items than screen size.
public class MyLinearLayoutManager extends LinearLayoutManager {
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
// If child view is more than screen size, there is no need to make it wrap content. We can use original onMeasure() so we can scroll view.
if (height < heightSize && width < widthSize) {
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
} else {
super.onMeasure(recycler, state, widthSpec, heightSpec);
}
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
// For adding Item Decor Insets to view
super.measureChildWithMargins(view, 0, 0);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight() + getDecoratedLeft(view) + getDecoratedRight(view), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom() + getPaddingBottom() + getDecoratedBottom(view) , p.height);
view.measure(childWidthSpec, childHeightSpec);
// Get decorated measurements
measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
}
And if you want to use it with GridLayoutManager just extends it from GridLayoutManager and change
for (int i = 0; i < getItemCount(); i++)
to
for (int i = 0; i < getItemCount(); i = i + getSpanCount())
Your Custom AuthenticationProvider class should be annotated with the following:
@Transactional
This will make sure the presence of the hibernate session there as well.
There are two BeanUtils.copyProperties(parameter1, parameter2) in Java.
One is
org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)
Another is
org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)
Pay attention to the opposite position of parameters.
As said, JsonMappingException: out of START_ARRAY token
exception is thrown by Jackson object mapper as it's expecting an Object {}
whereas it found an Array [{}]
in response.
A simpler solution could be replacing the method getLocations
with:
public static List<Location> getLocations(InputStream inputStream) {
ObjectMapper objectMapper = new ObjectMapper();
try {
TypeReference<List<Location>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
On the other hand, if you don't have a pojo like Location
, you could use:
TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);
If you're playing around in Blazor and get the error, you need to add the package Microsoft.AspNetCore.Blazor.HttpClient
.
Swift 3 & Swift 4:
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
var visibleRect = CGRect()
visibleRect.origin = collectionView.contentOffset
visibleRect.size = collectionView.bounds.size
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
guard let indexPath = collectionView.indexPathForItem(at: visiblePoint) else { return }
print(indexPath[1])
}
If you want to show actual number than you can add +1
Your using
statements appear to be correct.
Are you, perhaps, missing the assembly reference to System.configuration.dll
?
Right click the "References" folder in your project and click on "Add Reference..."
Static tStart As Single, tEnd As Single, myInterval As Integer
myInterval = 5 ' seconds
tStart = VB.Timer()
tEnd = myInterval + VB.Timer()
Do While tEnd > tStart
Application.DoEvents()
tStart = VB.Timer()
Loop
I would use XMLHTTP request to retrieve page content as much faster. Then it is easy enough to use querySelectorAll to apply a CSS class selector to grab by class name. Then you access the child elements by tag name and index.
Option Explicit
Public Sub GetInfo()
Dim sResponse As String, html As HTMLDocument, elements As Object, i As Long
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://www.hsbc.com/about-hsbc/leadership", False
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
.send
sResponse = StrConv(.responseBody, vbUnicode)
End With
Set html = New HTMLDocument
With html
.body.innerHTML = sResponse
Set elements = .querySelectorAll(".profile-col1")
For i = 0 To elements.Length - 1
Debug.Print String(20, Chr$(61))
Debug.Print elements.item(i).getElementsByTagName("a")(0).innerText
Debug.Print elements.item(i).getElementsByTagName("p")(0).innerText
Debug.Print elements.item(i).getElementsByTagName("p")(1).innerText
Next
End With
End Sub
References:
VBE > Tools > References > Microsoft HTML Object Library
After updating from TFS 2018 v3 to DevOps Server 2019.0.1 last weekend I now receive this authentication error when attempting to manage security:
TF30063: You are not authorized to access tfs.
I receive this error when attempting to manage security from the Server Administration Console via Application Tier > Administer Security. I also receive the error when I attempt to set permissions via tfssecurity cli tool. I am in the local administrator group and I am listed in the console administration user section.
I'm trying to set permissions because after the update I received several reports from employees that receive errors when they try to access their projects. Those errors are:
TF40049: You do not have licensing rights to access this feature: Code.
I spent 8 hrs working through this issue yesterday, and this is what fixed our problem:
I deleted the cache off the server based on an article I read with the same error, a user was having security/permissions issues with visual studio and they deleted the vs cache on their local machine and it solved their problem. I don't know if deleting the cache or the reboot would have fixed it independently because I did them both as a single troubleshooting step.
Hope this helps someone.
I agree with bizl
[XmlInclude(typeof(ParentOfTheItem))]
[Serializable]
public abstract class WarningsType{ }
also if you need to apply this included class to an object item you can do like that
[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))]
public object[] Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
This can happen if you call
.SingleOrDefault()
on an IEnumerable with 2 or more elements.
I had the same problem, two list boxes and two buttons.
The data in the list boxes was being loaded from a database and you could move items between boxes by clicking the buttons.
I was getting an invalid postback.
turns out that it was the data had carriage return line feeds in it which you cannot see when displayed in the list box.
worked fine in every browser except IE 10 and IE 11.
Remove the carriage return line feeds and all works fine.
The answer below is apparently obsolete now, but works with older drivers. See comments.
If you have the connection string you could also use MongoDatabase directly:
var db = MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");
clear()
will go through the underlying Array and set each entry to null;
removeAll(collection)
will go through the ArrayList checking for collection and remove(Object)
it if it exists.
I would imagine that clear()
is way faster then removeAll because it's not comparing, etc.
Had the same issue and managed to resolve it.
In my case, I had an AD group in the current logon domain with members (users) from a sub domain. The server that I was running the code on could not access the domain controller of the sub domain (the server had never needed to access the sub domain before).
I struggled for a while as my desktop PC could access the domain so everything looked OK in the MMC plugin (Active Directory Users & Computers).
Hope that helps someone else.
you can returns a private collection named HttpValueCollection even the documentation says it's a NameValueCollection using the ParseQueryString utility. Then add the keys manually, HttpValueCollection do the encoding for you. And then just append the QueryString manually :
var qs = HttpUtility.ParseQueryString("");
qs.Add("name", "John")
qs.Add("contact", "calgary");
qs.Add("contact", "vancouver")
<a href="<%: Url.Action("GetByList", "Listing")%>?<%:qs%>">
<span>People</span>
</a>
You may just need to add @Transient
annotations on roles to not serialize the set.
you can combine them using LINQ:
list = list1.Concat(list2).Concat(list3).ToList();
the more traditional approach of using List.AddRange()
might be more efficient though.
The following example is from the Code Project article, (Almost) Everything In Active Directory via C#:
// userDn is a Distinguished Name such as:
// "LDAP://CN=Joe Smith,OU=Sales,OU=domain,OU=com"
public ArrayList Groups(string userDn, bool recursive)
{
ArrayList groupMemberships = new ArrayList();
return AttributeValuesMultiString("memberOf", userDn,
groupMemberships, recursive);
}
public ArrayList AttributeValuesMultiString(string attributeName,
string objectDn, ArrayList valuesCollection, bool recursive)
{
DirectoryEntry ent = new DirectoryEntry(objectDn);
PropertyValueCollection ValueCollection = ent.Properties[attributeName];
IEnumerator en = ValueCollection.GetEnumerator();
while (en.MoveNext())
{
if (en.Current != null)
{
if (!valuesCollection.Contains(en.Current.ToString()))
{
valuesCollection.Add(en.Current.ToString());
if (recursive)
{
AttributeValuesMultiString(attributeName, "LDAP://" +
en.Current.ToString(), valuesCollection, true);
}
}
}
}
ent.Close();
ent.Dispose();
return valuesCollection;
}
Just call the Groups method with the Distinguished Name for the user, and pass in the bool flag to indicate if you want to include nested / child groups memberships in your resulting ArrayList:
ArrayList groups = Groups("LDAP://CN=Joe Smith,OU=Sales,OU=domain,OU=com", true);
foreach (string groupName in groups)
{
Console.WriteLine(groupName);
}
If you need to do any serious level of Active Directory programming in .NET I highly recommend bookmarking & reviewing the Code Project article I mentioned above.
Use "vol" shell command and parse serial from it's output, like this. Works at least in Win7
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CheckHD
{
class HDSerial
{
const string MY_SERIAL = "F845-BB23";
public static bool CheckSerial()
{
string res = ExecuteCommandSync("vol");
const string search = "Number is";
int startI = res.IndexOf(search, StringComparison.InvariantCultureIgnoreCase);
if (startI > 0)
{
string currentDiskID = res.Substring(startI + search.Length).Trim();
if (currentDiskID.Equals(MY_SERIAL))
return true;
}
return false;
}
public static string ExecuteCommandSync(object command)
{
try
{
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows,
// and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
return result;
}
catch (Exception)
{
// Log the exception
return null;
}
}
}
}
If you are looking for a custom configuration section like following
<CustomApplicationConfig>
<Credentials Username="itsme" Password="mypassword"/>
<PrimaryAgent Address="10.5.64.26" Port="3560"/>
<SecondaryAgent Address="10.5.64.7" Port="3570"/>
<Site Id="123" />
<Lanes>
<Lane Id="1" PointId="north" Direction="Entry"/>
<Lane Id="2" PointId="south" Direction="Exit"/>
</Lanes>
</CustomApplicationConfig>
then you can use my implementation of configuration section so to get started add System.Configuration
assembly reference to your project
Look at the each nested elements I used, First one is Credentials with two attributes so lets add it first
Credentials Element
public class CredentialsConfigElement : System.Configuration.ConfigurationElement
{
[ConfigurationProperty("Username")]
public string Username
{
get
{
return base["Username"] as string;
}
}
[ConfigurationProperty("Password")]
public string Password
{
get
{
return base["Password"] as string;
}
}
}
PrimaryAgent and SecondaryAgent
Both has the same attributes and seem like a Address to a set of servers for a primary and a failover, so you just need to create one element class for both of those like following
public class ServerInfoConfigElement : ConfigurationElement
{
[ConfigurationProperty("Address")]
public string Address
{
get
{
return base["Address"] as string;
}
}
[ConfigurationProperty("Port")]
public int? Port
{
get
{
return base["Port"] as int?;
}
}
}
I'll explain how to use two different element with one class later in this post, let us skip the SiteId as there is no difference in it. You just have to create one class same as above with one property only. let us see how to implement Lanes collection
it is splitted in two parts first you have to create an element implementation class then you have to create collection element class
LaneConfigElement
public class LaneConfigElement : ConfigurationElement
{
[ConfigurationProperty("Id")]
public string Id
{
get
{
return base["Id"] as string;
}
}
[ConfigurationProperty("PointId")]
public string PointId
{
get
{
return base["PointId"] as string;
}
}
[ConfigurationProperty("Direction")]
public Direction? Direction
{
get
{
return base["Direction"] as Direction?;
}
}
}
public enum Direction
{
Entry,
Exit
}
you can notice that one attribute of LanElement
is an Enumeration and if you try to use any other value in configuration which is not defined in Enumeration application will throw an System.Configuration.ConfigurationErrorsException
on startup. Ok lets move on to Collection Definition
[ConfigurationCollection(typeof(LaneConfigElement), AddItemName = "Lane", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class LaneConfigCollection : ConfigurationElementCollection
{
public LaneConfigElement this[int index]
{
get { return (LaneConfigElement)BaseGet(index); }
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
public void Add(LaneConfigElement serviceConfig)
{
BaseAdd(serviceConfig);
}
public void Clear()
{
BaseClear();
}
protected override ConfigurationElement CreateNewElement()
{
return new LaneConfigElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((LaneConfigElement)element).Id;
}
public void Remove(LaneConfigElement serviceConfig)
{
BaseRemove(serviceConfig.Id);
}
public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
public void Remove(String name)
{
BaseRemove(name);
}
}
you can notice that I have set the AddItemName = "Lane"
you can choose whatever you like for your collection entry item, i prefer to use "add" the default one but i changed it just for the sake of this post.
Now all of our nested Elements have been implemented now we should aggregate all of those in a class which has to implement System.Configuration.ConfigurationSection
CustomApplicationConfigSection
public class CustomApplicationConfigSection : System.Configuration.ConfigurationSection
{
private static readonly ILog log = LogManager.GetLogger(typeof(CustomApplicationConfigSection));
public const string SECTION_NAME = "CustomApplicationConfig";
[ConfigurationProperty("Credentials")]
public CredentialsConfigElement Credentials
{
get
{
return base["Credentials"] as CredentialsConfigElement;
}
}
[ConfigurationProperty("PrimaryAgent")]
public ServerInfoConfigElement PrimaryAgent
{
get
{
return base["PrimaryAgent"] as ServerInfoConfigElement;
}
}
[ConfigurationProperty("SecondaryAgent")]
public ServerInfoConfigElement SecondaryAgent
{
get
{
return base["SecondaryAgent"] as ServerInfoConfigElement;
}
}
[ConfigurationProperty("Site")]
public SiteConfigElement Site
{
get
{
return base["Site"] as SiteConfigElement;
}
}
[ConfigurationProperty("Lanes")]
public LaneConfigCollection Lanes
{
get { return base["Lanes"] as LaneConfigCollection; }
}
}
Now you can see that we have two properties with name PrimaryAgent
and SecondaryAgent
both have the same type now you can easily understand why we had only one implementation class against these two element.
Before you can use this newly invented configuration section in your app.config (or web.config) you just need to tell you application that you have invented your own configuration section and give it some respect, to do so you have to add following lines in app.config (may be right after start of root tag).
<configSections>
<section name="CustomApplicationConfig" type="MyNameSpace.CustomApplicationConfigSection, MyAssemblyName" />
</configSections>
NOTE: MyAssemblyName should be without .dll e.g. if you assembly file name is myDll.dll then use myDll instead of myDll.dll
to retrieve this configuration use following line of code any where in your application
CustomApplicationConfigSection config = System.Configuration.ConfigurationManager.GetSection(CustomApplicationConfigSection.SECTION_NAME) as CustomApplicationConfigSection;
I hope above post would help you to get started with a bit complicated kind of custom config sections.
Happy Coding :)
****Edit****
To Enable LINQ on LaneConfigCollection
you have to implement IEnumerable<LaneConfigElement>
And Add following implementation of GetEnumerator
public new IEnumerator<LaneConfigElement> GetEnumerator()
{
int count = base.Count;
for (int i = 0; i < count; i++)
{
yield return base.BaseGet(i) as LaneConfigElement;
}
}
for the people who are still confused about how yield really works read this nice article
Two key points taken from above article are
it doesn’t really end the method’s execution. yield return pauses the method execution and the next time you call it (for the next enumeration value), the method will continue to execute from the last yield return call. It sounds a bit confusing I think… (Shay Friedman)
Yield is not a feature of the .Net runtime. It is just a C# language feature which gets compiled into simple IL code by the C# compiler. (Lars Corneliussen)
There is a bit of confusion going on here, but let me try to clarify things:
Lets say you wanted sql that looked something like:
SELECT
`main_table`.*,
`main_table`.`email` AS `invitation_email`,
`main_table`.`group_id` AS `invitee_group_id`
FROM
`enterprise_invitation` AS `main_table`
WHERE (
(status = 'new')
OR (customer_id = '1234')
)
In order to achieve this, your collection needs to be formatted like this:
$collection = Mage::getModel('enterprise_invitation/invitation')->getCollection();
$collection->addFieldToFilter(array('status', 'customer_id'), array(
array('status','eq'=>'new'),
array('customer_id', 'eq'=>'1234') ));
Now to see what this looks like you can always echo the query that this creates by using
echo $collection->getSelect()->__toString();
The following code can cause similar error:
using (var session = SessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
movie = session.Get<Movie>(movieId);
tx.Commit();
}
Assert.That(movie.Actors.Count == 1);
You can fix it simply:
using (var session = SessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
movie = session.Get<Movie>(movieId);
Assert.That(movie.Actors.Count == 1);
tx.Commit();
}
I was searching how to do something similar in WPF and I got this solution:
<ItemsControl ItemsSource="{Binding MyItems,Mode=OneWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton
Content="{Binding}"
Command="{Binding Path=DataContext.CustomCommand,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ItemsControl}} }"
CommandParameter="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
I hope this works for somebody else. I have a data context which is set automatically to the ItemsControls, and this data context has two properties: MyItems
-which is a collection-, and one command 'CustomCommand'. Because of the ItemTemplate
is using a DataTemplate
, the DataContext
of upper levels is not directly accessible. Then the workaround to get the DC of the parent is use a relative path and filter by ItemsControl
type.
After a lot of trial and error, followed by a stagnant period while I waited for an opportunity to speak with our server guys, I finally had a chance to discuss the problem with them and asked them if they wouldn't mind switching our Sharepoint authentication over to Kerberos.
To my surprise, they said this wouldn't be a problem and was in fact easy to do. They enabled Kerberos and I modified my app.config as follows:
<security mode="Transport">
<transport clientCredentialType="Windows" />
</security>
For reference, my full serviceModel entry in my app.config looks like this:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="TestServerReference" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2000000" maxBufferPoolSize="2000000" maxReceivedMessageSize="2000000"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://path/to/site/_vti_bin/Lists.asmx"
binding="basicHttpBinding" bindingConfiguration="TestServerReference"
contract="TestServerReference.ListsSoap" name="TestServerReference" />
</client>
</system.serviceModel>
After this, everything worked like a charm. I can now (finally!) utilize Sharepoint Web Services. So, if anyone else out there can't get their Sharepoint Web Services to work with NTLM, see if you can convince the sysadmins to switch over to Kerberos.
If you simply want to initialise a member field or property with the constructor parameter, in C# >= 3 you can do it very easier:
public static string GetAllItems<T>(...) where T : InterfaceOrBaseClass, new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(new T{ BaseMemberItem = listItem }); // No error, BaseMemberItem owns to InterfaceOrBaseClass.
}
...
}
This is the same thing Garry Shutler said, but I'd like to put an aditional note.
Of course you can use a property trick to do more stuff than just setting a field value. A property "set()" can trigger any processing needed to setup its related fields and any other need for the object itself, including a check to see if a full initialization is to take place before the object is used, simulating a full contruction (yes, it is an ugly workaround, but it overcomes M$'s new() limitation).
I can't be assure if it is a planned hole or an accidental side effect, but it works.
It is very funny how MS people adds new features to the language and seems to not do a full side effects analysis. The entire generic thing is a good evidence of this...
private String betweenComma(ArrayList<String> strings) {
String united = "";
for (String string : strings) {
united = united + "," + string;
}
return united.replaceFirst(",", "");
}
Try using a ConcurrentHashMap
instead of a plain HashMap
By the way, you can use next code in you event handler:
switch(e.EventType)
{
case SerialData.Chars:
{
// means you receives something
break;
}
case SerialData.Eof:
{
// means receiving ended
break;
}
}
Well, if you know where your user lives in the AD hierarchy (e.g. quite possibly in the "Users" container, if it's a small network), you could also bind to the user account directly, instead of searching for it.
DirectoryEntry deUser = new DirectoryEntry("LDAP://cn=John Doe,cn=Users,dc=yourdomain,dc=com");
if (deUser != null)
{
... do something with your user
}
And if you're on .NET 3.5 already, you could even use the vastly expanded System.DirectorySrevices.AccountManagement namespace with strongly typed classes for each of the most common AD objects:
// bind to your domain
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://dc=yourdomain,dc=com");
// find the user by identity (or many other ways)
UserPrincipal user = UserPrincipal.FindByIdentity(pc, "cn=John Doe");
There's loads of information out there on System.DirectoryServices.AccountManagement - check out this excellent article on MSDN by Joe Kaplan and Ethan Wilansky on the topic.
I know that this is a super-old post. Assuming that you are calling into your application, here is an idea that has worked for me:
If you don't need total control, you could use an update panel which would do this for you.
You could try:
List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.ToArray());
Not sure if .ToArray() is available for the collection. If you do use the code you posted, make sure you initialize the List with the number of existing elements:
List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.Count); // or .Length
This should do:
$chunk = "abc\tdef\tghi";
Here is a link to an article with more extensive examples.
Regarding the comment of Andrew Mairose - Although a fine solution, I would just like to add that this solution will not work on fixed size lists.
You could attempt doing like so:
Arrays.asList(new String[]{"a", "b", null, "c", " "})
.removeIf(item -> item == null || "".equals(item));
But you'll encounter an UnsupportedOperationException at java.util.AbstractList.remove
(since asList
returns a non-resizable List).
A different solution might be this:
List<String> collect =
Stream.of(new String[]{"a", "b", "c", null, ""})
.filter(item -> item != null && !"".equals(item))
.collect(Collectors.toList());
Which will produce a nice list of strings :-)
You shouldn't use both ngRoute
and UI-router
. Here's a sample code for UI-router:
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
_x000D_
$stateProvider_x000D_
.state('state1', {_x000D_
url: "/state1",_x000D_
templateUrl: "partials/state1.html",_x000D_
controller: 'YourCtrl'_x000D_
})_x000D_
_x000D_
.state('state2', {_x000D_
url: "/state2",_x000D_
templateUrl: "partials/state2.html",_x000D_
controller: 'YourOtherCtrl'_x000D_
});_x000D_
$urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?
You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router
Here nice is used in the meaning of an editor you like or find more user friendly.
The underlying problem is that Git by default uses an editor that is too unintuitive to use for most people: Vim. Now, don't get me wrong, I love Vim, and while you could set some time aside (like a month) to learn Vim and try to understand why some people think Vim is the greatest editor in existence, there is a quicker way of fixing this problem :-)
The fix is not to memorize cryptic commands, like in the accepted answer, but configuring Git to use an editor that you like and understand! It's really as simple as configuring either of these options
core.editor
(per project, or globally)VISUAL
or EDITOR
environment variable (this works for other programs as well)I'll cover the first option for a couple of popular editors, but GitHub has an excellent guide on this for many editors as well.
Straight from its docs, enter this in a terminal:
git config --global core.editor "atom --wait"
Git normally wait for the editor command to finish, but since Atom forks to a background process immediately, this won't work, unless you give it the --wait
option.
For the same reasons as in the Atom case, you need a special flag to signal to the process that it shouldn't fork to the background:
git config --global core.editor "subl -n -w"
There's no easy solution. Each way has their pros and cons . But the canonical way is using the first option: multipart/form-data
. As W3 recommendation guide says
The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
We aren't sending forms,really, but the implicit principle still applies. Using base64 as a binary representation, is incorrect because you're using the incorrect tool for accomplish your goal, in other hand, the second option forces your API clients to do more job in order to consume your API service. You should do the hard work in the server side in order to supply an easy-to-consume API. The first option is not easy to debug, but when you do it, it probably never changes.
Using multipart/form-data
you're sticked with the REST/http philosophy. You can view an answer to similar question here.
Another option if mixing the alternatives, you can use multipart/form-data but instead of send every value separate, you can send a value named payload with the json payload inside it. (I tried this approach using ASP.NET WebAPI 2 and works fine).
You could also do it via jQuery:
$('#x_Created').addClass(date);
This worked fine for me
int max = Convert.ToInt32(datatable_name.AsEnumerable()
.Max(row => row["column_Name"]));
https://gist.github.com/3118596
There is an implementation for JavaScript. It has functions to get k-combinations and all combinations of an array of any objects. Examples:
k_combinations([1,2,3], 2)
-> [[1,2], [1,3], [2,3]]
combinations([1,2,3])
-> [[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
In batch files, as in standard C programs, argument 0 contains the path to the currently executing script. You can use %~dp0
to get only the path portion of the 0th argument (which is the current script) - this path is always a fully qualified path.
You can also get the fully qualified path of your first argument by using %~f1
, but this gives a path according to the current working directory, which is obviously not what you want.
Personally, I often use the %~dp0%~1
idiom in my batch file, which interpret the first argument relative to the path of the executing batch. It does have a shortcoming though: it miserably fails if the first argument is fully-qualified.
If you need to support both relative and absolute paths, you can make use of Frédéric Ménez's solution: temporarily change the current working directory.
Here's an example that'll demonstrate each of these techniques:
@echo off
echo %%~dp0 is "%~dp0"
echo %%0 is "%0"
echo %%~dpnx0 is "%~dpnx0"
echo %%~f1 is "%~f1"
echo %%~dp0%%~1 is "%~dp0%~1"
rem Temporarily change the current working directory, to retrieve a full path
rem to the first parameter
pushd .
cd %~dp0
echo batch-relative %%~f1 is "%~f1"
popd
If you save this as c:\temp\example.bat and the run it from c:\Users\Public as
c:\Users\Public>\temp\example.bat ..\windows
...you'll observe the following output:
%~dp0 is "C:\temp\"
%0 is "\temp\example.bat"
%~dpnx0 is "C:\temp\example.bat"
%~f1 is "C:\Users\windows"
%~dp0%~1 is "C:\temp\..\windows"
batch-relative %~f1 is "C:\Windows"
the documentation for the set of modifiers allowed on a batch argument can be found here: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/call
One thing to note that you guys are over-complicating the problem just like a lot of other posts! All you need to do is create drawable selectors with whatever backgrounds you need and set them to actual items. I just spend two hours trying your solutions (all suggested on this page) and none of them worked. Not to mention that there are tons of errors that essentially slow your performance in those try/catch blocks you have.
Anyways here is a menu xml file:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/m1"
android:icon="@drawable/item1_selector"
/>
<item android:id="@+id/m2"
android:icon="@drawable/item2_selector"
/>
</menu>
Now in your item1_selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/item_highlighted" />
<item android:state_selected="true" android:drawable="@drawable/item_highlighted" />
<item android:state_focused="true" android:drawable="@drawable/item_nonhighlighted" />
<item android:drawable="@drawable/item_nonhighlighted" />
</selector>
Next time you decide to go to the supermarket through Canada try google maps!
before comparing the two or more strings first execute the following commands
alter session set NLS_COMP=LINGUISTIC;
alter session set NLS_SORT=BINARY_CI;
after those two statements executed then you may compare the strings and there will be case insensitive.for example you had two strings s1='Apple' and s2='apple', if yow want to compare the two strings before executing the above statements then those two strings will be treated as two different strings but when you compare the strings after the execution of the two alter statements then those two strings s1 and s2 will be treated as the same string
reasons for using those two statements
We need to set NLS_COMP=LINGUISTIC and NLS_SORT=BINARY_CI in order to use 10gR2 case insensitivity. Since these are session modifiable, it is not as simple as setting them in the initialization parameters. We can set them in the initialization parameters but they then only affect the server and not the client side.
To check if a string got any characters, ie. not null or whitespaces, check StringUtils.hasText
-method (if you are using Spring of course)
Example:
StringUtils.hasText(null) == false
StringUtils.hasText("") == false
StringUtils.hasText(" ") == false
StringUtils.hasText("12345") == true
StringUtils.hasText(" 12345 ") == true
This works well
If you want a TRIE implemented as a Python class, here is something I wrote after reading about them:
class Trie:
def __init__(self):
self.__final = False
self.__nodes = {}
def __repr__(self):
return 'Trie<len={}, final={}>'.format(len(self), self.__final)
def __getstate__(self):
return self.__final, self.__nodes
def __setstate__(self, state):
self.__final, self.__nodes = state
def __len__(self):
return len(self.__nodes)
def __bool__(self):
return self.__final
def __contains__(self, array):
try:
return self[array]
except KeyError:
return False
def __iter__(self):
yield self
for node in self.__nodes.values():
yield from node
def __getitem__(self, array):
return self.__get(array, False)
def create(self, array):
self.__get(array, True).__final = True
def read(self):
yield from self.__read([])
def update(self, array):
self[array].__final = True
def delete(self, array):
self[array].__final = False
def prune(self):
for key, value in tuple(self.__nodes.items()):
if not value.prune():
del self.__nodes[key]
if not len(self):
self.delete([])
return self
def __get(self, array, create):
if array:
head, *tail = array
if create and head not in self.__nodes:
self.__nodes[head] = Trie()
return self.__nodes[head].__get(tail, create)
return self
def __read(self, name):
if self.__final:
yield name
for key, value in self.__nodes.items():
yield from value.__read(name + [key])
You can use this
function LinkCheck(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
You need to wrap the table inside another element and set the height of that element. Example with inline css:
<div style="height: 500px; overflow: auto;">
<table>
</table>
</div>
Using the request module solved the issue.
// Include the request library for Node.js
var request = require('request');
// Basic Authentication credentials
var username = "vinod";
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(
{
url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
console.log(body); } );
DPI should not be stored in an bitmap image file, as most sources of data for bitmaps render it meaningless.
A bitmap image is stored as pixels. Pixels have no inherent size in any respect. It's only at render time - be it monitor, printer, or automated crossstitching machine - that DPI matters.
A 800x1000 pixel bitmap image, printed at 100 dpi, turns into a nice 8x10" photo. Printed at 200 dpi, the EXACT SAME bitmap image turns into a 4x5" photo.
Capture an image with a digital camera, and what does DPI mean? It's certainly not the size of the area focused onto the CCD imager - that depends on the distance, and with NASA returning images of galaxies that are 100,000 light years across, and 2 million light years apart, in the same field of view, what kind of DPI do you get from THAT information?
Don't fall victim to the idea of the DPI of a bitmap image - it's a mistake. A bitmap image has no physical dimensions (save for a few micrometers of storage space in RAM or hard drive). It's only a displayed image, or a printed image, that has a physical size in inches, or millimeters, or furlongs.
Add XML comments to the publicly visible types and members of course :)
///<Summary>
/// Gets the answer
///</Summary>
public int MyMethod()
{
return 42;
}
You need these <summary>
type comments on all members - these also show up in the intellisense popup menu.
The reason you get this warning is because you've set your project to output documentation xml file (in the project settings). This is useful for class libraries (.dll assemblies) which means users of your .dll are getting intellisense documentation for your API right there in visual studio.
I recommend you get yourself a copy of the GhostDoc Visual Studio AddIn.. Makes documenting much easier.
The problem was caused because the page was an intranet site, & IE had compatibility mode set to default for this. IE11 does support addEventListener()
What Mocha options are you using?
Maybe it is something to do with reporter (-R) or ui (-ui) being used?
console.log(msg);
works fine during my test runs, though sometimes mixed in a little goofy. Presumably due to the async nature of the test run.
Here are the options (mocha.opts) I'm using:
--require should
-R spec
--ui bdd
Hmm..just tested without any mocha.opts and console.log
still works.
The following solution seems to be a much shorter version for that:
<div id="imageDiv"></div>
In Javascript:
document.getElementById('imageDiv').innerHTML = '<img width="100" height="100" src="images/hydrangeas.jpg">';
I had the same problem because I changed the user from myself to someone else:
su
For some reason, after did the normal compiling I was not able to execute it (the same error message). Directly ssh to the other user account works.
I do not think that is possible you have to set all the values individualling (like the first example you provided.)
The Second example you gave, will only Initialize the last varuable to "" and not the others.
When you are using multidex , then try to extend your application class with MultiDexAppication instead of Application and override below method this required for Android below 5.0 (because 5.0 and above support to the multidex)
@Override
protected void attachBaseContext(Context base)
{
super.attachBaseContext(base);
MultiDex.install(BaseApplication.this);
}
and in dependencies add this
compile 'com.android.support:multidex:1.0.1'
array.length
will tell you how many elements are in an array
This is a helper function for mustacheJS, without pre-formatting the data and instead getting it during render.
var data = {
valueFromMap: function() {
return function(text, render) {
// "this" will be an object with map key property
// text will be color that we have between the mustache-tags
// in the template
// render is the function that mustache gives us
// still need to loop since we have no idea what the key is
// but there will only be one
for ( var key in this) {
if (this.hasOwnProperty(key)) {
return render(this[key][text]);
}
}
};
},
list: {
blueHorse: {
color: 'blue'
},
redHorse: {
color: 'red'
}
}
};
Template:
{{#list}}
{{#.}}<span>color: {{#valueFromMap}}color{{/valueFromMap}}</span> <br/>{{/.}}
{{/list}}
Outputs:
color: blue
color: red
(order might be random - it's a map) This might be useful if you know the map element that you want. Just watch out for falsy values.
Based on hints from other answers, this is probably the most robust way:
isEmulator = "goldfish".equals(Build.HARDWARE)
If you want to use a stable version of your preferred Laravel version of choice, use:
composer create-project --prefer-dist laravel/laravel project-name "5.5.*"
That will pick out the most recent or best update of version 5.5.* (5.5.28)
to search every column of every table for a particular value
This does not define how to match exactly.
Nor does it define what to return exactly.
Assuming:
regclass
) and the tuple ID (ctid
), because that's simplest.Here is a dead simple, fast and slightly dirty way:
CREATE OR REPLACE FUNCTION search_whole_db(_like_pattern text)
RETURNS TABLE(_tbl regclass, _ctid tid) AS
$func$
BEGIN
FOR _tbl IN
SELECT c.oid::regclass
FROM pg_class c
JOIN pg_namespace n ON n.oid = relnamespace
WHERE c.relkind = 'r' -- only tables
AND n.nspname !~ '^(pg_|information_schema)' -- exclude system schemas
ORDER BY n.nspname, c.relname
LOOP
RETURN QUERY EXECUTE format(
'SELECT $1, ctid FROM %s t WHERE t::text ~~ %L'
, _tbl, '%' || _like_pattern || '%')
USING _tbl;
END LOOP;
END
$func$ LANGUAGE plpgsql;
Call:
SELECT * FROM search_whole_db('mypattern');
Provide the search pattern without enclosing %
.
Why slightly dirty?
If separators and decorators for the row in text
representation can be part of the search pattern, there can be false positives:
,
by default()
"
\
may be added as escape charAnd the text representation of some columns may depend on local settings - but that ambiguity is inherent to the question, not to my solution.
Each qualifying row is returned once only, even when it matches multiple times (as opposed to other answers here).
This searches the whole DB except for system catalogs. Will typically take a long time to finish. You might want to restrict to certain schemas / tables (or even columns) like demonstrated in other answers. Or add notices and a progress indicator, also demonstrated in another answer.
The regclass
object identifier type is represented as table name, schema-qualified where necessary to disambiguate according to the current search_path
:
What is the ctid
?
You might want to escape characters with special meaning in the search pattern. See:
This is an example of using REG_EXTENDED. This regular expression
"^(-)?([0-9]+)((,|.)([0-9]+))?\n$"
Allows you to catch decimal numbers in Spanish system and international. :)
#include <regex.h>
#include <stdlib.h>
#include <stdio.h>
regex_t regex;
int reti;
char msgbuf[100];
int main(int argc, char const *argv[])
{
while(1){
fgets( msgbuf, 100, stdin );
reti = regcomp(®ex, "^(-)?([0-9]+)((,|.)([0-9]+))?\n$", REG_EXTENDED);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
/* Execute regular expression */
printf("%s\n", msgbuf);
reti = regexec(®ex, msgbuf, 0, NULL, 0);
if (!reti) {
puts("Match");
}
else if (reti == REG_NOMATCH) {
puts("No match");
}
else {
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
/* Free memory allocated to the pattern buffer by regcomp() */
regfree(®ex);
}
}
$(document).ready(function(){
$('#category').change(function(){
$("#app").fadeOut();
$.ajax({
type: "POST",
url: "themes/ajax.php",
data: "cat="+$(this).val(),
cache: false,
success: function(msg)
{
$('#app').fadeIn().html(msg);
$('#app').change(function(){
$("#store").fadeOut();
$.ajax({
type: "POST",
url: "themes/ajax.php",
data: "app="+$(this).val(),
cache: false,
success: function(ms)
{
$('#store').fadeIn().html(ms);
}
});// second ajAx
});// second on change
}// first ajAx sucess
});// firs ajAx
});// firs on change
});
What do you mean by impacts? Content will flow around a float. That's how they work.
If you want it to appear above your design, try setting:
z-index: 10;
position: absolute;
right: 0;
top: 0;
Use HashBytes
SELECT HashBytes('MD5', '[email protected]')
That will give you 0xF53BD08920E5D25809DF2563EF9C52B6
-
SELECT CONVERT(NVARCHAR(32),HashBytes('MD5', '[email protected]'),2)
That will give you F53BD08920E5D25809DF2563EF9C52B6
def copy_myfile_dirOne_to_dirSec(src, dest, ext):
if not os.path.exists(dest): # if dest dir is not there then we create here
os.makedirs(dest);
for item in os.listdir(src):
if item.endswith(ext):
s = os.path.join(src, item);
fd = open(s, 'r');
data = fd.read();
fd.close();
fname = str(item); #just taking file name to make this name file is destination dir
d = os.path.join(dest, fname);
fd = open(d, 'w');
fd.write(data);
fd.close();
print("Files are copyed successfully")
To find all configurations, you just write this command:
git config --list
In my local i run this command .
Md Masud@DESKTOP-3HTSDV8 MINGW64 ~
$ git config --list
core.symlinks=false
core.autocrlf=true
core.fscache=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
help.format=html
rebase.autosquash=true
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
credential.helper=manager
[email protected]
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
filter.lfs.clean=git-lfs clean -- %f
You could use a group function so that your query always returns a result. ie
MIN(ID_NMB_SRZ)
You cannot place checkbox inside select element but you can get the same functionality by using HTML, CSS and JavaScript. Here is a possible working solution. The explanation follows.
var expanded = false;_x000D_
_x000D_
function showCheckboxes() {_x000D_
var checkboxes = document.getElementById("checkboxes");_x000D_
if (!expanded) {_x000D_
checkboxes.style.display = "block";_x000D_
expanded = true;_x000D_
} else {_x000D_
checkboxes.style.display = "none";_x000D_
expanded = false;_x000D_
}_x000D_
}
_x000D_
.multiselect {_x000D_
width: 200px;_x000D_
}_x000D_
_x000D_
.selectBox {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.selectBox select {_x000D_
width: 100%;_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.overSelect {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
}_x000D_
_x000D_
#checkboxes {_x000D_
display: none;_x000D_
border: 1px #dadada solid;_x000D_
}_x000D_
_x000D_
#checkboxes label {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#checkboxes label:hover {_x000D_
background-color: #1e90ff;_x000D_
}
_x000D_
<form>_x000D_
<div class="multiselect">_x000D_
<div class="selectBox" onclick="showCheckboxes()">_x000D_
<select>_x000D_
<option>Select an option</option>_x000D_
</select>_x000D_
<div class="overSelect"></div>_x000D_
</div>_x000D_
<div id="checkboxes">_x000D_
<label for="one">_x000D_
<input type="checkbox" id="one" />First checkbox</label>_x000D_
<label for="two">_x000D_
<input type="checkbox" id="two" />Second checkbox</label>_x000D_
<label for="three">_x000D_
<input type="checkbox" id="three" />Third checkbox</label>_x000D_
</div>_x000D_
</div>_x000D_
</form>
_x000D_
At first we create a select element that shows text "Select an option", and empty element that covers (overlaps) the select element (<div class="overSelect">
). We do not want the user to click on the select element - it would show an empty options. To overlap the element with other element we use CSS position property with value relative | absolute.
To add the functionality we specify a JavaScript function that is called when the user clicks on the div that contains our select element (<div class="selectBox" onclick="showCheckboxes()">
).
We also create div that contains our checkboxes and style it using CSS. The above mentioned JavaScript function just changes <div id="checkboxes">
value of CSS display property from "none" to "block" and vice versa.
The solution was tested in the following browsers: Internet Explorer 10, Firefox 34, Chrome 39. The browser needs to have JavaScript enabled.
CSS positioning
How to overlay one div over another div
http://www.w3schools.com/css/css_positioning.asp
CSS display property
The format specifers matter: "%s" says that the next string is a narrow string ("ascii" and typically 8 bits per character). "%S" means wide char string. Mixing the two will give "undefined behaviour", which includes printing garbage, just one character or nothing.
One character is printed because wide chars are, for example, 16 bits wide, and the first byte is non-zero, followed by a zero byte -> end of string in narrow strings. This depends on byte-order, in a "big endian" machine, you'd get no string at all, because the first byte is zero, and the next byte contains a non-zero value.
billmanH's solution helped me but didn't work until i switched from:
n = data.loc[row,'json_column']
to:
n = data.iloc[[row]]['json_column']
here's the rest of it, converting to a dictionary is helpful for working with json data.
import json
for row in range(len(data)):
n = data.iloc[[row]]['json_column'].item()
jsonDict = json.loads(n)
if ('mykey' in jsonDict):
display(jsonDict['mykey'])
Simple way is that you have "Collections" in Java. You just need to call it and use "reverse()" method of it.
Example usage:
ArrayList<Integer> yourArrayList = new ArrayList<>();
yourArrayList.add(1);
yourArrayList.add(2);
yourArrayList.add(3);
//yourArrayList is: 1,2,3
Collections.reverse(yourArrayList);
// Now, yourArrayList is: 3,2,1
For more question: @canerkaseler
Here is code to get line number and column position
function getLineNumber(tArea) {
return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}
function getCursorPos() {
var me = $("textarea[name='documenttext']")[0];
var el = $(me).get(0);
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
var ret = pos - prevLine(me);
alert(ret);
return ret;
}
function prevLine(me) {
var lineArr = me.value.substr(0, me.selectionStart).split("\n");
var numChars = 0;
for (var i = 0; i < lineArr.length-1; i++) {
numChars += lineArr[i].length+1;
}
return numChars;
}
tArea is the text area DOM element
Install PIL(Python Image Library) :
then:
from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();
Returning null is usually the best idea if you intend to indicate that no data is available.
An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.
Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.
var is used like public .if a varable is declared like this in a class var $a; if means its scope is public for the class. in simplea words var ~public
var $a;
public
im compiling my program in gcc in GNU/Linux and mingw in win 7 and win xp and worked good
you can use my program and to create a 80 GB file just change the line 33 to
makeFile("Text.txt",1024,8192000);
when exit the program the file will be destroyed then check the file when it is running
to have the program that you want just change the program
firt one is the windows program and the second is for GNU/Linux
First create a mapper :
import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();
As Array:
MyClass[] myObjects = mapper.readValue(json, MyClass[].class);
As List:
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
Another way to specify the List type:
List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
This thread has some great tips. However....
@GirishB's answer isn't correct - sorry. Jartender's is best.
Also, every post in here seems to assume you're logging in to the Linux guest as root, except for @tomoguisuru. Yuck! Don't use root, use a separate user account and "sudo" when you need root privileges. Then this user (or any other user who needs the shared folder) should have membership in the vboxsf group, and @tomoguisuru's command is perfect, even terser than what I use.
Forget running mount yourself. Set up the shared folder to auto mount and you'll find the shared folder - it's under /media in my OEL (RH and Centos probably the same). If it's not there, just run "mount" with no arguments and look for the mounted directory of type vboxsf.
For Bootstrap 4
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control" placeholder="Start"/>_x000D_
<div class="input-group-prepend">_x000D_
<span class="input-group-text" id="">-</span>_x000D_
</div>_x000D_
<input type="text" class="form-control" placeholder="End"/>_x000D_
</div>
_x000D_
You can use the return
statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success.
If no return
is explicitly set, then the stored procedure returns zero.
CREATE PROCEDURE GetImmediateManager
@employeeID INT,
@managerID INT OUTPUT
AS
BEGIN
SELECT @managerID = ManagerID
FROM HumanResources.Employee
WHERE EmployeeID = @employeeID
if @@rowcount = 0 -- manager not found?
return 1;
END
And you call it this way:
DECLARE @return_status int;
DECLARE @managerID int;
EXEC @return_status = GetImmediateManager 2, @managerID output;
if @return_status = 1
print N'Immediate manager not found!';
else
print N'ManagerID is ' + @managerID;
go
You should use the return value for status codes only. To return data, you should use output parameters.
If you want to return a dataset, then use an output parameter of type cursor
.
z
means (un)z_ip.x
means ex_tract files from the archive.v
means print the filenames v_erbosely.f
means the following argument is a f_ilename.For more details, see tar
's man page.
Specify the path starting from src as below:
src/main/resources/myprop.proper
The jackson API has changed:
new ObjectMapper()
.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(new HashMap<String, Object>());
I found this page with detailed instructions to upgrade Anaconda to a major newer version of Python (from Anaconda 4.0+). First,
conda update conda
conda remove argcomplete conda-manager
I also had to conda remove
some packages not on the official list:
Depending on packages installed on your system, you may get additional UnsatisfiableError
errors - simply add those packages to the remove list. Next, install the version of Python,
conda install python==3.6
which takes a while, after which a message indicated to conda install anaconda-client
, so I did
conda install anaconda-client
which said it's already there. Finally, following the directions,
conda update anaconda
I did this in the Windows 10 command prompt, but things should be similar in Mac OS X.
from a Debug Keystore we can get the SHA1 value in Eclipse
. Accessing from the menu:
Window
-> Preferences
-> Android
-> Build
but it doesn´t work for a production Keystore
.
So, to get the SHA1 value from a production Keystore go to:
Android Tools
-> Export Signed Application Package
. Follow the process for signing your apk and the SHA1 will showed as a certificate.
I tried this:
long now = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
new Date().getTime();
}
long result = System.currentTimeMillis() - now;
System.out.println("Date(): " + result);
now = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
System.currentTimeMillis();
}
result = System.currentTimeMillis() - now;
System.out.println("currentTimeMillis(): " + result);
And result was:
Date(): 199
currentTimeMillis(): 3
you can include @ in a 'scriptBlock' like this:
@(
echo don't echoed
hostname
)
echo echoed
and especially do not do that :)
for %%a in ("@") do %%~aecho %%~a
I was experiencing this issue due to the misconfiguration of my Apple Worldwide Developer Relations Certification Authority certificate.
I resolved issue by switching from "Alway Trust" to "Use System Defaults"
Step by Step:
Here's something I came up with after applying a few principles other SO posts, including Aaron's link:
AnnotationPin *myAnnotation = (AnnotationPin *)annotation;
self = [super initWithAnnotation:myAnnotation reuseIdentifier:reuseIdentifier];
self.backgroundColor = [UIColor greenColor];
self.frame = CGRectMake(0,0,30,30);
imageView = [[UIImageView alloc] initWithImage:myAnnotation.THEIMAGE];
imageView.frame = CGRectMake(3,3,20,20);
imageView.layer.masksToBounds = NO;
[self addSubview:imageView];
[imageView release];
CGSize titleSize = [myAnnotation.THETEXT sizeWithFont:[UIFont systemFontOfSize:12]];
CGRect newFrame = self.frame;
newFrame.size.height = titleSize.height + 12;
newFrame.size.width = titleSize.width + 32;
self.frame = newFrame;
self.layer.borderColor = [UIColor colorWithRed:0 green:.3 blue:0 alpha:1.0f].CGColor;
self.layer.borderWidth = 3.0;
UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(26,5,newFrame.size.width-32,newFrame.size.height-12)];
infoLabel.text = myAnnotation.title;
infoLabel.backgroundColor = [UIColor clearColor];
infoLabel.textColor = [UIColor blackColor];
infoLabel.textAlignment = UITextAlignmentCenter;
infoLabel.font = [UIFont systemFontOfSize:12];
[self addSubview:infoLabel];
[infoLabel release];
In this example, I'm adding a custom pin to a MKAnnotation class that resizes a UILabel according to the text size. It also adds an image on the left side of the view, so you see some of the code managing the proper spacing to handle the image and padding.
The key is to use CGSize titleSize = [myAnnotation.THETEXT sizeWithFont:[UIFont systemFontOfSize:12]];
and then redefine the view's dimensions. You can apply this logic to any view.
Although Aaron's answer works for some, it didn't work for me. This is a far more detailed explanation that you should try immediately before going anywhere else if you want a more dynamic view with an image and resizable UILabel. I already did all the work for you!!
try this....
public void buildPushNotification(Context ctx, String content, int icon, CharSequence text, boolean silent) {
Intent intent = new Intent(ctx, Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 1410, intent, PendingIntent.FLAG_ONE_SHOT);
Bitmap bm = BitmapFactory.decodeResource(ctx.getResources(), //large drawable);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
.setSmallIcon(icon)
.setLargeIcon(bm)
.setContentTitle(content)
.setContentText(text)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
if(!silent)
notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1410, notificationBuilder.build());
}
and in onMessageReceived, call it
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("Msg", "Message received [" + remoteMessage.getNotification().getBody() + "]");
buildPushNotification(/*your param*/);
}
or follow KongJing, Is also correct as he says, but you can use a Firebase Console.
Your problem may have been due to a deficiency in an earlier version of Swift or of the Xcode Beta. Working with Xcode Version 6.0 (6A279r) on August 21, 2014, your code works as expected with this output:
column: 0 row: 0 value:1.0 column: 0 row: 1 value:4.0 column: 0 row: 2 value:7.0 column: 1 row: 0 value:2.0 column: 1 row: 1 value:5.0 column: 1 row: 2 value:8.0 column: 2 row: 0 value:3.0 column: 2 row: 1 value:6.0 column: 2 row: 2 value:9.0
I just copied and pasted your code into a Swift playground and defined two constants:
let NumColumns = 3, NumRows = 3
From the documentation on http://curl.haxx.se/docs/httpscripting.html :
HTTP Authentication
curl --user name:password http://www.example.com
Put a file to a HTTP server with curl:
curl --upload-file uploadfile http://www.example.com/receive.cgi
Send post data with curl:
curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi
Charles is written in Java and runs on Macs. It's not free though.
You can point your Mac at your Windows+Fiddler machine: http://www.fiddler2.com/fiddler/help/hookup.asp#Q-NonWindows
And as of 2013, there's an Alpha download of Fiddler for the Mono Framework, which runs on Mac and Linux. Also, the very latest version of Fiddler can import .PCAP files captured from WireShark or other tools run on the Mac.
You do not need it.
If your action has the HttpPost
attribute, then you do not need to bother with setting the JsonRequestBehavior
and use the overload without it. There is an overload for each method without the JsonRequestBehavior
enum. Here they are:
Without JsonRequestBehavior
protected internal JsonResult Json(object data);
protected internal JsonResult Json(object data, string contentType);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding);
With JsonRequestBehavior
protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
protected internal JsonResult Json(object data, string contentType,
JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType,
Encoding contentEncoding, JsonRequestBehavior behavior);
if ([ $NUM1 == 1 ] || [ $NUM2 == 1 ]) && [ -z "$STR" ]
then
echo STR is empty but should have a value.
fi
fetch('http://localhost/foo.txt')
.then(response => response.text())
.then((data) => {
console.log(data)
})
I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).
Solution is: First Update ADT to 22.0.4(Latest version) and then Update SDK Tool to 22.0.4(Latest Version)
The above link says,
ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so
What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).
How to Update your ADT to Latest Version
Help
Install New Software
---> Add
Add Repository
write the Name: ADT
(or whatever you want)https://dl-ssl.google.com/android/eclipse/
Developer Tools
and NDK Plugins
Developer Tool
onlyNext
Finish
If you are using BookId as an combined primary key, then remember to change your interface from:
public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {
to:
public interface QueuedBookRepo extends JpaRepository<QueuedBook, BookId> {
And change the annotation @Embedded to @EmbeddedId, in your QueuedBook class like this:
public class QueuedBook implements Serializable {
@EmbeddedId
@NotNull
private BookId bookId;
...
Actually I just found out that there is even one more way of getting a country code, using the getSimCountryIso() method of TelephoneManager
:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
Since it is the sim code it also should not change when traveling to other countries.
It worked like a champ, after bit modification to your code
# initialization
app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app, resources={r"/foo": {"origins": "http://localhost:port"}})
@app.route('/foo', methods=['POST'])
@cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
def foo():
return request.json['inputVar']
if __name__ == '__main__':
app.run()
I replaced * by localhost. Since as I read in many blogs and posts, you should allow access for specific domain
The most Pythonic idiom is to clearly document what the function expects and then just try to use whatever gets passed to your function and either let exceptions propagate or just catch attribute errors and raise a TypeError
instead. Type-checking should be avoided as much as possible as it goes against duck-typing. Value testing can be OK – depending on the context.
The only place where validation really makes sense is at system or subsystem entry point, such as web forms, command line arguments, etc. Everywhere else, as long as your functions are properly documented, it's the caller's responsibility to pass appropriate arguments.
You are asking the wrong question. In databases is not the operator performance that matters, is always the SARGability of the expression, and the coverability of the overall query. Performance of the operator itself is largely irrelevant.
So, how do LIKE
and =
compare in terms of SARGability? LIKE
, when used with an expression that does not start with a constant (eg. when used LIKE '%something'
) is by definition non-SARGabale. But does that make =
or LIKE 'something%'
SARGable? No. As with any question about SQL performance the answer does not lie with the query of the text, but with the schema deployed. These expression may be SARGable if an index exists to satisfy them.
So, truth be told, there are small differences between =
and LIKE
. But asking whether one operator or other operator is 'faster' in SQL is like asking 'What goes faster, a red car or a blue car?'. You should eb asking questions about the engine size and vechicle weight, not about the color... To approach questions about optimizing relational tables, the place to look is your indexes and your expressions in the WHERE clause (and other clauses, but it usually starts with the WHERE).
Use element .innerHTML=
which is quite fast in modern browsers
document.body.innerHTML = "<canvas width=500 height=150 id='CursorLayer'>";
// TEST
var ctx = CursorLayer.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 100, 50, 50);
_x000D_
canvas { border: 1px solid black }
_x000D_
This error tells you everything:
undefined reference toHash::insert(int, char)
You're not linking with the implementations of functions defined in Hash.h
. Don't you have a Hash.cpp
to also compile and link?
First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:
ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");
Then inject the mock into m_orderSvc and call your method.
m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
Finally, verify that the mock was called properly:
verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");
Use jline3:
Example:
Terminal terminal = TerminalBuilder.builder()
.jna(true)
.system(true)
.build();
// raw mode means we get keypresses rather than line buffered input
terminal.enterRawMode();
reader = terminal .reader();
...
int read = reader.read();
....
reader.close();
terminal.close();
int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");
This is a jQuery plugin which sets the equal height for all elements on the same row(by checking the element's offset.top). So if your jQuery array contains elements from more than one row(different offset.top), each row will have a separated height, based on element with maximum height on that row.
jQuery.fn.setEqualHeight = function(){
var $elements = [], max_height = [];
jQuery(this).css( 'min-height', 0 );
// GROUP ELEMENTS WHICH ARE ON THE SAME ROW
this.each(function(index, el){
var offset_top = jQuery(el).offset().top;
var el_height = jQuery(el).css('height');
if( typeof $elements[offset_top] == "undefined" ){
$elements[offset_top] = jQuery();
max_height[offset_top] = 0;
}
$elements[offset_top] = $elements[offset_top].add( jQuery(el) );
if( parseInt(el_height) > parseInt(max_height[offset_top]) )
max_height[offset_top] = el_height;
});
// CHANGE ELEMENTS HEIGHT
for( var offset_top in $elements ){
if( jQuery($elements[offset_top]).length > 1 )
jQuery($elements[offset_top]).css( 'min-height', max_height[offset_top] );
}
};
Within the definition of the appender, I believe you can do something like this:
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="INFO"/>
<param name="LevelMax" value="INFO"/>
</filter>
...
</appender>
If we want only hh:mm:ss, we can use a function like that:
//param: duration in milliseconds
MillisecondsToTime: function(duration) {
var seconds = parseInt((duration/1000)%60)
, minutes = parseInt((duration/(1000*60))%60)
, hours = parseInt((duration/(1000*60*60))%24)
, days = parseInt(duration/(1000*60*60*24));
var hoursDays = parseInt(days*24);
hours += hoursDays;
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
}
Just use the atol()
function:
#include <stdio.h>
#include <stdlib.h>
int main()
{
const char *c = "5";
int d = atol(c);
printf("%d\n", d);
}
I like Brian R. Bondy's answer. I just wanted to add that Wikipedia provides a clear description of REST. The article distinguishes it from SOAP.
REST is an exchange of state information, done as simply as possible.
SOAP is a message protocol that uses XML.
One of the main reasons that many people have moved from SOAP to REST is that the WS-* (called WS splat) standards associated with SOAP based web services are EXTREMELY complicated. See wikipedia for a list of the specifications. Each of these specifications is very complicated.
EDIT: for some reason the links are not displaying correctly. REST = http://en.wikipedia.org/wiki/REST
WS-* = http://en.wikipedia.org/wiki/WS-*
Here you go :
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("first_column_name");
String str1 = rs.getString("second_column_name");
}
con.close();
In rs.getInt
or rs.getString
you can pass column_id
starting from 1
, but i prefer to pass column_name
as its more informative as you don't have to look at database table
for which index
is what column
.
UPDATE : rs.next
boolean next() throws SQLException
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If the result set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will return false or throw an SQLException on a subsequent call to next.
If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.
Returns: true if the new current row is valid; false if there are no more rows Throws: SQLException - if a database access error occurs or this method is called on a closed result set
you should use this code:
$json = json_encode(array_map('utf8_encode', $arr))
array_map function converts special characters in UTF8 standard
Per the Javadoc:
Returns the value of a request parameter as a String, or null if the parameter does not exist.
Do note that it is possible to submit an empty parameter - such that the parameter exists, but has no value. For example, I could include &log=&somethingElse
into the URL to enable logging, without needing to specify &log=true
. In this case, the value will be an empty String (""
).
You can create a .a
file using the ar
utility, like so:
ar crf lib/libHeader.a header.o
lib
is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a
in the directory lib
. So, in your current directory, do:
mkdir lib
Then run the above ar
command.
When linking all libraries, you can do it like so:
g++ test.o -L./lib -lHeader -o test
The -L
flag will get g++
to add the lib/
directory to the path. This way, g++
knows what directory to search when looking for libHeader
. -llibHeader
flags the specific library to link.
where test.o is created like so:
g++ -c test.cpp -o test.o
Queue
is an interface in java, you could not do that.
try:
Queue<Integer> Q = new LinkedList<Integer>();
LocalDate.parse(
"19/05/2009" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
)
The other Answers with java.util.Date
, java.sql.Date
, and SimpleDateFormat
are now outdated.
LocalDate
The modern way to do date-time is work with the java.time classes, specifically LocalDate
. The LocalDate
class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter
To parse, or generate, a String representing a date-time value, use the DateTimeFormatter
class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "19/05/2009" , f );
Do not conflate a date-time object with a String representing its value. A date-time object has no format, while a String does. A date-time object, such as LocalDate
, can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects.
You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing.
DateTimeFormatter f =
DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f );
Dump to console.
System.out.println( "ld: " + ld + " | output: " + output );
ld: 2009-05-19 | output: mardi 19 mai 2009
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.
Under Project->Properties->Debug, you should see a box for Command line arguments (This is in C# 2010, but it should basically be the same place)
Consider using SCSS. It's full compatible with CSS syntax, so a valid CSS file is also a valid SCSS file. This makes migration easy, just change the suffix. It has numerous enhancements, the most useful being variables and nested selectors.
You need to run it through a pre-processor to convert it to CSS before shipping it to the client.
I've been a hardcore CSS developer for many years now, but since forcing myself to do a project in SCSS, I now won't use anything else.
Some refinements to answer above. To remove more than one char you add multiple question marks. For example, to remove last two chars from variable $SRC_IP_MSG, you can use:
SRC_IP_MSG=${SRC_IP_MSG%??}
Another option here is to have your iPhone connect via a proxy. Here's an example of how to do it with Fiddler (it's very easy):
http://conceptdev.blogspot.com/2009/01/monitoring-iphone-web-traffic-with.html
In that case any dns lookups your iPhone does will use the hosts file of the machine Fiddler is running on. Note, though, that you must use a name that will be resolved via DNS. example.local
, for instance, will not work. example.xyz
or example.dev
will.
mime-types starting with x-
are not standardized. In case of javascript it's kind of outdated.
Additional the second code snippet
<?Header('Content-Type: text/javascript');?>
requires short_open_tags
to be enabled. you should avoid it.
<?php Header('Content-Type: text/javascript');?>
However, the completely correct mime-type for javascript is
application/javascript
http://www.iana.org/assignments/media-types/application/index.html
You can use Spacers if all you want is a little bit of spacing between items in a row. The example below centers 2 Text widgets within a row with some spacing between them.
Spacer creates an adjustable, empty spacer that can be used to tune the spacing between widgets in a Flex
container, like Row
or Column
.
In a row
, if we want to put space between two widgets such that it occupies all remaining space.
widget = Row (
children: <Widget>[
Spacer(flex: 20),
Text(
"Item #1",
),
Spacer(), // Defaults to flex: 1
Text(
"Item #2",
),
Spacer(flex: 20),
]
);
private boolean removeFragFromBackStack() {
try {
FragmentManager manager = getSupportFragmentManager();
List<Fragment> fragsList = manager.getFragments();
if (fragsList.size() == 0) {
return true;
}
manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);
The method takes a regular expression, not a string, and the dot has a special meaning in regular expressions. Escape it like so split("\\.")
. You need a double backslash, the second one escapes the first.
$('#test').click(function() {_x000D_
var todayDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("08.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + todayDate.diff(endDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
In SQL Server 2008:
DECLARE @PAGE INTEGER = 2
DECLARE @TAKE INTEGER = 50
SELECT [t1].*
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY [t0].[COLUMNORDER] DESC) AS [ROW_NUMBER], [t0].*
FROM [dbo].[TABLA] AS [t0]
WHERE ([t0].[COLUMNS_CONDITIONS] = 1)
) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN ((@PAGE*@TAKE) - (@TAKE-1)) AND (@PAGE*@TAKE)
ORDER BY [t1].[ROW_NUMBER]
In t0 are all records In t1 are only those corresponding to that page
Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests
response header, indicating that the browser supports it (and in fact prefers it).
It took me 30mins of Googling, but I finally found it buried in the W3 spec.
The confusion comes because the header in the spec was HTTPS: 1
, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:
"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
— Mike West, in Chrome Issue 501842
Their fix was to rename it to Upgrade-Insecure-Requests: 1
, and the spec has since been updated to match.
Anyway, here is the explanation from the W3 spec (as it appeared at the time)...
The
HTTPS
HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide....
When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.
When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a
Strict-Transport-Security
header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].
There are a lot of answers here varying by version, so I thought I'd confirm and expound upon Julien Le Coupanec's answer above from October 2018 when using the Vue CLI. In the most recent version of Vue.js as of this post - [email protected] - the outlined steps below made the most sense to me after looking through some of the myriad answers in this post. The Vue.js documentation references pieces of this puzzle, but isn't quite as explicit.
package.json
file in the root directory of the Vue.js project.package.json
file.Upon finding the following reference to "port", edit the serve
script element to reflect the desired port, using the same syntax as shown below:
"scripts": {
"serve": "vue-cli-service serve --port 8000",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
}
Make sure to re-start the npm
server to avoid unnecessary insanity.
The documentation shows that one can effectively get the same result by adding --port 8080
to the end of the npm run serve
command like so: npm run serve --port 8080
. I preferred editing the package.json
directly to avoid extra typing, but editing npm run serve --port 1234
inline may come in handy for some.
As you should know by now, purists say it's forbiden to run ordered tests. That might be true for unit tests. MSTest and other Unit Test frameworks are used to run pure unit test but also UI tests, full integration tests, you name it. Maybe we shouldn't call them Unit Test frameworks, or maybe we should and use them according to our needs. That's what most people do anyway.
I'm running VS2015 and I MUST run tests in a given order because I'm running UI tests (Selenium).
Priority - Doesn't do anything at all This attribute is not used by the test system. It is provided to the user for custom purposes.
orderedtest - it works but I don't recommend it because:
Other suggestions in this thread are interesting but you loose the ability to follow the test progress on Test Explorer.
You are left with the solution that purist will advise against, but in fact is the solution that works: sort by declaration order.
The MSTest executor uses an interop that manages to get the declaration order and this trick will work until Microsoft changes the test executor code.
This means the test method that is declared in the first place executes before the one that is declared in second place, etc.
To make your life easier, the declaration order should match the alphabetical order that is is shown in the Test Explorer.
I strongly suggest some old and tested rules:
VERY IMPORTANT
In order to execute the tests by the declaration order, you must use Run All in the Test Explorer.
Say you have 3 test classes (in my case tests for Chrome, Firefox and Edge). If you select a given class and right click Run Selected Tests it usually starts by executing the method declared in the last place.
Again, as I said before, declared order and listed order should match or else you'll in big trouble in no time.
I had a similar problem and solved it this way.
My working directory is a general script folder and serveral particular script folder in same root, i need to call particular script folder (which call general script with the parameter of the particular problem). So working directory is like this
\Nico\Scripts\Script1.ps1
\Script2.ps1
\Problem1\Solution1.ps1
\ParameterForSolution1.config
\Problem2\Solution2.ps1
\ParameterForSolution2.config
Solutions1 and Solutions2 call the PS1 in Scripts folder loading the parameter stored in ParameterForSolution. So in powershell ISE i run this command
.\Nico\Problem1\Solution1.PS1
And the code inside Solution1.PS1 is:
# This is the path where my script is running
$path = split-path -parent $MyInvocation.MyCommand.Definition
# Change to root dir
cd "$path\..\.."
$script = ".\Script\Script1.PS1"
$parametro = "Problem1\ParameterForSolution1.config"
# Another set of parameter Script1.PS1 can receive for debuggin porpuose
$parametro +=' -verbose'
Invoke-Expression "$script $parametro"
When creating AVD,
Now, after creating the AVD, you should see the google play icon .
Starting with PHP 5.6, you can define constant arrays using const
keyword like below
const DEFAULT_ROLES = ['test', 'development', 'team'];
and different elements can be accessed as below:
echo DEFAULT_ROLES[1];
....
Starting with PHP 7, constant arrays can be defined using define
as below:
define('DEFAULT_ROLES', [
'test',
'development',
'team'
]);
and different elements can be accessed same way as before.
If you want to display more column values without an aggregation function use GROUPING SETS
instead of ROLLUP
:
SELECT
Type = ISNULL(Type, 'Total'),
SomeIntColumn = ISNULL(SomeIntColumn, 0),
TotalSales = SUM(TotalSales)
FROM atable
GROUP BY GROUPING SETS ((Type, SomeIntColumn ), ())
ORDER BY SomeIntColumn --Displays summary row as the first row in query result
you need to avoid spaces in the AVD name. & Select the "Skin" option.
Some controls, like Button in System.Windows.Forms, have a "PerformClick" method to do just that.
Check out the Magick++ API to ImageMagick.
For a one time change you can do this:
export EMAIL='[email protected]'; mutt -s "Elvis is dead" [email protected]
Firt add a reference to System.web
, if you don't have. Do that in the References folder.
You can then use Hosting.HostingEnvironment.MapPath(path);
For
throw new Exception('test exception');
I got 500 (but didn't see anything in the browser), until I put
php_flag display_errors on
in my .htaccess (just for a subfolder). There are also more detailed settings, see Enabling error display in php via htaccess only
Check this out : readdir()
This bit of code should list all entries in a certain directory:
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}
Edit: miah's solution is much more elegant than mine, you should use his solution instead.
All good answers...From the validation perspective, I also noticed that MaxLength gets validated at the server side only, while StringLength gets validated at client side too.
Just add this extension:
extension NSDate {
var stringValue: String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yourDateFormat"
return formatter.stringFromDate(self)
}
}
Split Method
data = input_string
df = pd.DataFrame([x.split(';') for x in data.split('\n')])
print(df)
std::max_element
takes two iterators delimiting a sequence and returns an iterator pointing to the maximal element in that sequence. You can additionally pass a predicate to the function that defines the ordering of elements.
Beginning with Java 7, you can use the following idiom:
String someString = "...";
InputStream is = new ByteArrayInputStream( someString.getBytes(StandardCharsets.UTF_8) );
var i=0,length=2;
for(i; i<=length;i++)
{
$('#footer-div'+[i]).append($('<div class="ui-footer ui-bar-b ui-footer-fixed slideup" data-theme="b" data-position="fixed" data-role="footer" role="contentinfo" ><h3 class="ui-title" role="heading" aria-level="1">Advertisement </h3></div>'));
}
You are getting close!
# Find all of the text between paragraph tags and strip out the html
page = soup.find('p').getText()
Using find (as you've noticed) stops after finding one result. You need find_all if you want all the paragraphs. If the pages are formatted consistently ( just looked over one), you could also use something like
soup.find('div',{'id':'ctl00_PlaceHolderMain_RichHtmlField1__ControlWrapper_RichHtmlField'})
to zero in on the body of the article.
It depends on the semantic of the primary key. If it's just autoincrement, then use something like:
insert into table1 (all columns except pk)
select all_columns_except_pk
from table2;
If PK means something, you need to find a way to determine which record should have priority. You could create a select query to find duplicates first (see answer by cpitis). Then eliminate the ones you don't want to keep and use the above insert to add records that remain.
Verify the length
property of the array to be greater than 0
:
<p ng-if="post.capabilities.items.length > 0">
<strong>Topics</strong>:
<span ng-repeat="topic in post.capabilities.items">
{{topic.name}}
</span>
</p>
Arrays (objects) in JavaScript are truthy values, so your initial verification <p ng-if="post.capabilities.items">
evaluates always to true
, even if the array is empty.
this is my xml, dynamic component to align right, in my case i use 3 button
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkinInputCodeMember">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="7"
android:orientation="vertical" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/bttn_extends"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textColor="@color/colorAccent"
android:text="3"/>
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/bttn_checkout"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textColor="@color/colorAccent"
android:text="2"/>
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/checkinButtonScanQrCodeMember"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textColor="@color/colorAccent"
android:text="1"/>
</LinearLayout>
and the result
you can hide the right first button with change visibility GONE, and this my code
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkinInputCodeMember">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="7"
android:orientation="vertical" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/bttn_extends"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textColor="@color/colorAccent"
android:text="3"/>
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/bttn_checkout"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textColor="@color/colorAccent"
android:text="2"/>
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/checkinButtonScanQrCodeMember"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="1"
android:textColor="@color/colorAccent"
**android:visibility="gone"**/>
</LinearLayout>
still align right, after visibility gone first right component
That also happened to me on a recreated directory, the directory is the same but to make it work again just run:
cd .
Try this:
b = [ entry.split(',') for entry in a ]
b = [ b[i] if i % 3 == 0 else int(b[i]) for i in xrange(0, len(b)) ]
maybe this will help you out:
or this page:
www.scala-lang.org/node/6372
Check this reference link:
Give Safe User Permission To Use Port 80
Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like
http://ip:port/
Unfortunately, unless you sign on as root, you’ll normally have to use a URL like
http://ip:port
- where port number > 1024.A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:
sudo apt-get install libcap2-bin sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``
Now, when you tell a Node application that you want it to run on port 80, it will not complain.
You should really use the pip tool.
Use pip install -e .
to install your package in development mode. This is a very good practice, recommended by pytest (see their good practices documentation, where you can also find two project layouts to follow).
We can use Stack and push "i" into the stack every time we encounter the condition "arr[i]==value"
Check this:
static void getindex(int arr[], int value)
{
Stack<Integer>st= new Stack<Integer>();
int n= arr.length;
for(int i=n-1; i>=0 ;i--)
{
if(arr[i]==value)
{
st.push(i);
}
}
while(!st.isEmpty())
{
System.out.println(st.peek()+" ");
st.pop();
}
}
This one-liner works for me:
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
CredentialCache.DefaultNetWorkCredentials
is the proxy settings set in Internet Explorer.
WebRequest.DefaultWebProxy.Credentials
is used for all internet connectivity in the application.
Your main
doesn't know about writeFile()
and can't call it.
Move writefile
to be before main
, or declare a function prototype int writeFile();
before main
.
See this example: http://www.p2e.dk/diverse/detectPaste.htm
It essentialy tracks every change with oninput event and then checks if it’s a paste by string comparison. Oh, and in IE there’s an onpaste event. So:
$ (something).bind ("input paste", function (e) {
// check for paste as in example above and
// do something
})
Extending a bit to "Appending a list of strings to a list of strings":
import numpy as np
lst1 = ['a','b','c','d','e']
lst2 = ['1','2','3','4','5']
at = np.full(fill_value='@',shape=len(lst1),dtype=object) #optional third list
result = np.array(lst1,dtype=object)+at+np.array(lst2,dtype=object)
Result:
array(['a@1', 'b@2', 'c@3', 'd@4', 'e@5'], dtype=object)
dtype odject may be further converted str
aforementioned solutions did not help me, I could solve it by re-installing the Tomcat server which took few seconds.
This is all a bit roundabout..
I've used the glyphs like this
</div>
<div class="span2">
<span class="glyphicons thumbs_up"><i class="green"></i></span>
</div>
<div class="span2">
<span class="glyphicons thumbs_down"><i class="red"></i></span>
</div>
and to affect the color, i included a bit of css at the head like this
<style>
i.green:before {
color: green;
}
i.red:before {
color: red;
}
</style>
Voila, green and red thumbs.
As per your requirement, Thread.Sleep
is perfectly fine to use because you are not sure when the data will be available so you might need to wait for the data to become available. I have slightly changed the logic of your function this might help you little further.
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
int bytes = 0;
do
{
bytes = 0;
while (!stm.DataAvailable)
Thread.Sleep(20); // some delay
bytes = stm.Read(resp, 0, resp.Length);
memStream.Write(resp, 0, bytes);
}
while (bytes > 0);
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
Hope this helps!
For single line comment you can use Ctrl+/ and for multiple line comment you can use Ctrl + Shift + / after selecting the lines you want to comment in java editor.
On Mac/OS X you can use ? + / to comment out single lines or selected blocks.
You can use groupingBy feature of Java 8 for your use case.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
List<String> animals = new ArrayList<>();
animals.add("bat");
animals.add("owl");
animals.add("bat");
animals.add("bat");
Map<String,Long> occurrenceMap =
animals.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println("occurrenceMap:: " + occurrenceMap);
}
}
Output
occurrenceMap:: {bat=3, owl=1}
The .env file should have same database name , username and password as in the mysql database and check whether all permissions are granted to the user for accessing the database or not. I solved my problem by adding the cpanel username in front of database name and username like jumbo_admingo and jumbo_user1 respectively where jumbo is my cpanel username and admingo is the database name i created in mysql and user1 is the user which has been provided the access to the database admingo. THIS SOLVED MY PROBLEM.
(source: https://stackoverflow.com/a/22784404/2377343 )
You need to stop Mysql and change user password using Commands.
Design Patterns in Dynamic Programming by Peter Norvig has thoughtful coverage of this general theme, though about 'dynamic' languages instead of 'functional' (there's overlap).
This is largely a shameless clone of my answer to the Java question of the same topic. It turns out that JewelCLI is Scala-friendly in that it doesn't require JavaBean style methods to get automatic argument naming.
JewelCLI is a Scala-friendly Java library for command-line parsing that yields clean code. It uses Proxied Interfaces Configured with Annotations to dynamically build a type-safe API for your command-line parameters.
An example parameter interface Person.scala
:
import uk.co.flamingpenguin.jewel.cli.Option
trait Person {
@Option def name: String
@Option def times: Int
}
An example usage of the parameter interface Hello.scala
:
import uk.co.flamingpenguin.jewel.cli.CliFactory.parseArguments
import uk.co.flamingpenguin.jewel.cli.ArgumentValidationException
object Hello {
def main(args: Array[String]) {
try {
val person = parseArguments(classOf[Person], args:_*)
for (i <- 1 to (person times))
println("Hello " + (person name))
} catch {
case e: ArgumentValidationException => println(e getMessage)
}
}
}
Save copies of the files above to a single directory and download the JewelCLI 0.6 JAR to that directory as well.
Compile and run the example in Bash on Linux/Mac OS X/etc.:
scalac -cp jewelcli-0.6.jar:. Person.scala Hello.scala
scala -cp jewelcli-0.6.jar:. Hello --name="John Doe" --times=3
Compile and run the example in the Windows Command Prompt:
scalac -cp jewelcli-0.6.jar;. Person.scala Hello.scala
scala -cp jewelcli-0.6.jar;. Hello --name="John Doe" --times=3
Running the example should yield the following output:
Hello John Doe
Hello John Doe
Hello John Doe
Hope this will assist anyone having the same error while importing CSV data into related tables. In my case the parent table was OK, but I got the error while importing data to the child table containing the foreign key. After temporarily removing the foregn key constraint on the child table, I managed to import the data and was suprised to find some of the values in the FK column having values of 0 (obviously this had been causing the error since the parent table did not have such values in its PK column). The cause was that, the data in my CSV column preceeding the FK column contained commas (which I was using as a field delimeter). Changing the delimeter for my CSV file solved the problem.
i think you can download the latest android SDK and use it.i do this and fixed the problem and work well. here is the link: http://developer.android.com/sdk/index.html#download
You can use the zPosition
property of the view's layer (it's a CALayer
object) to change the z-index of the view.
theView.layer.zPosition = 1;
As Viktor Nordling added, "big values are on top. You can use any values you want, including negative values." The default value is 0.
You need to import the QuartzCore framework to access the layer. Just add this line of code at the top of your implementation file.
#import "QuartzCore/QuartzCore.h"
I think that it's not supported. If you have a look at this DefaultValueAccessor
directive (see https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/default_value_accessor.ts#L23). You will see that the value used to update the bound element is $event.target.value
.
This doesn't apply in the case of inputs with type file
since the file object can be reached $event.srcElement.files
instead.
For more details, you can have a look at this plunkr: https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info:
@Component({
selector: 'my-app',
template: `
<div>
<input type="file" (change)="onChange($event)"/>
</div>
`,
providers: [ UploadService ]
})
export class AppComponent {
onChange(event) {
var files = event.srcElement.files;
console.log(files);
}
}
POSIX 7 quotes
POSIX 7 specifies both at http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html:
CLOCK_REALTIME
:
This clock represents the clock measuring real time for the system. For this clock, the values returned by clock_gettime() and specified by clock_settime() represent the amount of time (in seconds and nanoseconds) since the Epoch.
CLOCK_MONOTONIC
(optional feature):
For this clock, the value returned by clock_gettime() represents the amount of time (in seconds and nanoseconds) since an unspecified point in the past (for example, system start-up time, or the Epoch). This point does not change after system start-up time. The value of the CLOCK_MONOTONIC clock cannot be set via clock_settime().
clock_settime()
gives an important hint: POSIX systems are able to arbitrarily change CLOCK_REALITME
with it, so don't rely on it flowing neither continuously nor forward. NTP could be implemented using clock_settime()
, and could only affect CLOCK_REALITME
.
The Linux kernel implementation seems to take boot time as the epoch for CLOCK_MONOTONIC
: Starting point for CLOCK_MONOTONIC
I had faced the same issue because of some dll files were missing from References of VS13. I went to the location http://scn.sap.com/docs/DOC-7824 and installed the newest pack. It resolved the issue.
I've built a fairly simple, reusable and functional Angular2 autocomplete component based on some of the ideas in this answer/other tutorials around on this subject and others. It's by no means comprehensive but may be helpful if you decide to build your own.
The component:
import { Component, Input, Output, OnInit, ContentChild, EventEmitter, HostListener } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { AutoCompleteRefDirective } from "./autocomplete.directive";
@Component({
selector: 'autocomplete',
template: `
<ng-content></ng-content>
<div class="autocomplete-wrapper" (click)="clickedInside($event)">
<div class="list-group autocomplete" *ngIf="results">
<a [routerLink]="" class="list-group-item" (click)="selectResult(result)" *ngFor="let result of results; let i = index" [innerHTML]="dataMapping(result) | highlight: query" [ngClass]="{'active': i == selectedIndex}"></a>
</div>
</div>
`,
styleUrls: ['./autocomplete.component.css']
})
export class AutoCompleteComponent implements OnInit {
@ContentChild(AutoCompleteRefDirective)
public input: AutoCompleteRefDirective;
@Input() data: (searchTerm: string) => Observable<any[]>;
@Input() dataMapping: (obj: any) => string;
@Output() onChange = new EventEmitter<any>();
@HostListener('document:click', ['$event'])
clickedOutside($event: any): void {
this.clearResults();
}
public results: any[];
public query: string;
public selectedIndex: number = 0;
private searchCounter: number = 0;
ngOnInit(): void {
this.input.change
.subscribe((query: string) => {
this.query = query;
this.onChange.emit();
this.searchCounter++;
let counter = this.searchCounter;
if (query) {
this.data(query)
.subscribe(data => {
if (counter == this.searchCounter) {
this.results = data;
this.input.hasResults = data.length > 0;
this.selectedIndex = 0;
}
});
}
else this.clearResults();
});
this.input.cancel
.subscribe(() => {
this.clearResults();
});
this.input.select
.subscribe(() => {
if (this.results && this.results.length > 0)
{
this.selectResult(this.results[this.selectedIndex]);
}
});
this.input.up
.subscribe(() => {
if (this.results && this.selectedIndex > 0) this.selectedIndex--;
});
this.input.down
.subscribe(() => {
if (this.results && this.selectedIndex + 1 < this.results.length) this.selectedIndex++;
});
}
selectResult(result: any): void {
this.onChange.emit(result);
this.clearResults();
}
clickedInside($event: any): void {
$event.preventDefault();
$event.stopPropagation();
}
private clearResults(): void {
this.results = [];
this.selectedIndex = 0;
this.searchCounter = 0;
this.input.hasResults = false;
}
}
The component CSS:
.autocomplete-wrapper {
position: relative;
}
.autocomplete {
position: absolute;
z-index: 100;
width: 100%;
}
The directive:
import { Directive, Input, Output, HostListener, EventEmitter } from '@angular/core';
@Directive({
selector: '[autocompleteRef]'
})
export class AutoCompleteRefDirective {
@Input() hasResults: boolean = false;
@Output() change = new EventEmitter<string>();
@Output() cancel = new EventEmitter();
@Output() select = new EventEmitter();
@Output() up = new EventEmitter();
@Output() down = new EventEmitter();
@HostListener('input', ['$event'])
oninput(event: any) {
this.change.emit(event.target.value);
}
@HostListener('keydown', ['$event'])
onkeydown(event: any)
{
switch (event.keyCode) {
case 27:
this.cancel.emit();
return false;
case 13:
var hasResults = this.hasResults;
this.select.emit();
return !hasResults;
case 38:
this.up.emit();
return false;
case 40:
this.down.emit();
return false;
default:
}
}
}
The highlight pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'highlight'
})
export class HighlightPipe implements PipeTransform {
transform(value: string, args: any): any {
var re = new RegExp(args, 'gi');
return value.replace(re, function (match) {
return "<strong>" + match + "</strong>";
})
}
}
The implementation:
import { Component } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Subscriber } from "rxjs/Subscriber";
@Component({
selector: 'home',
template: `
<autocomplete [data]="getData" [dataMapping]="dataMapping" (onChange)="change($event)">
<input type="text" class="form-control" name="AutoComplete" placeholder="Search..." autocomplete="off" autocompleteRef />
</autocomplete>
`
})
export class HomeComponent {
getData = (query: string) => this.search(query);
// The dataMapping property controls the mapping of an object returned via getData.
// to a string that can be displayed to the use as an option to select.
dataMapping = (obj: any) => obj;
// This function is called any time a change is made in the autocomplete.
// When the text is changed manually, no object is passed.
// When a selection is made the object is passed.
change(obj: any): void {
if (obj) {
// You can do pretty much anything here as the entire object is passed if it's been selected.
// Navigate to another page, update a model etc.
alert(obj);
}
}
private searchData = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
// This function mimics an Observable http service call.
// In reality it's probably calling your API, but today it's looking at mock static data.
private search(query: string): Observable<any>
{
return new Observable<any>((subscriber: Subscriber<any>) => subscriber
.next())
.map(o => this.searchData.filter(d => d.indexOf(query) > -1));
}
}
I know this is a very old thread but I was looking for a solution to the same problem and I came across this before eventually finding the answer and I wanted to just post it here so somebody else in my shoes would have a shorter trek across the internet.
****Note that you probably have to run cmd.exe as an administrator for this to work**
So here we go, open up the prompt (as an adminstrator) and go to your System32 directory. Then run
C:\Windows\System32>cd ras
Now you'll be in the ras directory. Now it's time to create a temporary file with our connection info that we will then append onto the rasphone.pbk file that will allow us to use the rasdial command.
So to create our temp file run:
C:\Windows\System32\ras>copy con temp.txt
Now it will let you type the contents of the file, which should look like this:
[CONNECTION NAME]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=vpn.server.address.com
So replace CONNECTION NAME and vpn.server.address.com with the desired connection name and the vpn server address you want.
Make a new line and press Ctrl+Z to finish and save.
Now we will append this onto the rasphone.pbk file that may or may not exist depending on if you already have network connections configured or not. To do this we will run the following command:
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
This will append the contents of temp.txt to the end of rasphone.pbk, or if rasphone.pbk doesn't exist it will be created. Now we might as well delete our temp file:
C:\Windows\System32\ras>del temp.txt
Now we can connect to our newly configured VPN server with the following command:
C:\Windows\System32\ras>rasdial "CONNECTION NAME" myUsername myPassword
When we want to disconnect we can run:
C:\Windows\System32\ras>rasdial /DISCONNECT
That should cover it! I've included a direct copy and past from the command line of me setting up a connection for and connecting to a canadian vpn server with this method:
Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.
C:\Windows\system32>cd ras
C:\Windows\System32\ras>copy con temp.txt
[Canada VPN Connection]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=ca.justfreevpn.com
^Z
1 file(s) copied.
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
C:\Windows\System32\ras>del temp.txt
C:\Windows\System32\ras>rasdial "Canada VPN Connection" justfreevpn 2932
Connecting to Canada VPN Connection...
Verifying username and password...
Connecting to Canada VPN Connection...
Connecting to Canada VPN Connection...
Verifying username and password...
Registering your computer on the network...
Successfully connected to Canada VPN Connection.
Command completed successfully.
C:\Windows\System32\ras>rasdial /DISCONNECT
Command completed successfully.
C:\Windows\System32\ras>
Hope this helps.
Not sure if this completely helps, but I had an issue where I needed a "smart" merge. I had two columns, A & B. I wanted to move B over only if A was blank. See below. It is based on a selection Range, which you could use to offset the first row, perhaps.
Private Sub MergeProjectNameColumns()
Dim rngRowCount As Integer
Dim i As Integer
'Loop through column C and simply copy the text over to B if it is not blank
rngRowCount = Range(dataRange).Rows.Count
ActiveCell.Offset(0, 0).Select
ActiveCell.Offset(0, 2).Select
For i = 1 To rngRowCount
If (Len(RTrim(ActiveCell.Value)) > 0) Then
Dim currentValue As String
currentValue = ActiveCell.Value
ActiveCell.Offset(0, -1) = currentValue
End If
ActiveCell.Offset(1, 0).Select
Next i
'Now delete the unused column
Columns("C").Select
selection.Delete Shift:=xlToLeft
End Sub
The typical way is with scanf
:
int input_value;
scanf("%d", &input_value);
In most cases, however, you want to check whether your attempt at reading input succeeded. scanf
returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:
if (scanf("%d", &input_value) == 1)
// it succeeded
else
// it failed
Of course, the same is true of all the scanf
family (sscanf
, fscanf
and so on).
Put the following line in your myscript
set myFold = '~/Files/Scripts/Main'
In the terminal use
source myscript
cd $myFold
This works with font awesome:
<button class="btn btn-outline-success">
<i class="fa fa-print" aria-hidden="true"></i>
Print
</button>
None of the solutions listed worked for me. Instead, I ended up uninstalling and reinstalling Homebrew, which did the trick. Uninstall instructions may be found here: http://osxdaily.com/2018/08/12/how-uninstall-homebrew-mac/
With Symfony 4.2.7, I'm able to implement the following in my twig template, which displays the custom route name I defined in my controller(s).
In index.html.twig
<div class="col">
{% set current_path = app.request.get('_route') %}
{{ current_path }}
</div>
In my controller
...
class ArticleController extends AbstractController {
/**
* @Route("/", name="article_list")
* @Method({"GET"})
*/
public function index() {
...
}
...
}
The result prints out "article_list" to the desired page in my browser.
You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.
perhaps a:
i=2
while i < n:
if something:
do something
i += 1
else:
do something else
i = 2 #restart the loop
I had a similar problem with the same error message:
System.Web.Services.Protocols.SoapException:
Server did not recognize the value of HTTP Header SOAPAction
:
We utilize dynamic URL's in our web service calls. We have a central configuration server that manages the location of all web service calls so that our code can run in DEV, test or live without recompiling. The URL for a specific web service call for the test environment was incorrect in our configuration server. The web service call was being sent to the wrong server and the wrong web service.
So this error can simply be the result of the web service request not matching the web service being called.
It took running fiddler on the Web App server to see that the actual call was to the incorrect web service.
I think the default place for access logs is
%SystemDrive%\inetpub\logs\LogFiles
Otherwise, check under IIS Manager, select the computer on the left pane, and in the middle pane, go under "Logging" in the IIS area. There you will se the default location for all sites (this is however overridable on all sites)
You could also look into
%SystemDrive%\Windows\System32\LogFiles\HTTPERR
Which will contain similar log files that only represents errors.
It work if Lbound is different than 0 or 1. You Redim once at start
Function MergeArrays(ByRef arr1 As Variant, ByRef arr2 As Variant) As Variant
'Test if not isarray then exit
If Not IsArray(arr1) And Not IsArray(arr2) Then Exit Function
Dim arr As Variant
Dim a As Long, b As Long 'index Array
Dim len1 As Long, len2 As Long 'nb of item
'get len if array don't start to 0
len1 = UBound(arr1) - LBound(arr1) + 1
len2 = UBound(arr2) - LBound(arr2) + 1
b = 1 'position of start index
'dim new array
ReDim arr(b To len1 + len2)
'merge arr1
For a = LBound(arr1) To UBound(arr1)
arr(b) = arr1(a)
b = b + 1 'move index
Next a
'merge arr2
For a = LBound(arr2) To UBound(arr2)
arr(b) = arr2(a)
b = b + 1 'move index
Next a
'final
MergeArrays = arr
End Function
This really wierd when XCode 10
stopped to "refine debugs".
In my case, i setted UITableViewDelegate and UITableViewDataSource with Storyboard and forget to implemente those required methods.
I just wanted to test the view first, before implement those methods, then crash! XCode 9
, will warning about those methods, but XCode 10
, really maked my code slow, not on this one, others i been thru this "error doubt".
Hope this help someone.
Thanks
The best way to use https and avoid security issues is to use Firefox (or another tool) and download the certificate to your server. This webpage helped me a lot, and these were the steps that worked for me:
1) Open in Firefox the URL you're gonna use with CURL
2) On the address bar click on the padlock
> more information
(FF versions can have different menus, just find it). Click the View certificate button > Details
tab.
3) Highlight the "right" certificate in Certificate hierarchy
. In my case it was the second of three, called "cPanel, Inc. Certification Authority". I just discovered the right one by "trial and error" method.
4) Click the Export button. In my case the one who worked was the file type "PEM with chains" (again by trial and error method).
5) Then in your PHP script add:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, [PATH_TO_CRT_FILE]);
In addition I'd say that we must pay attention on the fact that these steps will probably need to be redone once a year or whenever the URL certificate is replaced or renewed.
Simple loop
public static String repeat(String string, int times) {
StringBuilder out = new StringBuilder();
while (times-- > 0) {
out.append(string);
}
return out.toString();
}
There are severals hacks available for IE
Using conditional comments with stylesheet
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="only-ie.css" />
<![endif]-->
Using conditional comments with head section css
<!--[if IE]>
<style type="text/css">
/************ css for all IE browsers ****************/
</style>
<![endif]-->
Using conditional comments with HTML elements
<!--[if IE]> <div class="ie-only"> /*content*/ </div> <![endif]-->
Using media query
IE10+
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
selector { property:value; }
}
IE6,7,9,10
@media screen and (min-width: 640px), screen\9 {
selector { property:value; }
}
IE6,7
@media screen\9 {
selector { property:value; }
}
IE8
@media \0screen {
selector { property:value; }
}
IE6,7,8
@media \0screen\,screen\9 {
selector { property:value; }
}
IE9,10
@media screen and (min-width:0\0){
selector { property:value; }
}
Anyway you need 'Year'.
In some engineering fields, you have fixed day and month and year can be variable. But that day and month are important for beginning calculation without considering which year you are. Your user, for example, only should select a day and a month and providing year is up to you.
You can create a custom combobox using this: Customizable ComboBox Drop-Down.
1- In VS create a user control.
2- See the code in the link above for impelemnting that control.
3- Create another user control and place in it 31 button or label and above them place a label to show months.
4- Place the control in step 3 in your custom combobox.
5- Place the control in setp 4 in step 1.
You now have a control with only days and months. You can use any year that you have in your database or ....
Use the HorizontalAlignment and VerticalAlignment layout properties. They control how an element uses the space it has inside its parent when more room is available than it required by the element.
The width of a StackPanel, for example, will be as wide as the widest element it contains. So, all narrower elements have a bit of excess space. The alignment properties control what the child element does with the extra space.
The default value for both properties is Stretch, so the child element is stretched to fill all available space. Additional options include Left, Center and Right for HorizontalAlignment and Top, Center and Bottom for VerticalAlignment.
There is no other way - except implementing lazy loading.
Or manual loading....
myobj = context.MyObjects.First();
myobj.ChildA.Load();
myobj.ChildB.Load();
...
Rob Heiser suggested checking out your java version by using 'java -version'.
That will identify the Java version that will be commonly found and used. Doing dev work, you can often have more than one version installed (I currently have 2 JREs - 6 and 7 - and may soon have 8).
http://www.coderanch.com/t/453224/java/java/java-version-work-setting-path
java -version will look for java.exe in the System32 directory in Windows. That's where a JRE will install it.
I'm assuming that IE either simply looks for java and that automatically starts checking in System32 or it'll use the path and hit whichever java.exe comes first in your path (if you tamper with the path to point to another JRE).
Also from what SLaks said, I would disagree with one thing. There is likely slightly better performance out of 64-it IE in 64-bit environments. So there is some reason for using it.
Here is a one liner that does this, just replace username with the username you want to kill things for. Don't even think on putting root there!
pkill -9 -u `id -u username`
Note: if you want to be nice remove -9, but it will not kill all kinds of processes.
Once I updated my Java version to 8 as suggested by browser. However I had selected to uninstall previous Java 6 version I have been used for coding my projects. When I enter the command in "java -version" in cmd it showed 1.8 and I could not start eclipse IDE run on Java 1.6.
When I installed Java 8 update for the browser it had changed the "PATH" System variable appending "C:\ProgramData\Oracle\Java\javapath" to the beginning. Newly added path pointed to Java vesion 8. So I removed that path from "PATH" System variable and everything worked fine. :)
Copy-pasted from here: Incrementing a date in JavaScript
Three options for you:
Using just JavaScript's Date object (no libraries):
var today = new Date(); var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
Or if you don't mind changing the date in place (rather than creating a new date):
var dt = new Date(); dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));
Edit: See also Jigar's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
Using MomentJS:
var today = moment(); var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)
Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today() var tomorrow = today.add(1).day();
From @Erik Hunter, I post full code for make horizontal UICollectionView
UICollectionViewFlowLayout *collectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
[collectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
self.myCollectionView.collectionViewLayout = collectionViewFlowLayout;
In Swift
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .Horizontal
self.myCollectionView.collectionViewLayout = layout
In Swift 3.0
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
self.myCollectionView.collectionViewLayout = layout
Hope this help
Make sure the PNGs are fully opaque before creating the video
e.g. with imagemagick, give them a black background:
convert 0.png -background black -flatten +matte 0_opaque.png
From my tests, no bitrate or codec is sufficient to make the video look good if you feed ffmpeg PNGs with transparency
You can primarily use Zoredache solution, but If you don't want to overwrite the output file you should write tee with -a option as follow :
ls -lR / | tee -a output.file
You could also take a look at capabilities of Qt
library.
It has regular expressions support and QString class has nice methods, e.g. split()
returning QStringList, list of strings obtained by splitting the original string with a provided delimiter. Should suffice for csv file..
To get a column with a given header name I use following: c++ inheritance Qt problem qstring
These are the ways :
1. /proc/meminfo
MemTotal: 8152200 kB
MemFree: 760808 kB
You can write a code or script to parse it.
2. Use sysconf by using below macros
sysconf (_SC_PHYS_PAGES) * sysconf (_SC_PAGESIZE);
3. By using sysinfo system call
int sysinfo(struct sysinfo *info);
struct sysinfo { .
.
unsigned long totalram; /*Total memory size to use */
unsigned long freeram; /* Available memory size*/
.
.
};
To help the confused rookies like me, the answer to "What is the maximum length of a valid email address?" is 254 characters.
If your application uses an email, just set your field to accept 254 characters or less and you are good to go.
You can run a bunch of tests on an email to see if it is valid here. http://isemail.info/
The RFC, or Request for Comments is a type of publication from the Internet Engineering Task Force (IETF) that defines 254 characters as the limit. Located here - https://tools.ietf.org/html/rfc5321#section-4.5.3
You can use the box-shadow property on a tr element as a subtitute for a border. As a plus, any border-radius property on the same element will also apply to the box shadow.
box-shadow: 0px 0px 0px 1px rgb(0, 0, 0);
Accordingly to W3C checked input's attribute can be absent/ommited or have "checked" as its value. This does not invalidate other values because there's no restriction to the browser implementation to allow values like "true", "on", "yes" and so on. To guarantee that you'll write a cross-browser checkbox/radio use checked="checked", as recommended by W3C.
disabled, readonly and ismap input's attributes go on the same way.
EDITED
empty is not a valid value for checked, disabled, readonly and ismap input's attributes, as warned by @Quentin
"What is a “
static
” function in C?"
Let's start at the beginning.
It´s all based upon a thing called "linkage":
"An identifier declared in different scopes or in the same scope more than once can be made to refer to the same object or function by a process called linkage. 29)There are three kinds of linkage: external, internal, and none."
Source: C18, 6.2.2/1
"In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity."
Source: C18, 6.2.2/2
If a function is defined without a storage-class specifier, the function has extern
al linkage by default:
"If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern."
Source: C18, 6.2.2/5
That means that - if your program is contained of several translation units/source files (.c
or .cpp
) - the function is visible in all translation units/source files your program has.
This can be a problem in some cases. What if you want to use f.e. two different function (definitions), but with the same function name in two different contexts (actually the file-context).
In C and C++, the static
storage-class qualifier applied to a function at file scope (not a static member function of a class in C++ or a function within another block) now comes to help and signifies that the respective function is only visible inside of the translation unit/source file it was defined in and not in the other TLUs/files.
"If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage. 30)"
- A function declaration can contain the storage-class specifier static only if it is at file scope; see 6.7.1.
Source: C18, 6.2.2/3
Thus, A static
function only makes sense, iff:
.c
or .cpp
).and
If not both of these requirements match, you don't need to wrap your head around about qualifying a function as static
.
Side Notes:
static
function has absolutely no difference at all between C and C++, as this is a feature C++ inherited from C.It does not matter that in the C++ community, there is a heartbreaking debate about the depreciation of qualifying functions as static
in comparison to the use of unnamed namespaces instead, first initialized by a misplaced paragraph in the C++03 standard, declaring the use of static functions as deprecated which soon was revised by the committee itself and removed in C++11.
This was subject to various SO questions:
Unnamed/anonymous namespaces vs. static functions
Superiority of unnamed namespace over static?
Why an unnamed namespace is a "superior" alternative to static?
Deprecation of the static keyword... no more?
In fact, it is not deprecated per C++ standard yet. Thus, the use of static
functions is still legit. Even if unnamed namespaces have advantages, the discussion about using or not using static functions in C++ is subject to one´s one mind (opinion-based) and with that not suitable for this website.
Use css @keyframes
.elementToFadeInAndOut {
opacity: 1;
animation: fade 2s linear;
}
@keyframes fade {
0%,100% { opacity: 0 }
50% { opacity: 1 }
}
here is a DEMO
.elementToFadeInAndOut {_x000D_
width:200px;_x000D_
height: 200px;_x000D_
background: red;_x000D_
-webkit-animation: fadeinout 4s linear forwards;_x000D_
animation: fadeinout 4s linear forwards;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeinout {_x000D_
0%,100% { opacity: 0; }_x000D_
50% { opacity: 1; }_x000D_
}_x000D_
_x000D_
@keyframes fadeinout {_x000D_
0%,100% { opacity: 0; }_x000D_
50% { opacity: 1; }_x000D_
}
_x000D_
<div class=elementToFadeInAndOut></div>
_x000D_
Reading: Using CSS animations
You can clean the code by doing this:
.elementToFadeInAndOut {_x000D_
width:200px;_x000D_
height: 200px;_x000D_
background: red;_x000D_
-webkit-animation: fadeinout 4s linear forwards;_x000D_
animation: fadeinout 4s linear forwards;_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeinout {_x000D_
50% { opacity: 1; }_x000D_
}_x000D_
_x000D_
@keyframes fadeinout {_x000D_
50% { opacity: 1; }_x000D_
}
_x000D_
<div class=elementToFadeInAndOut></div>
_x000D_
TL;DR
MySQL server might not be running after installation with Brew. Try brew services start mysql
or just mysql.server start
if you don't want MySQL to run as a background service.
Full Story:
I just installed MySQL (stable) 5.7.17 on a new MacBook Pro running Sierra and also got an error when running mysql_secure_installation
:
Securing the MySQL server deployment.
Enter password for user root:
Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
Say what?
According to the installation info from Brew, mysql_secure_installation
should prompt me to... secure the installation. I figured the MySQL server might not be running and rightly so. Running brew services start mysql
and then mysql_secure_installation
worked like a charm.
Download and install LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0).
Steps for open SDF Files:
Click Add Connection
Select Build data context automatically and Default (LINQ to SQL), then Next.
Under Provider choose SQL CE 4.0.
Under Database with Attach database file selected, choose Browse to select your .sdf file.
Click OK.
The web.xml
file is the deployment descriptor for a Servlet-based Java web application (which most Java web apps are). Among other things, it declares which Servlets exist and which URLs they handle.
The part you cite defines a Servlet Filter. Servlet filters can do all kinds of preprocessing on requests. Your specific example is a filter had the Wicket framework uses as its entry point for all requests because filters are in some way more powerful than Servlets.
Here's an ES6 one liner that doesn't use jQuery:
var rgb = document.querySelector('#selector').style['background-color'];
return '#' + rgb.substr(4, rgb.indexOf(')') - 4).split(',').map((color) => parseInt(color).toString(16)).join('');
you need double quotes in all your three if
statements, eg.:
IF "%a%"=="2" (
@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.
set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if "%a%"=="" goto :aPrompt
echo %a%
IF "%a%"=="2" (
title USB WRITE LOCK
echo What do you want to do?
echo 1.Apply USB Write Protection
echo 2.Remove USB Write Protection
::param1
set "param1=%globalparam2%"
goto :param1Check
:param1Prompt
set /p "param1=Enter Choice: "
:param1Check
if "!param1!"=="" goto :param1Prompt
if "!param1!"=="1" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
USB Write is Locked!
)
if "!param1!"=="2" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
USB Write is Unlocked!
)
)
pause
Right Click on "Solution Explorer" -> "Properties"
Expand "Common Properties"
Select "Start Up Project"
click the radio button "Single Start_up Project"
select your Project name from the drop down list.
If still not working after the above steps, then try this.
Expand solutions explorer.
Right click on project name -> "Properties"
Go to "Application" tab
Select "Output type"
From the drop down list select the appropriate type according to your application.
"Windows application" or
"Console application"
Then save (ctrl + S)
Try debugging (F5)
If you want to reassign an element in an array, you can do the following:
var blah = ['Jan', 'Fed', 'Apr'];
console.log(blah);
function reassign(array, index, newValue) {
array[index] = newValue;
return array;
}
reassign(blah, [2], 'Mar');
0. last commit,i.e. HEAD commit
1. Working tree changes, file/directory deletion,adding,modification.
2. The changes are staged in index
3. Staged changes are committed
0->1: manual file/directory operation
1->2: git add .
2->3: git commit -m "xxx"
0->1: git diff
0->2: git diff --cached
0->1, and 0->2: git diff HEAD
last last commit->last commit: git diff HEAD^ HEAD
2->1: git reset
1->0: git checkout . #only for tracked files/directories(actions include modifying/deleting tracked files/directories)
1->0: git clean -fdx #only for untracked files/directories(action includes adding new files/directories)
2->1, and 1->0: git reset --hard HEAD
git reset && git checkout . && git clean -fdx
Another way, you can use the command line cc.dbl
of ConyEdit (a plugin) to delete blank lines or empty lines.
use MAX
in your SELECT
to return on value.. EXAMPLE
INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT MAX(student_id) FROM student), (SELECT MAX(syr_id) FROM school_year))
instead of
INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT (student_id) FROM student), (SELECT (syr_id) FROM school_year))
try it without MAX it will more than one value
You should use bootstrap column nesting.
See Bootstrap 3 or Bootstrap 4:
<div class="row">
<div class="col-md-5">Span 5</div>
<div class="col-md-3">Span 3<br />second line</div>
<div class="col-md-2">
<div class="row">
<div class="col-md-12">Span 2</div>
</div>
<div class="row">
<div class="col-md-12">Span 2</div>
</div>
</div>
<div class="col-md-2">Span 2</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-12">Span 6</div>
<div class="col-md-12">Span 6</div>
</div>
</div>
<div class="col-md-6">Span 6</div>
</div>
http://jsfiddle.net/DRanJ/125/
(In Fiddle screen, enlarge your test screen to see the result, because I'm using col-md-*, then responsive stacks columns)
Note: I am not sure that BS2 allows columns nesting, but in the answer of Paul Keister, the columns nesting is not used. You should use it and avoid to reinvente css while bootstrap do well.
The columns height are auto, if you add a second line (like I do in my example), column height adapt itself.
No, not all browsers support the sizes
attribute:
Note that some platforms define specific sizes:
manifest.json
if it is present. Plus, Chrome uses the Apple Touch icon for bookmarks.I used a combination of the above because my app works in the browser as well as on device. The problem with browser is it won't let you close the window from a script unless your app was opened by a script (like browsersync).
if (typeof cordova !== 'undefined') {
if (navigator.app) {
navigator.app.exitApp();
}
else if (navigator.device) {
navigator.device.exitApp();
}
} else {
window.close();
$timeout(function () {
self.showCloseMessage = true; //since the browser can't be closed (otherwise this line would never run), ask the user to close the window
});
}
As mentioned in my earlier answer, you can use RegExp.exec()
to iterate over all matches and count each occurrence; the advantage is limited to memory only, because on the whole it's about 20% slower than using String.match()
.
var re = /\s/g,
count = 0;
while (re.exec(text) !== null) {
++count;
}
return count;
What about:
//true if it doesn't contain letters
bool result = hello.Any(x => !char.IsLetter(x));
You don't need to call json.getJSONArray()
at all, because the JSON you're working with already is an array. So, don't construct an instance of JSONObject
; use a JSONArray
. This should suffice:
// ...
JSONArray json = new JSONArray(result);
// ...
for(int i=0;i<json.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = json.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("eqid"));
map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
mylist.add(map);
}
You can't use exactly the same methods as in the tutorial, because the JSON you're dealing with needs to be parsed into a JSONArray
at the root, not a JSONObject
.