You can do this with a custom action. You can add a refrence to your custom action under <InstallExecuteSequence>
:
<InstallExecuteSequence>
...
<Custom Action="FileCleaner" After='InstallFinalize'>
Installed AND NOT UPGRADINGPRODUCTCODE</Custom>
Then you will also have to define your Action under <Product>
:
<Product>
...
<CustomAction Id='FileCleaner' BinaryKey='FileCleanerEXE'
ExeCommand='' Return='asyncNoWait' />
Where FileCleanerEXE is a binary (in my case a little c++ program that does the custom action) which is also defined under <Product>
:
<Product>
...
<Binary Id="FileCleanerEXE" SourceFile="path\to\fileCleaner.exe" />
The real trick to this is the Installed AND NOT UPGRADINGPRODUCTCODE
condition on the Custom Action, with out that your action will get run on every upgrade (since an upgrade is really an uninstall then reinstall). Which if you are deleting files is probably not want you want during upgrading.
On a side note: I recommend going through the trouble of using something like C++ program to do the action, instead of a batch script because of the power and control it provides -- and you can prevent the "cmd prompt" window from flashing while your installer runs.
Expanding on @Kiran's answer, which I agree is more succinct and Pythonic, this adds codecs to support the reading and writing of UTF-8:
import codecs
from tempfile import mkstemp
from shutil import move
from os import remove
def replace(source_file_path, pattern, substring):
fh, target_file_path = mkstemp()
with codecs.open(target_file_path, 'w', 'utf-8') as target_file:
with codecs.open(source_file_path, 'r', 'utf-8') as source_file:
for line in source_file:
target_file.write(line.replace(pattern, substring))
remove(source_file_path)
move(target_file_path, source_file_path)
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
The second pipe was interpreted by this web site when submitted... You need two backslashes at the beginning. So make sure to use System.IO.Directory.GetFiles(@"\\.\pipe\").
Note that I have seen this function call throw an 'illegal characters in path.' exception when one of the pipes on my machine had invalid characters. PipleList.exe worked ok though, so it seems like a bug in MS's .net code.
INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);
Works great, minimal setup and no third parties.
According to Chrome's documentation:
Here's the updated workflow:What happens when you blackbox a script?
Exceptions thrown from library code will not pause (if Pause on exceptions is enabled), Stepping into/out/over bypasses the library code, Event listener breakpoints don't break in library code, The debugger will not pause on any breakpoints set in library code. The end result is you are debugging your application code instead of third party resources.
jquery\..*\.js
(glob pattern/human translation: jquery.*.js
)|
, like so: jquery\..*\.js|include\.postload\.js
(which acts like an "or this pattern", so to speak. Or keep adding them with the "Add" button.Bonus tip! I use Regex101 regularly (but there are many others: ) to quickly test my rusty regex patterns and find out where I'm wrong with the step-by-step regex debugger. If you are not yet "fluent" in Regular Expressions I recommend you start using sites that help you write and visualize them such as http://buildregex.com/ and https://www.debuggex.com/
You can also use the context menu when working in the Sources panel. When viewing a file, you can right-click in the editor and choose Blackbox Script. This will add the file to the list in the Settings panel:
It's an excellent tool to have:
Visual Event is an open-source Javascript bookmarklet which provides debugging information about events that have been attached to DOM elements. Visual Event shows:
- Which elements have events attached to them
- The type of events attached to an element
- The code that will be run with the event is triggered
- The source file and line number for where the attached function was defined (Webkit browsers and Opera only)
You can pause the code when you click somewhere in the page, or when the DOM is modified... and other kinds of JS breakpoints that will be useful to know. You should apply blackboxing here to avoid a nightmare.
In this instance, I want to know what exactly goes on when I click the button.
Open Dev Tools -> Sources tab, and on the right find Event
Listener Breakpoints
:
Expand Mouse
and select click
With Dev Tools activated, you can search the whole codebase (all code in all files) with ?+?+F or:
and searching #envio
or whatever the tag/class/id you think starts the party and you may get somewhere faster than anticipated.
Be aware sometimes there's not only an img
but lots of elements stacked, and you may not know which one triggers the code.
If this is a bit out of your knowledge, take a look at Chrome's tutorial on debugging.
You should be able to simply do this:
Context context = new InitialContext();
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");
If you are looking it up from a remote destination you need to use the WL initial context factory like this:
Hashtable<String, String> h = new Hashtable<String, String>(7);
h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, pURL); //For example "t3://127.0.0.1:7001"
h.put(Context.SECURITY_PRINCIPAL, pUsername);
h.put(Context.SECURITY_CREDENTIALS, pPassword);
InitialContext context = new InitialContext(h);
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");
You need to install Cmake.
dlib is an c++ libary with python bindings. It needs to be builded first. My guess is this will happen automatically once you have installed Cmake
import com.google.common.collect.Streams;
and use Streams.stream(iterator)
:
Streams.stream(iterator)
.map(v-> function(v))
.collect(Collectors.toList());
http://www.codeproject.com/Articles/237501/Windows-Phone-NTP-Client is going to work well for Windows Phone .
Adding the relevant code
/// <summary>
/// Class for acquiring time via Ntp. Useful for applications in which correct world time must be used and the
/// clock on the device isn't "trusted."
/// </summary>
public class NtpClient
{
/// <summary>
/// Contains the time returned from the Ntp request
/// </summary>
public class TimeReceivedEventArgs : EventArgs
{
public DateTime CurrentTime { get; internal set; }
}
/// <summary>
/// Subscribe to this event to receive the time acquired by the NTP requests
/// </summary>
public event EventHandler<TimeReceivedEventArgs> TimeReceived;
protected void OnTimeReceived(DateTime time)
{
if (TimeReceived != null)
{
TimeReceived(this, new TimeReceivedEventArgs() { CurrentTime = time });
}
}
/// <summary>
/// Not reallu used. I put this here so that I had a list of other NTP servers that could be used. I'll integrate this
/// information later and will provide method to allow some one to choose an NTP server.
/// </summary>
public string[] NtpServerList = new string[]
{
"pool.ntp.org ",
"asia.pool.ntp.org",
"europe.pool.ntp.org",
"north-america.pool.ntp.org",
"oceania.pool.ntp.org",
"south-america.pool.ntp.org",
"time-a.nist.gov"
};
string _serverName;
private Socket _socket;
/// <summary>
/// Constructor allowing an NTP server to be specified
/// </summary>
/// <param name="serverName">the name of the NTP server to be used</param>
public NtpClient(string serverName)
{
_serverName = serverName;
}
/// <summary>
///
/// </summary>
public NtpClient()
: this("time-a.nist.gov")
{ }
/// <summary>
/// Begins the network communication required to retrieve the time from the NTP server
/// </summary>
public void RequestTime()
{
byte[] buffer = new byte[48];
buffer[0] = 0x1B;
for (var i = 1; i < buffer.Length; ++i)
buffer[i] = 0;
DnsEndPoint _endPoint = new DnsEndPoint(_serverName, 123);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
SocketAsyncEventArgs sArgsConnect = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
sArgsConnect.Completed += (o, e) =>
{
if (e.SocketError == SocketError.Success)
{
SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
sArgs.Completed +=
new EventHandler<SocketAsyncEventArgs>(sArgs_Completed);
sArgs.SetBuffer(buffer, 0, buffer.Length);
sArgs.UserToken = buffer;
_socket.SendAsync(sArgs);
}
};
_socket.ConnectAsync(sArgsConnect);
}
void sArgs_Completed(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
byte[] buffer = (byte[])e.Buffer;
SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs();
sArgs.RemoteEndPoint = e.RemoteEndPoint;
sArgs.SetBuffer(buffer, 0, buffer.Length);
sArgs.Completed += (o, a) =>
{
if (a.SocketError == SocketError.Success)
{
byte[] timeData = a.Buffer;
ulong hTime = 0;
ulong lTime = 0;
for (var i = 40; i <= 43; ++i)
hTime = hTime << 8 | buffer[i];
for (var i = 44; i <= 47; ++i)
lTime = lTime << 8 | buffer[i];
ulong milliseconds = (hTime * 1000 + (lTime * 1000) / 0x100000000L);
TimeSpan timeSpan =
TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
var currentTime = new DateTime(1900, 1, 1) + timeSpan;
OnTimeReceived(currentTime);
}
};
_socket.ReceiveAsync(sArgs);
}
}
}
Usage :
public partial class MainPage : PhoneApplicationPage
{
private NtpClient _ntpClient;
public MainPage()
{
InitializeComponent();
_ntpClient = new NtpClient();
_ntpClient.TimeReceived += new EventHandler<NtpClient.TimeReceivedEventArgs>(_ntpClient_TimeReceived);
}
void _ntpClient_TimeReceived(object sender, NtpClient.TimeReceivedEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
txtCurrentTime.Text = e.CurrentTime.ToLongTimeString();
txtSystemTime.Text = DateTime.Now.ToUniversalTime().ToLongTimeString();
});
}
private void UpdateTimeButton_Click(object sender, RoutedEventArgs e)
{
_ntpClient.RequestTime();
}
}
Datatables have a .Select method, which returns a rows array according to the criteria you specify. Something like this:
Dim oRows() As DataRow
oRows = dtCountries.Select("CountryName = '" & userinput & "'")
If oRows.Count = 0 Then
' No rows found
Else
' At least one row found. Could be more than one
End If
Of course, if userinput contains ' character, it would raise an exception (like if you query the database). You should escape the ' characters (I use a function to do that).
public static void selectSpinnerItemByValue(Spinner spnr, long value) {
SimpleCursorAdapter adapter = (SimpleCursorAdapter) spnr.getAdapter();
for (int position = 0; position < adapter.getCount(); position++) {
if(adapter.getItemId(position) == value) {
spnr.setSelection(position);
return;
}
}
}
You can use the above like:
selectSpinnerItemByValue(spinnerObject, desiredValue);
& of course you can also select by index directly like
spinnerObject.setSelection(index);
Another one is to use the -F option but pass it regex to print the text between left and or right parenthesis ()
.
The file content:
528(smbw)
529(smbt)
530(smbn)
10115(smbs)
The command:
awk -F"[()]" '{print $2}' filename
result:
smbw
smbt
smbn
smbs
Using awk to just print the text between []
:
Use awk -F'[][]'
but awk -F'[[]]'
will not work.
http://stanlo45.blogspot.com/2020/06/awk-multiple-field-separators.html
// prepare json data
let mapDict = [ "1":"First", "2":"Second"]
let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
let jsonData : NSData = NSKeyedArchiver.archivedData(withRootObject: json) as NSData
// create post request
let url = NSURL(string: "http://httpbin.org/post")!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData as Data
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
return
}
do {
let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
print("Result",result!)
} catch {
print("Error -> \(error)")
}
}
task.resume()
I've found out a nice workaround to IP blocking when scraping sites. It lets you run a Scraper indefinitely by running it from Google App Engine and redeploying it automatically when you get a 429.
Check out this article
public class Application {
private static List<HttpMessageConverter<?>> getMessageConverters() {
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(new MappingJacksonHttpMessageConverter());
return converters;
}
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(getMessageConverters());
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
//Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class);
ResponseEntity<Page> response =
restTemplate.exchange("http://graph.facebook.com/skbh86", HttpMethod.GET, entity, Page.class, "1");
Page page = response.getBody();
System.out.println("Name: " + page.getId());
System.out.println("About: " + page.getFirst_name());
System.out.println("Phone: " + page.getLast_name());
System.out.println("Website: " + page.getMiddle_name());
System.out.println("Website: " + page.getName());
}
}
One-to-Many and Many-to-One are similar in Multiplicity but not Aspect (i.e. Directionality).
The mapping of Associations between entity classes and the Relationships between tables. There are two categories of Relationships:
Doing this with POSIX is tricky:
POSIX Sed does not support \r
or \15
. Even if it did, the in place
option -i
is not POSIX
POSIX Awk does support \r
and \15
, however the -i inplace
option
is not POSIX
d2u and dos2unix are not POSIX utilities, but ex is
POSIX ex does not support \r
, \15
, \n
or \12
To remove carriage returns:
awk 'BEGIN{RS="^$";ORS="";getline;gsub("\r","");print>ARGV[1]}' file
To add carriage returns:
awk 'BEGIN{RS="^$";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file
If you would like to apply all of the common boolean masks as well as a general purpose mask you can chuck the following in a file and then simply assign them all as follows:
pd.DataFrame = apply_masks()
Usage:
A = pd.DataFrame(np.random.randn(4, 4), columns=["A", "B", "C", "D"])
A.le_mask("A", 0.7).ge_mask("B", 0.2)... (May be repeated as necessary
It's a little bit hacky but it can make things a little bit cleaner if you're continuously chopping and changing datasets according to filters. There's also a general purpose filter adapted from Daniel Velkov above in the gen_mask function which you can use with lambda functions or otherwise if desired.
File to be saved (I use masks.py):
import pandas as pd
def eq_mask(df, key, value):
return df[df[key] == value]
def ge_mask(df, key, value):
return df[df[key] >= value]
def gt_mask(df, key, value):
return df[df[key] > value]
def le_mask(df, key, value):
return df[df[key] <= value]
def lt_mask(df, key, value):
return df[df[key] < value]
def ne_mask(df, key, value):
return df[df[key] != value]
def gen_mask(df, f):
return df[f(df)]
def apply_masks():
pd.DataFrame.eq_mask = eq_mask
pd.DataFrame.ge_mask = ge_mask
pd.DataFrame.gt_mask = gt_mask
pd.DataFrame.le_mask = le_mask
pd.DataFrame.lt_mask = lt_mask
pd.DataFrame.ne_mask = ne_mask
pd.DataFrame.gen_mask = gen_mask
return pd.DataFrame
if __name__ == '__main__':
pass
Instead of removing and re-adding, you can do this:
git remote set-url origin git://new.url.here
See this question: How to change the URI (URL) for a remote Git repository?
To remove remote use this:
git remote remove origin
However, if you want to do it anyway, search for regex pattern
<primaryAddress>[\s\S]*?<\/primaryAddress>
and replace it with empty string...
LocalDate.now().minusDays( 10 )
Better to specify time zone.
LocalDate.now( ZoneId.of( "America/Montreal" ) ).minusDays( 10 )
The old date-time classes bundled with early versions of Java, such as java.util.Date
/.Calendar
, have proven to be troublesome, confusing, and flawed. Avoid them.
Java 8 and later supplants those old classes with the new java.time framework. See Tutorial. Defined by JSR 310, inspired by Joda-Time, and extended by theThreeTen-Extra project. The ThreeTen-Backport project back-ports the classes to Java 6 & 7; the ThreeTenABP project to Android.
The Question is vague, not clear if it asks for a date-only or a date-time.
LocalDate
For a date-only, without time-of-day, use the LocalDate
class. Note that a time zone in crucial in determining a date such as "today".
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
LocalDate tenDaysAgo = today.minusDays( 10 );
ZonedDateTime
If you meant a date-time, then use the Instant
class to get a moment on the timeline in UTC. From there, adjust to a time zone to get a ZonedDateTime
object.
Instant now = Instant.now(); // UTC.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
ZonedDateTime tenDaysAgo = zdt.minusDays( 10 );
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.
You need to use Style Sheet for this purpose.
<td style="display:none;">
There is an excellent jquery plugin, LiveQuery, that does just this.
Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.
For example you could use the following code to bind a click event to all A tags, even any A tags you might add via AJAX.
$('a').livequery('click', function(event) {
alert('clicked');
return false;
});
Once you add new A tags to your document, Live Query will bind the click event and there is nothing else that needs to be called or done.
Here is a working example of its magic...
try this
<iframe name="myIframe" id="myIframe" width="400px" height="400px" runat="server"></iframe>
Expose this iframe in the master page's codebehind:
public HtmlControl iframe
{
get
{
return this.myIframe;
}
}
Add the MasterType directive for the content page to strongly typed Master Page.
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>
In code behind
protected void Page_Load(object sender, EventArgs e)
{
this.Master.iframe.Attributes.Add("src", "some.aspx");
}
There are a few different libraries doing parsing of Excel files (.xlsx). I will list two projects I find interesting and worth looking into.
Excel parser and builder. It's kind of a wrapper for a popular project JS-XLSX, which is a pure javascript implementation from the Office Open XML spec.
Example for parsing file
var xlsx = require('node-xlsx');
var obj = xlsx.parse(__dirname + '/myFile.xlsx'); // parses a file
var obj = xlsx.parse(fs.readFileSync(__dirname + '/myFile.xlsx')); // parses a buffer
Read, manipulate and write spreadsheet data and styles to XLSX and JSON. It's an active project. At the time of writing the latest commit was 9 hours ago. I haven't tested this myself, but the api looks extensive with a lot of possibilites.
Code example:
// read from a file
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename)
.then(function() {
// use workbook
});
// pipe from stream
var workbook = new Excel.Workbook();
stream.pipe(workbook.xlsx.createInputStream());
Here's what I was able to use in a VBscript to detect Office 64bit Outlook:
Dim WshShell, blnOffice64, strOutlookPath
Set WshShell = WScript.CreateObject("WScript.Shell")
blnOffice64=False
strOutlookPath=WshShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\outlook.exe\Path")
If WshShell.ExpandEnvironmentStrings("%PROCESSOR_ARCHITECTURE%") = "AMD64" And _
not instr(strOutlookPath, "x86") > 0 then
blnOffice64=True
wscript.echo "Office 64"
End If
Here you haven't print the max and min values. Print the max and min values in the getMaxVal and getMin val methods or after the call. This is the output.
Enter the numbers now.
5
Max: 5
Min: 0
3
Max: 5
Min: 0
7
Max: 7
Min: 0
3
Max: 7
Min: 0
90
Max: 90
Min: 0
43
Max: 90
Min: 0
100
Max: 100
Min: 0
45
Max: 100
Min: 0
23
Max: 100
Min: 0
22
Max: 100
Min: 3
These are the numbers you have entered.
5 3 7 3 90 43 100 45 23 22
Also when you are declaring an array, it has all 0s initially.
try adding this to your js function:
var outputvar = document.getElementById("your_div_id_inside_html_form");
outputvar.innerHTML='<input id=id_to_send_to_php value='+your_js_var+'>';
Later in html:
<div id="id_you_choosed_for_outputvar"></div>
this div will contain the js var to be passed through a form to another js function or to php, remember to place it inside your html form!. This solution is working fine for me.
In your specific geolocation case you can try adding the following to function showPosition(position):
var outputlon = document.getElementById("lon1");
outputlon.innerHTML = '<input id=lon value='+lon+'>';
var outputlat = document.getElementById("lat1");
outputlat.innerHTML = '<input id=lat value='+lat+'>';
later add these div to your html form:
<div id=lat1></div>
<div id=lon1></div>
In these div you'll get latitude and longitude as input values for your php form, you would better hide them using css (show only the marker on a map if used) in order to avoid users to change them before to submit, and set your database to accept float values with lenght 10,7.
Hope this will help.
Updated: As of React > 0.16
Render method does not necessarily have to return a single element. An array can also be returned.
var indents = [];
for (var i = 0; i < this.props.level; i++) {
indents.push(<span className='indent' key={i}></span>);
}
return indents;
OR
return this.props.level.map((item, index) => (
<span className="indent" key={index}>
{index}
</span>
));
Docs here explaining about JSX children
OLD:
You can use one loop instead
var indents = [];
for (var i = 0; i < this.props.level; i++) {
indents.push(<span className='indent' key={i}></span>);
}
return (
<div>
{indents}
"Some text value"
</div>
);
You can also use .map and fancy es6
return (
<div>
{this.props.level.map((item, index) => (
<span className='indent' key={index} />
))}
"Some text value"
</div>
);
Also, you have to wrap the return value in a container. I used div in the above example
As the docs say here
Currently, in a component's render, you can only return one node; if you have, say, a list of divs to return, you must wrap your components within a div, span or any other component.
In Android Marshmallow many methods are deprecated.
For example, to get color use
ContextCompat.getColor(context, R.color.color_name);
Also to get drawable use
ContextCompat.getDrawable(context, R.drawable.drawble_name);
Look for assigning the output to Clipboard (in your first script) and then in second script parse Clipboard value.
Try to use the <font>
tag
?<table>
<thead>
<tr>
<th><font color="#FFF">Header 1</font></th>
<th><font color="#FFF">Header 1</font></th>
<th><font color="#FFF">Header 1</font></th>
</tr>
</thead>
<tbody>
<tr>
<td>blah blah</td>
<td>blah blah</td>
<td>blah blah</td>
</tr>
</tbody>
</table>
But I think this should work, too:
?<table>
<thead>
<tr>
<th color="#FFF">Header 1</th>
<th color="#FFF">Header 1</th>
<th color="#FFF">Header 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>blah blah</td>
<td>blah blah</td>
<td>blah blah</td>
</tr>
</tbody>
</table>
EDIT:
Crossbrowser solution:
use capitals in HEX-color.
<th bgcolor="#5D7B9D" color="#FFFFFF"><font color="#FFFFFF">Header 1</font></th>
Why do you use Int64
? AddDays
demands a double
-value to be added. Then you'll need to use the return-value of AddDays.
See here.
The problem is that, even if you see the error, your return false
affects the callback of the .each()
method ... so, even if there is an error, you reach the line
$('form').unbind('submit').submit();
and the form is submitted.
You should create a variable, validated
, for example, and set it to true. Then, in the callback, instead of return false
, set validated = false
.
Finally...
if (validated) $('form').unbind('submit').submit();
This way, only if there are no errors will the form be submitted.
var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element
I think the confusing aspect of this is the fact that BootStrap 3 is a mobile first responsive system and fails to explain how this affects the col-xx-n hierarchy in that part of the Bootstrap documentation. This makes you wonder what happens on smaller devices if you choose a value for larger devices and makes you wonder if there is a need to specify multiple values. (You don't)
I would attempt to clarify this by stating that... Lower grain types (xs, sm) attempt retain layout appearance on smaller screens and larger types (md,lg) will display correctly only on larger screens but will wrap columns on smaller devices. The values quoted in previous examples refer to the threshold as which bootstrap degrades the appearance to fit the available screen estate.
What this means in practice is that if you make the columns col-xs-n then they will retain correct appearance even on very small screens, until the window drops to a size that is so restrictive that the page cannot be displayed correctly. This should mean that devices that have a width of 768px or less should show your table as you designed it rather than in degraded (single or wrapped column form). Obviously this still depends on the content of the columns and that's the whole point. If the page attempts to display multiple columns of large data, side by side on a small screen then the columns will naturally wrap in a horrible way if you did not account for it. Therefore, depending on the data within the columns you can decide the point at which the layout is sacificed to display the content adequately.
e.g. If your page contains three col-sm-n columns bootstrap would wrap the columns into rows when the page width drops below 992px. This means that the data is still visible but will require vertical scrolling to view it. If you do not want your layout to degrade, choose xs (as long as your data can be adequately displayed on a lower resolution device in three columns)
If the horizontal position of the data is important then you should try to choose lower granularity values to retain the visual nature. If the position is less important but the page must be visible on all devices then a higher value should be used.
If you choose col-lg-n then the columns will display correctly until the screen width drops below the xs threshold of 1200px.
Hash tables are O(1)
average and amortized case complexity, however it suffers from O(n)
worst case time complexity. [And I think this is where your confusion is]
Hash tables suffer from O(n)
worst time complexity due to two reasons:
O(n)
time.However, it is said to be O(1)
average and amortized case because:
O(n)
, can at most happen after n/2
ops, which are all assumed O(1)
: Thus when you sum the average time per op, you get : (n*O(1) + O(n)) / n) = O(1)
Note because of the rehashing issue - a realtime applications and applications that need low latency - should not use a hash table as their data structure.
EDIT: Annother issue with hash tables: cache
Another issue where you might see a performance loss in large hash tables is due to cache performance. Hash Tables suffer from bad cache performance, and thus for large collection - the access time might take longer, since you need to reload the relevant part of the table from the memory back into the cache.
mvn test -Dtest=Test1#methodname
mvn test // Run all the unit test classes
mvn test -Dtest=Test1 // Run a single test class
mvn test -Dtest=Test1,Test2 // Run multiple test classes
mvn test -Dtest=Test1#testFoo* // Run all test methods that match pattern 'testFoo*' from a test class.
mvn test -Dtest=Test1#testFoo*+testBar* // Run all test methods match pattern 'testFoo*' and 'testBar*' from a test class.
Different tools may interpret the meaning of @Nullable
differently. For example, the Checker Framework and FindBugs handle @Nullable
differently.
On Angular to update a component including its template, there is a straight forward solution to this, having an @Input
property on your ChildComponent and add to your @Component
decorator changeDetection: ChangeDetectionStrategy.OnPush
as follows:
import { ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'master',
templateUrl: templateUrl,
styleUrls:[styleUrl1],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent{
@Input() data: MyData;
}
This will do all the work of check if Input data have changed and re-render the component
There is a way to make youtube autoplay, and complete playlists play through. Get Adblock browser for Android, and then go to the youtube website, and and configure it for the desktop version of the page, close Adblock browser out, and then reopen, and you will have the desktop version, where autoplay will work.
Using the desktop version will also mean that AdBlock will work. The mobile version invokes the standalone YouTube player, which is why you want the desktop version of the page, so that autoplay will work, and so ad blocking will work.
As I mentioned in my comment, I think the reason why this doesn't work is because the compiler can't infer types based on generic constraints.
Below is an alternative implementation that will compile. I've revised the IAccess interface to only have the T
generic type parameter.
interface ISignatur<T>
{
Type Type { get; }
}
interface IAccess<T>
{
ISignatur<T> Signature { get; }
T Value { get; set; }
}
class Signatur : ISignatur<bool>
{
public Type Type
{
get { return typeof(bool); }
}
}
class ServiceGate
{
public IAccess<T> Get<T>(ISignatur<T> sig)
{
throw new NotImplementedException();
}
}
static class Test
{
static void Main()
{
ServiceGate service = new ServiceGate();
var access = service.Get(new Signatur());
}
}
The Location directive system is
Like you want to forward all request which start /static
and your data present in /var/www/static
So a simple method is separated last folder from full path , that means
Full path : /var/www/static
Last Path : /static
and First path : /var/www
location <lastPath> {
root <FirstPath>;
}
So lets see what you did mistake and what is your solutions
Your Mistake :
location /static {
root /web/test.example.com/static;
}
Your Solutions :
location /static {
root /web/test.example.com;
}
For anyone having issues with Visual Studio 2019:
I had to first open menu Test ? Windows ? Test Explorer, and run the tests from there, before the option to Run / Debug tests would show up on the right click menu.
The previously obtained value of a sequence is accessed with the currval()
function.
But that will only return a value if nextval()
has been called before that.
There is absolutely no way of "peeking" at the next value of a sequence without actually obtaining it.
But your question is unclear. If you call nextval()
before doing the insert, you can use that value in the insert. Or even better, use currval()
in your insert statement:
select nextval('my_sequence') ...
... do some stuff with the obtained value
insert into my_table(id, filename)
values (currval('my_sequence'), 'some_valid_filename');
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
int n,k=0;
char *ch1;
ch1=(char*)malloc((j-i+1)*1);
n=j-i+1;
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return (char *)ch1;
}
int main()
{
int i=0,j=2;
char s[]="String";
char *test;
test=substring(i,j,s);
printf("%s",test);
free(test); //free the test
return 0;
}
This will compile fine without any warning
#include stdlib.h
test=substring(i,j,s)
; m
as it is unused char substring(int i,int j,char *ch)
or define it before main You need to include the jQuery library on your page.
You can download jQuery here and host it yourself or you can link from an external source like from Google or Microsoft.
Google's:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
Microsoft's:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js">
I am willing to bet some of my reputation that there is no such thing.
Partially because if you are worried about cross-platform SQL compatibility, your best bet in turn is to abstract your database code with some API or ORM tool that handles these things for you, and is well supported, so will deal with newer database versions as they come out.
Exact kind of API available to you will be dependent on your programming language/platform. For example, PHP has Pear:DB and others, I personally have found quite nice Python's ORM features implemented in Django framework. I presume there should be some of these things available on other platforms as well.
I am surprised that no one has given reference to Otto event Bus library
I have been using this in my android apps and it works seamlessly.
I've found this easy solution
To convert from bitmap to Base64 use this method.
private String convertBitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
To convert from Base64 to bitmap OR revert.
private Bitmap convertBase64ToBitmap(String b64) {
byte[] imageAsBytes = Base64.decode(b64.getBytes(), Base64.DEFAULT);
return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
}
Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:
registered(X, Y) :-
X = ct101; X = ct102; X = ct103.
For a fuller explanation:
If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex @Bergi mentioned just the string version for new RegExp constructor
df -g .
Option g for Size in GBs Block and . for current working directory.
I had a similar issue when deploying from OSx on my local to my Linux live site.
It ran fine on OSx, but on Linux I was getting:
An Error Was Encountered
Unable to load the requested class: Ckeditor
The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".
I also changed my load call to match the capitalization:
$this->load->library('CKEditor');
For resource names and IDs, I use @PathParams
. For optional variables, I use @QueryParams
I guess you are talking about installation in Ubuntu. Just use:
apt-get install python-numpy python-scipy
That should take care of the BLAS libraries compiling as well. Else, compiling the BLAS libraries is very difficult.
@Jay Mooney: A generic Dictionary class in .NET is actually a hash table, just with fixed types.
The code you've shown shouldn't convince anyone to use Hashtable instead of Dictionary, since both code pieces can be used for both types.
For hashtable:
foreach(object key in h.keys)
{
string keyAsString = key.ToString(); // btw, this is unnecessary
string valAsString = h[key].ToString();
System.Diagnostics.Debug.WriteLine(keyAsString + " " + valAsString);
}
For dictionary:
foreach(string key in d.keys)
{
string valAsString = d[key].ToString();
System.Diagnostics.Debug.WriteLine(key + " " + valAsString);
}
And just the same for the other one with KeyValuePair, just use the non-generic version for Hashtable, and the generic version for Dictionary.
So it's just as easy both ways, but Hashtable uses Object for both key and value, which means you will box all value types, and you don't have type safety, and Dictionary uses generic types and is thus better.
Possible duplicate: Check if an element has event listener on it. No jQuery Please find my answer there.
Basically here is the trick for Chromium (Chrome) browser:
getEventListeners(document.querySelector('your-element-selector'));
Cross Browser jQuery Solution! Raw available at GitHub
The following plugin will go through your standard test for various versions of IE, Chrome, Firefox, Safari, etc.. and establish your declared methods accordingly. It also deals with issues such as:
Use is as simple as: Scroll Down to 'Run Snippet'
$.winFocus(function(event, isVisible) {
console.log("Combo\t\t", event, isVisible);
});
// OR Pass False boolean, and it will not trigger on load,
// Instead, it will first trigger on first blur of current tab_window
$.winFocus(function(event, isVisible) {
console.log("Combo\t\t", event, isVisible);
}, false);
// OR Establish an object having methods "blur" & "focus", and/or "blurFocus"
// (yes, you can set all 3, tho blurFocus is the only one with an 'isVisible' param)
$.winFocus({
blur: function(event) {
console.log("Blur\t\t", event);
},
focus: function(event) {
console.log("Focus\t\t", event);
}
});
// OR First method becoms a "blur", second method becoms "focus"!
$.winFocus(function(event) {
console.log("Blur\t\t", event);
},
function(event) {
console.log("Focus\t\t", event);
});
/* Begin Plugin */_x000D_
;;(function($){$.winFocus||($.extend({winFocus:function(){var a=!0,b=[];$(document).data("winFocus")||$(document).data("winFocus",$.winFocus.init());for(x in arguments)"object"==typeof arguments[x]?(arguments[x].blur&&$.winFocus.methods.blur.push(arguments[x].blur),arguments[x].focus&&$.winFocus.methods.focus.push(arguments[x].focus),arguments[x].blurFocus&&$.winFocus.methods.blurFocus.push(arguments[x].blurFocus),arguments[x].initRun&&(a=arguments[x].initRun)):"function"==typeof arguments[x]?b.push(arguments[x]):_x000D_
"boolean"==typeof arguments[x]&&(a=arguments[x]);b&&(1==b.length?$.winFocus.methods.blurFocus.push(b[0]):($.winFocus.methods.blur.push(b[0]),$.winFocus.methods.focus.push(b[1])));if(a)$.winFocus.methods.onChange()}}),$.winFocus.init=function(){$.winFocus.props.hidden in document?document.addEventListener("visibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="mozHidden")in document?document.addEventListener("mozvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden=_x000D_
"webkitHidden")in document?document.addEventListener("webkitvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="msHidden")in document?document.addEventListener("msvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="onfocusin")in document?document.onfocusin=document.onfocusout=$.winFocus.methods.onChange:window.onpageshow=window.onpagehide=window.onfocus=window.onblur=$.winFocus.methods.onChange;return $.winFocus},$.winFocus.methods={blurFocus:[],blur:[],focus:[],_x000D_
exeCB:function(a){$.winFocus.methods.blurFocus&&$.each($.winFocus.methods.blurFocus,function(b,c){this.apply($.winFocus,[a,!a.hidden])});a.hidden&&$.winFocus.methods.blur&&$.each($.winFocus.methods.blur,function(b,c){this.apply($.winFocus,[a])});!a.hidden&&$.winFocus.methods.focus&&$.each($.winFocus.methods.focus,function(b,c){this.apply($.winFocus,[a])})},onChange:function(a){var b={focus:!1,focusin:!1,pageshow:!1,blur:!0,focusout:!0,pagehide:!0};if(a=a||window.event)a.hidden=a.type in b?b[a.type]:_x000D_
document[$.winFocus.props.hidden],$(window).data("visible",!a.hidden),$.winFocus.methods.exeCB(a);else try{$.winFocus.methods.onChange.call(document,new Event("visibilitychange"))}catch(c){}}},$.winFocus.props={hidden:"hidden"})})(jQuery);_x000D_
/* End Plugin */_x000D_
_x000D_
// Simple example_x000D_
$(function() {_x000D_
$.winFocus(function(event, isVisible) {_x000D_
$('td tbody').empty();_x000D_
$.each(event, function(i) {_x000D_
$('td tbody').append(_x000D_
$('<tr />').append(_x000D_
$('<th />', { text: i }),_x000D_
$('<td />', { text: this.toString() })_x000D_
)_x000D_
)_x000D_
});_x000D_
if (isVisible) _x000D_
$("#isVisible").stop().delay(100).fadeOut('fast', function(e) {_x000D_
$('body').addClass('visible');_x000D_
$(this).stop().text('TRUE').fadeIn('slow');_x000D_
});_x000D_
else {_x000D_
$('body').removeClass('visible');_x000D_
$("#isVisible").text('FALSE');_x000D_
}_x000D_
});_x000D_
})
_x000D_
body { background: #AAF; }_x000D_
table { width: 100%; }_x000D_
table table { border-collapse: collapse; margin: 0 auto; width: auto; }_x000D_
tbody > tr > th { text-align: right; }_x000D_
td { width: 50%; }_x000D_
th, td { padding: .1em .5em; }_x000D_
td th, td td { border: 1px solid; }_x000D_
.visible { background: #FFA; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h3>See Console for Event Object Returned</h3>_x000D_
<table>_x000D_
<tr>_x000D_
<th><p>Is Visible?</p></th>_x000D_
<td><p id="isVisible">TRUE</p></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan="2">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th colspan="2">Event Data <span style="font-size: .8em;">{ See Console for More Details }</span></th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody></tbody>_x000D_
</table>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
In my case I also have unmanaged dll's (C++) in workspace and if you specify:
<files>
<file src="bin\*.dll" target="lib" />
</files>
nuget would try to load every dll as an assembly, even the C++ libraries! To avoid this
behaviour explicitly define your C# assemblies with references
tag:
<references>
<reference file="Managed1.dll" />
<reference file="Managed2.dll" />
</references>
Remark: parent of references is metadata -> according to documentation https://docs.microsoft.com/en-us/nuget/reference/nuspec#general-form-and-schema
Documentation: https://docs.microsoft.com/en-us/nuget/reference/nuspec
Op later stated they were using Apache Commons HttpClient 3.0.1
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
client.getHttpConnectionManager().getParams().setSoTimeout(5000);
npm install [email protected] -g
npm install [email protected] -g
$a = array(1, '', '', '', 2, '', 3, 4);
$b = array_values(array_filter($a));
print_r($b)
If one is on a Windows machine and in PowerShell, one needs to quote the argument such as:
git stash apply "stash@{0}"
...or to apply the changes and remove from the stash:
git stash pop "stash@{0}"
Otherwise without the quotes you might get this error:
fatal: ambiguous argument 'stash@': unknown revision or path not in the working tree.
While you can't inform JavaScript the language about types, you can inform your IDE about them, so you get much more useful autocompletion.
Here are two ways to do that:
Use JSDoc, a system for documenting JavaScript code in comments. In particular, you'll need the @param
directive:
/**
* @param {Date} myDate - The date
* @param {string} myString - The string
*/
function myFunction(myDate, myString) {
// ...
}
You can also use JSDoc to define custom types and specify those in @param
directives, but note that JSDoc won't do any type checking; it's only a documentation tool. To check types defined in JSDoc, look into TypeScript, which can parse JSDoc tags.
Use type hinting by specifying the type right before the parameter in a
/* comment */
:
This is a pretty widespread technique, used by ReactJS for instance. Very handy for parameters of callbacks passed to 3rd party libraries.
For actual type checking, the closest solution is to use TypeScript, a (mostly) superset of JavaScript. Here's TypeScript in 5 minutes.
Using the SSH URL from GitLab:
Step 1: Generate an SSH Key with default values from GitLab.
GitLab provides the commands to generate it. Just copy them, edit the email, and paste it in the terminal. Using the default values is important. Else SourceTree will not be able to access the SSH key without additional configuration.
STEP 2: Add the SSH key to your keychain using the command ssh-add -K
.
Open the terminal and paste the above command in it. This will add the key to your keychain.
STEP 3: Restart SourceTree and clone remote repo using URL.
Restarting SourceTree is needed so that SourceTree picks the new key.
STEP 4: Copy the SSH URL provided by GitLab.
STEP 5: Paste the SSH URL into the Source URL field of SourceTree.
These steps were successfully performed on Mac OS 10.13.2 using SourceTree 2.7.1.
I've had this same problem for a while as I generate a fair number of ad-hoc reports from SQL Server and copy/paste them into Excel. I would also welcome a proper solution but my temporary workaround was to create a default macro in Excel which converts highlighted cells to Excel's datetime format, and assigned it to a hotkey (Shift-Ctrl-D in my case). So I open Excel, copy/paste from SSMS into a new Excel worksheet, highlight the column to convert and press Shift-Ctrl-D. Job done.
file__IO = input('\nEnter file name here to analize with path:: ')
with open(file__IO, 'r') as f:
data = f.read()
line = data.splitlines()
words = data.split()
spaces = data.split(" ")
charc = (len(data) - len(spaces))
print('\n Line number ::', len(line), '\n Words number ::', len(words), '\n Spaces ::', len(spaces), '\n Charecters ::', (len(data)-len(spaces)))
I tried this code & it works as expected.
\b\d{1,6}\b
Explanation
\b # word boundary - start
\d # any digits between 0 to 9 (inclusive)
{1,6} # length - min 1 digit or max 6 digits
\b # word boundary - end
Above solution didn't work for me. So what I did is take ProgressDialog
as globally and then add this to my activity
@Override
protected void onDestroy() {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
super.onDestroy();
}
so that in case if activity is destroyed then the ProgressDialog will also be destroy.
I did a hack by putting it in background:
[root@localhost ~]# kubectl run hello -it --image ubuntu -- bash &
[2] 128461
Exec on pod hello
[root@localhost ~]# kubectl exec -it hello -- whoami
root
[root@localhost ~]# kubectl exec -it hello -- hostname
hello
Getting a shell
[root@localhost ~]# kubectl exec -it hello -- bash
root@hello:/# ls
bin boot dev etc home lib lib32 lib64 libx32 media mnt opt proc root run sbin srv sys tmp usr var
Disclaim: the following suggestion could be an overhead depending on the situation. The function is only tested with MSSQL 2008 R2 but seams be compatible to other versions
if you wane do this with many Id's you may could use a function which creates a temp table where you will be able to DELETE FROM the selection
how the query could look like:
-- not tested
-- @ids will contain a varchar with your ids e.g.'9 12 27 37'
DELETE FROM table WHERE id IN (SELECT i.number FROM iter_intlist_to_tbl(@ids))
here is the function:
ALTER FUNCTION iter_intlist_to_tbl (@list nvarchar(MAX))
RETURNS @tbl TABLE (listpos int IDENTITY(1, 1) NOT NULL,
number int NOT NULL) AS
-- funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
-- dient zum übergeben einer liste von elementen
BEGIN
-- Deklaration der Variablen
DECLARE @startpos int,
@endpos int,
@textpos int,
@chunklen smallint,
@str nvarchar(4000),
@tmpstr nvarchar(4000),
@leftover nvarchar(4000)
-- Startwerte festlegen
SET @textpos = 1
SET @leftover = ''
-- Loop 1
WHILE @textpos <= datalength(@list) / 2
BEGIN
--
SET @chunklen = 4000 - datalength(@leftover) / 2 --datalength() gibt die anzahl der bytes zurück (mit Leerzeichen)
--
SET @tmpstr = ltrim(@leftover + substring(@list, @textpos, @chunklen))--SUBSTRING ( @string ,start , length ) | ltrim(@string) abschneiden aller Leerzeichen am Begin des Strings
--hochzählen der TestPosition
SET @textpos = @textpos + @chunklen
--start position 0 setzen
SET @startpos = 0
-- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr)--charindex(searchChar,Wo,Startposition)
-- Loop 2
WHILE @endpos > 0
BEGIN
--str ist der string welcher zwischen den [LEERZEICHEN] steht
SET @str = substring(@tmpstr, @startpos + 1, @endpos - @startpos - 1)
--wenn @str nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
IF @str <> ''
INSERT @tbl (number) VALUES(convert(int, @str))-- convert(Ziel-Type,Value)
-- start wird auf das letzte bekannte end gesetzt
SET @startpos = @endpos
-- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr, @startpos + 1)
END
-- Loop 2
-- dient dafür den letzten teil des strings zu selektieren
SET @leftover = right(@tmpstr, datalength(@tmpstr) / 2 - @startpos)--right(@string,anzahl der Zeichen) bsp.: right("abcdef",3) => "def"
END
-- Loop 1
--wenn @leftover nach dem entfernen aller [LEERZEICHEN] nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
IF ltrim(rtrim(@leftover)) <> ''
INSERT @tbl (number) VALUES(convert(int, @leftover))
RETURN
END
-- ############################ WICHTIG ############################
-- das is ein Beispiel wie man die Funktion benutzt
--
--CREATE PROCEDURE get_product_names_iter
-- @ids varchar(50) AS
--SELECT P.ProductName, P.ProductID
--FROM Northwind.Products P
--JOIN iter_intlist_to_tbl(@ids) i ON P.ProductID = i.number
--go
--EXEC get_product_names_iter '9 12 27 37'
--
-- Funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
-- dient zum übergeben einer Liste von Id's
-- ############################ WICHTIG ############################
A simple way of doing this is to use Password Based Encryption in Java. This allows you to encrypt and decrypt a text by using a password.
This basically means initializing a javax.crypto.Cipher
with algorithm "AES/CBC/PKCS5Padding"
and getting a key from javax.crypto.SecretKeyFactory
with the "PBKDF2WithHmacSHA512"
algorithm.
Here is a code example (updated to replace the less secure MD5-based variant):
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class ProtectedConfigFile {
public static void main(String[] args) throws Exception {
String password = System.getProperty("password");
if (password == null) {
throw new IllegalArgumentException("Run with -Dpassword=<password>");
}
// The salt (probably) can be stored along with the encrypted data
byte[] salt = new String("12345678").getBytes();
// Decreasing this speeds down startup time and can be useful during testing, but it also makes it easier for brute force attackers
int iterationCount = 40000;
// Other values give me java.security.InvalidKeyException: Illegal key size or default parameters
int keyLength = 128;
SecretKeySpec key = createSecretKey(password.toCharArray(),
salt, iterationCount, keyLength);
String originalPassword = "secret";
System.out.println("Original password: " + originalPassword);
String encryptedPassword = encrypt(originalPassword, key);
System.out.println("Encrypted password: " + encryptedPassword);
String decryptedPassword = decrypt(encryptedPassword, key);
System.out.println("Decrypted password: " + decryptedPassword);
}
private static SecretKeySpec createSecretKey(char[] password, byte[] salt, int iterationCount, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterationCount, keyLength);
SecretKey keyTmp = keyFactory.generateSecret(keySpec);
return new SecretKeySpec(keyTmp.getEncoded(), "AES");
}
private static String encrypt(String property, SecretKeySpec key) throws GeneralSecurityException, UnsupportedEncodingException {
Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
pbeCipher.init(Cipher.ENCRYPT_MODE, key);
AlgorithmParameters parameters = pbeCipher.getParameters();
IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class);
byte[] cryptoText = pbeCipher.doFinal(property.getBytes("UTF-8"));
byte[] iv = ivParameterSpec.getIV();
return base64Encode(iv) + ":" + base64Encode(cryptoText);
}
private static String base64Encode(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
private static String decrypt(String string, SecretKeySpec key) throws GeneralSecurityException, IOException {
String iv = string.split(":")[0];
String property = string.split(":")[1];
Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(base64Decode(iv)));
return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
}
private static byte[] base64Decode(String property) throws IOException {
return Base64.getDecoder().decode(property);
}
}
One problem remains: Where should you store the password that you use to encrypt the passwords? You can store it in the source file and obfuscate it, but it's not too hard to find it again. Alternatively, you can give it as a system property when you start the Java process (-DpropertyProtectionPassword=...
).
The same issue remains if you use the KeyStore, which also is protected by a password. Basically, you will need to have one master password somewhere, and it's pretty hard to protect.
Another option is to use Descendant selectors
HTML:
<div class="social">
<p class="first">burrito</p>
<p class="last">chimichanga</p>
</div>
Reference first one in CSS: .social .first { color: blue; }
Reference last one in CSS: .social .last { color: green; }
Jsfiddle: https://jsfiddle.net/covbtpaq/153/
for example:
$_SERVER['SERVER_ADDR']
when your on IIS, try:
$_SERVER['LOCAL_ADDR']
Of note, use of DecimalFormat
constructor is discouraged. The javadoc for this class states:
In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat.
https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html
So what you need to do is (for instance):
NumberFormat formatter = NumberFormat.getInstance(Locale.US);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
formatter.setRoundingMode(RoundingMode.HALF_UP);
Float formatedFloat = new Float(formatter.format(floatValue));
If it is in the same class it is fine to trust the method.
It is very common to do this. It is good practice to check null values in constructor's and method's arguments to make sure that nobody is passing null values into them (if it is not allowed). Then if you implement your methods in a way that they never set the "start" graph to null, don't check for nulls there.
It is also good practice to implement unit tests for your methods and make sure that they are correctly implemented, so you can trust them.
UIView can be inserted at the top and bottom of the table(drag and drop). Set their properties as transparent and height of 1 px. This is to remove the extra padding in front of the cells.
You could use <iframe src="link/to/file.mp3" allow="autoplay">
, if the origin has an autoplay permission. More info here.
Is using MS SQL Server you can do the following:
--List all tables primary keys
select * from information_schema.table_constraints
where constraint_type = 'Primary Key'
You can also filter on the table_name column if you want a specific table.
For people who are using AngularJS, can handle this situation using Promises
.
Here it says,
Promises can be used to unnest asynchronous functions and allows one to chain multiple functions together.
You can find a nice explanation here also.
Example found in docs mentioned below.
promiseB = promiseA.then(
function onSuccess(result) {
return result + 1;
}
,function onError(err) {
//Handle error
}
);
// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1.
In Angular2
with look at the following example, but its recommended to use Observables
with Angular2
.
search(term: string) {
return this.http
.get(`https://api.spotify.com/v1/search?q=${term}&type=artist`)
.map((response) => response.json())
.toPromise();
}
You can consume that in this way,
search() {
this.searchService.search(this.searchField.value)
.then((result) => {
this.result = result.artists.items;
})
.catch((error) => console.error(error));
}
See the original post here. But Typescript does not support native es6 Promises, if you want to use it, you might need plugin for that.
Additionally here is the promises spec define here.
private void getRound() {
// this is very simple and interesting
double a = 5, b = 3, c;
c = a / b;
System.out.println(" round val is " + c);
// round val is : 1.6666666666666667
// if you want to only two precision point with double we
// can use formate option in String
// which takes 2 parameters one is formte specifier which
// shows dicimal places another double value
String s = String.format("%.2f", c);
double val = Double.parseDouble(s);
System.out.println(" val is :" + val);
// now out put will be : val is :1.67
}
Do you mean something like:
SELECT COLUMN1, COLUMN2 FROM MY_TABLE WHERE COLUMN1 = 'Value' OR COLUMN1 IS NULL
?
I use largely the same patterns as Aaronaught, but if you have a lot of properties it could be nice to use a little generic method magic to make your code a little more DRY
public class TheClass : INotifyPropertyChanged {
private int _property1;
private string _property2;
private double _property3;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null) {
handler(this, e);
}
}
protected void SetPropertyField<T>(string propertyName, ref T field, T newValue) {
if(!EqualityComparer<T>.Default.Equals(field, newValue)) {
field = newValue;
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
}
public int Property1 {
get { return _property1; }
set { SetPropertyField("Property1", ref _property1, value); }
}
public string Property2 {
get { return _property2; }
set { SetPropertyField("Property2", ref _property2, value); }
}
public double Property3 {
get { return _property3; }
set { SetPropertyField("Property3", ref _property3, value); }
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
Usually I also make the OnPropertyChanged method virtual to allow sub-classes to override it to catch property changes.
Yeah, this appears to be a common standard. Some coders use self, others use me. It's used as a reference back to the "real" object as opposed to the event.
It's something that took me a little while to really get, it does look odd at first.
I usually do this right at the top of my object (excuse my demo code - it's more conceptual than anything else and isn't a lesson on excellent coding technique):
function MyObject(){
var me = this;
//Events
Click = onClick; //Allows user to override onClick event with their own
//Event Handlers
onClick = function(args){
me.MyProperty = args; //Reference me, referencing this refers to onClick
...
//Do other stuff
}
}
The difference is in the exe being called: set it up to call bcomp.exe and it'll work fine. Configure your environment to call bcompare.exe and you'll end up with the side of the comparison taken from your revision system being empty.
If you are encountering this issue on an Alpine based image try this :
apk add --update --no-cache g++ gcc libxml2-dev libxslt-dev python-dev libffi-dev openssl-dev make
// pip install -r requirements.txt
Ahmet's answer provides on how to assign the comma separated values to String array.
To use the above configuration in different classes you might need to create getters/setters for this.. But if you would like to load this configuration once and keep using this as a bean with Autowired annotation, here is the how I accomplished:
In ConfigProvider.java
@Bean (name = "ignoreFileNames")
@ConfigurationProperties ( prefix = "ignore.filenames" )
public List<String> ignoreFileNames(){
return new ArrayList<String>();
}
In outside classes:
@Autowired
@Qualifier("ignoreFileNames")
private List<String> ignoreFileNames;
you can use the same list everywhere else by autowiring.
It looks like your 'trainData' is a list of strings:
['-214' '-153' '-58' ..., '36' '191' '-37']
Change your 'trainData' to a numeric type.
import numpy as np
np.array(['1','2','3']).astype(np.float)
You can use the following code:
return RedirectToAction("Index", "Home");
See RedirectToAction
Just export your gradient as SVG and use it using react-native-svg
and when after you import your component set width and height and preserveAspectRatio="xMinYMin slice"
to scale an SVG gradient at your needs.
Since the Except extension method operates on two IEumerables, it seems to me that it will be a O(n^2) operation. If performance is an issue (if say your lists are large), I'd suggest creating a HashSet from list1 and use HashSet's ExceptWith method.
I'm amazed that this topic is 9 years old and the actual straightforward answer is not here!
What you're looking for is scrollRectToVisible(_:animated:)
.
Example:
extension SignUpView: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
scrollView.scrollRectToVisible(textField.frame, animated: true)
}
}
What it does is exactly what you need, and it's far better than hacky contentOffset
This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing.
From: https://developer.apple.com/documentation/uikit/uiscrollview/1619439-scrollrecttovisible
A basic and very simple way of doing this without any code required would be to just provide an empty alt statement. The browser will then return the image as blank. It would look just like if the image isn't there.
Example:
<img class="img_gal" alt="" src="awesome.jpg">
Try it out to see! ;)
The solution indicated by Guannan Shen has one drawback that usually goes unnoticed.
When you run sudo R
in order to run install.packages()
as superuser, the directories in which you install the library end up belonging to root
user, a.k.a., the superuser.
So, next time you need to update your libraries, you will not remember that you ran sudo
, therefore leaving root
as the owner of the files and directories; that eventually causes the error when trying to move files, because no one can overwrite root
but themself.
That can be averted by running
sudo chown -R yourusername:yourusername *
in the directory lib
that contains your local libraries, replacing yourusername
by the adequated value in your installation. Then you try installing once again.
One of the following solutions will work for you:
c:\Python\27\python.exe
or set PYTHON=D:\Python\bin\Python.exe
npm config set python D:\Library\Python\Python27\python.exe
npm --add-python-to-path='true' --debug install --global windows-build-tools
(Must be executed via "Run As Administrator" PowerShell)If not... Try to install the required package on your own (I did so, and it was node-sass
, after installing it manually, the whole npm install
was successfully completed
In summary;
git init
git status
git add "*"
git commit -m "Comment you want"
git remote add origin https://link
git push -u origin master
I would like to share a source with you so that you learn about Git more easily.
You can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
Dim connString as String ="server=localhost;userid=root;password=123456;database=uni_park_db"
Dim conn as MySqlConnection(connString)
Dim cmd as MysqlCommand
Dim dt as New DataTable
Dim ireturn as Boolean
Private Sub Insert_Car()
Dim sql as String = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (@car_id,@member_id,@model,@color,@chassis_id,@plate_number,@code)"
Dim cmd = new MySqlCommand(sql, conn)
cmd.Paramaters.AddwithValue("@car_id", txtCar.Text)
cmd.Paramaters.AddwithValue("@member_id", txtMember.Text)
cmd.Paramaters.AddwithValue("@model", txtModel.Text)
cmd.Paramaters.AddwithValue("@color", txtColor.Text)
cmd.Paramaters.AddwithValue("@chassis_id", txtChassis.Text)
cmd.Paramaters.AddwithValue("@plate_number", txtPlateNo.Text)
cmd.Paramaters.AddwithValue("@code", txtCode.Text)
Try
conn.Open()
If cmd.ExecuteNonQuery() > 0 Then
ireturn = True
End If
conn.Close()
Catch ex as Exception
ireturn = False
conn.Close()
End Try
Return ireturn
End Sub
With C++11 you can use the constexpr
keyword and write in your header:
private:
static constexpr const char* SOMETHING = "something";
Notes:
constexpr
makes SOMETHING
a constant pointer so you cannot write
SOMETHING = "something different";
later on.
Depending on your compiler, you might also need to write an explicit definition in the .cpp file:
constexpr const char* MyClass::SOMETHING;
#include<iostream>
using namespace std;
class A
{
public:
struct Assign
{
public:
int a=10;
float b=20.5;
private:
double c=30.0;
long int d=40;
};
struct Assign ALT;
};
class B: public A
{
public:
int x = 10;
private:
float y = 20.8;
};
int main()
{
B myobj;
A obj;
//cout<<myobj.a<<endl;
//cout<<myobj.b<<endl;
//cout<<obj.a<<endl;
//cout<<obj.b<<endl;
cout<<myobj.ALT.a<<endl;
return 0;
}
enter code here
Brief syntax lesson
Cells(Row, Column)
identifies a cell. Row must be an integer between 1 and the maximum for version of Excel you are using. Column must be a identifier (for example: "A", "IV", "XFD") or a number (for example: 1, 256, 16384)
.Cells(Row, Column)
identifies a cell within a sheet identified in a earlier With statement:
With ActiveSheet
:
.Cells(Row,Column)
:
End With
If you omit the dot, Cells(Row,Column)
is within the active worksheet. So wsh = ActiveWorkbook
wsh.Range
is not strictly necessary. However, I always use a With statement so I do not wonder which sheet I meant when I return to my code in six months time. So, I would write:
With ActiveSheet
:
.Range.
:
End With
Actually, I would not write the above unless I really did want the code to work on the active sheet. What if the user has the wrong sheet active when they started the macro. I would write:
With Sheets("xxxx")
:
.Range.
:
End With
because my code only works on sheet xxxx.
Cells(Row,Column)
identifies a cell. Cells(Row,Column).xxxx identifies a property of the cell. Value
is a property. Value is the default property so you can usually omit it and the compiler will know what you mean. But in certain situations the compiler can be confused so the advice to include the .Value
is good.
Cells(Row,Column) like "*Miami*"
will give True if the cell is "Miami", "South Miami", "Miami, North" or anything similar.
Cells(Row,Column).Value = "Miami"
will give True if the cell is exactly equal to "Miami". "MIAMI" for example will give False. If you want to accept MIAMI, use the lower case function:
Lcase(Cells(Row,Column).Value) = "miami"
My suggestions
Your sample code keeps changing as you try different suggestions which I find confusing. You were using Cells(Row,Column) <> "Miami"
when I started typing this.
Use
If Cells(i, "A").Value like "*Miami*" And Cells(i, "D").Value like "*Florida*" Then
Cells(i, "C").Value = "BA"
if you want to accept, for example, "South Miami" and "Miami, North".
Use
If Cells(i, "A").Value = "Miami" And Cells(i, "D").Value like "Florida" Then
Cells(i, "C").Value = "BA"
if you want to accept, exactly, "Miami" and "Florida".
Use
If Lcase(Cells(i, "A").Value) = "miami" And _
Lcase(Cells(i, "D").Value) = "florida" Then
Cells(i, "C").Value = "BA"
if you don't care about case.
So that you don't mess up other permissions already on the file, use the flag +
, such as via
sudo chmod -R o+rw /var/www
One way is to use the multiple class selector (no space as that is the descendant selector):
.reMode_hover:not(.reMode_selected):hover _x000D_
{_x000D_
background-color: #f0ac00;_x000D_
}
_x000D_
<a href="" title="Design" class="reMode_design reMode_hover">_x000D_
<span>Design</span>_x000D_
</a>_x000D_
_x000D_
<a href="" title="Design" _x000D_
class="reMode_design reMode_hover reMode_selected">_x000D_
<span>Design</span>_x000D_
</a>
_x000D_
You can do:
git log -S <whatever> --source --all
To find all commits that added or removed the fixed string whatever
. The --all
parameter means to start from every branch and --source
means to show which of those branches led to finding that commit. It's often useful to add -p
to show the patches that each of those commits would introduce as well.
Versions of git since 1.7.4 also have a similar -G
option, which takes a regular expression. This actually has different (and rather more obvious) semantics, explained in this blog post from Junio Hamano.
As thameera points out in the comments, you need to put quotes around the search term if it contains spaces or other special characters, for example:
git log -S 'hello world' --source --all
git log -S "dude, where's my car?" --source --all
Here's an example using -G
to find occurrences of function foo() {
:
git log -G "^(\s)*function foo[(][)](\s)*{$" --source --all
Had to add the service in the calling App.config file to have it work. Make sure that you but it after all . This seemed to work for me.
You can try editing /etc/php5/fpm/php.ini:
; Old Limit
; memory_limit = 512M
; New Limit
memory_limit = 2048M
You may need to restart nginx
:
sudo systemctl restart nginx
You may also have an infinite loop somewhere. Can you post the code you're calling?
My case is I have a table like this
---------------------------------------------
|company_name|company_ID|CA | WA |
---------------------------------------------
|Costco | 1 |NULL | 2 |
---------------------------------------------
|Costco | 1 |3 |Null |
---------------------------------------------
And I want it to be like below:
---------------------------------------------
|company_name|company_ID|CA | WA |
---------------------------------------------
|Costco | 1 |3 | 2 |
---------------------------------------------
Most code is almost the same:
SELECT
FK,
MAX(CA) AS CA,
MAX(WA) AS WA
FROM
table1
GROUP BY company_name,company_ID
The only difference is the group by
, if you put two column names into it, you can group them in pairs.
I used a formula that I got from www.geomidpoint.com and wrote the following C++ implementation. The array
and geocoords
are my own classes whose functionality should be self-explanatory.
/*
* midpoints calculated using formula from www.geomidpoint.com
*/
geocoords geocoords::calcmidpoint( array<geocoords>& points )
{
if( points.empty() ) return geocoords();
float cart_x = 0,
cart_y = 0,
cart_z = 0;
for( auto& point : points )
{
cart_x += cos( point.lat.rad() ) * cos( point.lon.rad() );
cart_y += cos( point.lat.rad() ) * sin( point.lon.rad() );
cart_z += sin( point.lat.rad() );
}
cart_x /= points.numelems();
cart_y /= points.numelems();
cart_z /= points.numelems();
geocoords mean;
mean.lat.rad( atan2( cart_z, sqrt( pow( cart_x, 2 ) + pow( cart_y, 2 ))));
mean.lon.rad( atan2( cart_y, cart_x ));
return mean;
}
Just Try to do like this....
SortedDictionary<string, int> userCache = UserCache.getSortedUserValueCache();
// Add this code
if(userCache != null)
{
userListComboBox.DataSource = new BindingSource(userCache, null); // Key => null
userListComboBox.DisplayMember = "Key";
userListComboBox.ValueMember = "Value";
}
I experienced the System.TypeInitializationException
due to a different error in my .NET framework 4 project's app.config. Thank you to pStan for getting me to look at the app.config. My configSections were properly defined. However, an undefined element within one of the sections caused the exception to be thrown.
Bottom line is that problems in the app.config can generated this very misleading TypeInitializationException
.
A more meaningful ConfigurationErrorsException
can be generated by the same error in the app.config by waiting to access the config values until you are within a method rather than at the class level of the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections.Specialized;
namespace ConfigTest
{
class Program
{
public static string machinename;
public static string hostname;
public static NameValueCollection _AppSettings;
static void Main(string[] args)
{
machinename = System.Net.Dns.GetHostName().ToLower();
hostname = "abc.com";// System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).HostName.ToLower().Replace(machinename + ".", "");
_AppSettings = ConfigurationManager.GetSection("domain/" + hostname) as System.Collections.Specialized.NameValueCollection;
}
}
}
I don't know since which version of git this is working, but that's what you're searching for:
git submodule update --recursive
I use it with git pull
to update the root repository, too:
git pull && git submodule update --recursive
>>> s = pd.Series([1,2,3,4,np.NaN,5,np.NaN])
>>> s[~s.isnull()]
0 1
1 2
2 3
3 4
5 5
update or even better approach as @DSM suggested in comments, using pandas.Series.dropna()
:
>>> s.dropna()
0 1
1 2
2 3
3 4
5 5
I use div instead of tables and am able to target classes within the main class, as below:
.main {
.width: 800px;
.margin: 0 auto;
.text-align: center;
}
.main .table {
width: 80%;
}
.main .row {
/ ***something ***/
}
.main .column {
font-size: 14px;
display: inline-block;
}
.main .left {
width: 140px;
margin-right: 5px;
font-size: 12px;
}
.main .right {
width: auto;
margin-right: 20px;
color: #fff;
font-size: 13px;
font-weight: normal;
}
<div class="main">
<div class="table">
<div class="row">
<div class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:
.main #red { color: red; }
<div class="main">
<div class="table">
<div class="row">
<div id="red" class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
Regarding the suggestion So I would suggest that you use WebClient and investigate the causes of the 30 second delay.
From the answers for the question System.Net.WebClient unreasonably slow
Try setting Proxy = null;
WebClient wc = new WebClient(); wc.Proxy = null;
Credit to Alex Burtsev
Use Apache Common IO's FileUtils
:
import org.apache.commons.io.FileUtils
FileUtils.copyURLToFile(url, f);
The method downloads the content of url
and saves it to f
.
// "Main" is name of .storybord file "
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// "MiniGameView" is the ID given to the ViewController in the interfacebuilder
// MiniGameViewController is the CLASS name of the ViewController.swift file acosiated to the ViewController
var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MiniGameView") as MiniGameViewController
var rootViewController = self.window!.rootViewController
rootViewController?.presentViewController(setViewController, animated: false, completion: nil)
This worked fine for me when i put it in AppDelegate
You don't even need to cast, it is implicit.
int i = 3;
float f = i;
A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx
Have you tried this:
import java.io.*;
import java.util.*;
import java.net.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
public class cat{
public static void main (String [] args) throws Exception{
try{
FileSystem fs = FileSystem.get(new Configuration());
FileStatus[] status = fs.listStatus(new Path("hdfs://test.com:9000/user/test/in")); // you need to pass in your hdfs path
for (int i=0;i<status.length;i++){
BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(status[i].getPath())));
String line;
line=br.readLine();
while (line != null){
System.out.println(line);
line=br.readLine();
}
}
}catch(Exception e){
System.out.println("File not found");
}
}
}
I know this post is old but I was getting this error. It turns out World Wide Web Publishing Service was disabled.
If you're working under your feature and don't want to checkout back to master, you can run:
cd ./myrepo
git worktree add ../myrepo_master master
git worktree remove ../myrepo_master
It will create ../myrepo_master
directory with master
branch commits, where you can continue work
import UserNotifications
Next, go to the project editor for your target, and in the General tab, look for the Linked Frameworks and Libraries section.
Click + and select UserNotifications.framework:
// iOS 12 support
if #available(iOS 12, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound, .provisional, .providesAppNotificationSettings, .criticalAlert]){ (granted, error) in }
application.registerForRemoteNotifications()
}
// iOS 10 support
if #available(iOS 10, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
application.registerForRemoteNotifications()
}
// iOS 9 support
else if #available(iOS 9, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 8 support
else if #available(iOS 8, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 7 support
else {
application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
Use Notification delegate methods
// Called when APNs has assigned the device a unique token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Convert token to string
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("APNs device token: \(deviceTokenString)")
}
// Called when APNs failed to register the device for push notifications
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// Print the error to console (you should alert the user that registration failed)
print("APNs registration failed: \(error)")
}
For receiving push notification
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(UIBackgroundFetchResult.noData)
}
Setting up push notifications is enabling the feature within Xcode 8 for your app. Simply go to the project editor for your target and then click on the Capabilities tab. Look for Push Notifications and toggle its value to ON.
Check below link for more Notification delegate methods
Handling Local and Remote Notifications UIApplicationDelegate - Handling Local and Remote Notifications
https://developer.apple.com/reference/uikit/uiapplicationdelegate
First of all understand the mean of "without creating any new extra nodes", As I understand it does not mean that I can not have pointer(s) which points to an existing node(s).
You can not achieve it without talking pointers to existing nodes, even if you use recursion to achieve the same, system will create pointers for you as call stacks. It is just like telling system to add pointers which you have avoided in your code.
Simple function to achieve the same with taking extra pointers:
typedef struct _LLNode{
int value;
struct _LLNode* next;
}LLNode;
LLNode* CombineSortedLists(LLNode* a,LLNode* b){
if(NULL == a){
return b;
}
if(NULL == b){
return a;
}
LLNode* root = NULL;
if(a->value < b->value){
root = a;
a = a->next;
}
else{
root = b;
b = b->next;
}
LLNode* curr = root;
while(1){
if(a->value < b->value){
curr->next = a;
curr = a;
a=a->next;
if(NULL == a){
curr->next = b;
break;
}
}
else{
curr->next = b;
curr = b;
b=b->next;
if(NULL == b){
curr->next = a;
break;
}
}
}
return root;
}
This may seem silly, but in the original question, Turion was editing a plain text file. Make sure you choose the correct language from the Language menu
I use javadoc packaged by Allimant since I was in college.
http://www.allimant.org/javadoc/
The javadoc is in the CHM format (standard windows help format), so it's the best viewed when you're using windows.
for OrderedDict() you can access the elements by indexing by getting the tuples of (key,value) pairs as follows or using '.values()'
>>> import collections
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> d.items()
[('foo', 'python'), ('bar', 'spam')]
>>>d.values()
odict_values(['python','spam'])
>>>list(d.values())
['python','spam']
If the problem is 100% here
EffectSelectorForm effectSelectorForm = new EffectSelectorForm(Effects);
There's only one possible explanation: property/variable "Effects" is not initialized properly... Debug your code to see what you pass to your objects.
EDIT after several hours
There were some problems:
MEF attribute [Import] didn't work as expected, so we replaced it for the time being with a manually populated List<>. While the collection was null, it was causing exceptions later in the code, when the method tried to get the type of the selected item and there was none.
several event handlers weren't wired up to control events
Some problems are still present, but I believe OP's original problem has been fixed. Other problems are not related to this one.
'make' is a command for UNIX/Linux. Instead of it, use 'nmake' command in MS Windows. Or you'd better use an emulator like CYGWIN.
Do you want iteration? itertools.combinations. Common usage:
>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']
If you just need to compute the formula, use math.factorial:
import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
if __name__ == '__main__':
print nCr(4,2)
In Python 3, use the integer division //
instead of /
to avoid overflows:
return f(n) // f(r) // f(n-r)
6
The biggest disadvantage of Text
(together with NText
and Image
) is that it will be removed in a future version of SQL Server, as by the documentation. That will effectively make your schema harder to upgrade when that version of SQL Server will be released.
All those settings are necessary to choose which tags you are interested in, but in order to display these tags in a list, you also need to select the right Eclipse perspective. I finally discovered that the "Markers" tab containing the "Task" list is only available under the "Java EE" perspective... Hope this helps! :-)
The original DateTime field : [_Date_Time]
The converted to Shortdate : 'Short_Date'
CONVERT(date, [_Date_Time]) AS 'Short_Date'
Recently I was playing with this method too. I wrote a memoized algorithm to calcualte Fibonacci numbers which could serve as another illustration on how to use the method.
We can start by defining a map and putting the values in it for the base cases, namely, fibonnaci(0)
and fibonacci(1)
:
private static Map<Integer,Long> memo = new HashMap<>();
static {
memo.put(0,0L); //fibonacci(0)
memo.put(1,1L); //fibonacci(1)
}
And for the inductive step all we have to do is redefine our Fibonacci function as follows:
public static long fibonacci(int x) {
return memo.computeIfAbsent(x, n -> fibonacci(n-2) + fibonacci(n-1));
}
As you can see, the method computeIfAbsent
will use the provided lambda expression to calculate the Fibonacci number when the number is not present in the map. This represents a significant improvement over the traditional, tree recursive algorithm.
class Element
{
public string Company;
public string TypeOfInvestment;
public decimal Worth;
}
class Program
{
static void Main(string[] args)
{
List<Element> elements = new List<Element>()
{
new Element { Company = "JPMORGAN CHASE",TypeOfInvestment = "Stocks", Worth = 96983 },
new Element { Company = "AMER TOWER CORP",TypeOfInvestment = "Securities", Worth = 17141 },
new Element { Company = "ORACLE CORP",TypeOfInvestment = "Assets", Worth = 59372 },
new Element { Company = "PEPSICO INC",TypeOfInvestment = "Assets", Worth = 26516 },
new Element { Company = "PROCTER & GAMBL",TypeOfInvestment = "Stocks", Worth = 387050 },
new Element { Company = "QUASLCOMM INC",TypeOfInvestment = "Bonds", Worth = 196811 },
new Element { Company = "UTD TECHS CORP",TypeOfInvestment = "Bonds", Worth = 257429 },
new Element { Company = "WELLS FARGO-NEW",TypeOfInvestment = "Bank Account", Worth = 106600 },
new Element { Company = "FEDEX CORP",TypeOfInvestment = "Stocks", Worth = 103955 },
new Element { Company = "CVS CAREMARK CP",TypeOfInvestment = "Securities", Worth = 171048 },
};
//Group by on multiple column in LINQ (Query Method)
var query = from e in elements
group e by new{e.TypeOfInvestment,e.Company} into eg
select new {eg.Key.TypeOfInvestment, eg.Key.Company, Points = eg.Sum(rl => rl.Worth)};
foreach (var item in query)
{
Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Points.ToString());
}
//Group by on multiple column in LINQ (Lambda Method)
var CompanyDetails =elements.GroupBy(s => new { s.Company, s.TypeOfInvestment})
.Select(g =>
new
{
company = g.Key.Company,
TypeOfInvestment = g.Key.TypeOfInvestment,
Balance = g.Sum(x => Math.Round(Convert.ToDecimal(x.Worth), 2)),
}
);
foreach (var item in CompanyDetails)
{
Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Balance.ToString());
}
Console.ReadLine();
}
}
Python
element.get_attribute("attribute name")
Java
element.getAttribute("attribute name")
Ruby
element.attribute("attribute name")
C#
element.GetAttribute("attribute name");
You can also use named arguments which are optional and can be given in any order.
Set namedArguments = WScript.Arguments.Named
Here's a little helper function:
Function GetNamedArgument(ByVal argumentName, ByVal defaultValue)
If WScript.Arguments.Named.Exists(argumentName) Then
GetNamedArgument = WScript.Arguments.Named.Item(argumentName)
Else
GetNamedArgument = defaultValue
End If
End Function
Example VBS:
'[test.vbs]
testArg = GetNamedArgument("testArg", "-unknown-")
wscript.Echo now &": "& testArg
Example Usage:
test.vbs /testArg:123
You can use onlinefontconverter.com site. It works fine and have plenty of output formats (afm bin cff dfont eot pfa pfb pfm ps pt3 suit svg t42 tfm ttc ttf woff). One of the advantages I saw, is that it export all the fonts contained inside the ttc at once (which is very convenient).
You can do it in a single query:
Select t.Id, t.title, z.dupCount
From yourtable T
Join
(select title, Count (*) dupCount
from yourtable
group By title
Having Count(*) > 1) z
On z.title = t.Title
order By dupCount Desc
My simple fix it turned out to be calling the form's Activate()
method, so there's no need to use TopMost
(which is what I was aiming at).
First, don't use update panels. They are the second most evil thing that Microsoft has ever created for the web developer.
Second, if you must use update panels, try setting the UpdateMode property to Conditional. Then add a trigger to an Asp:Hidden control that you add to the page. Assign the change event as the trigger. In your dragstop event, change the value of the hidden control.
This is untested, but the theory seems sound... If this does not work, you could try the same thing with an asp:button, just set the display:none style on it and use the click event instead of the change event.
Just use the Distinct()
with your own comparer.
here is a code with confirm exit:
@Override
public void onBackPressed()
{
if(webView.canGoBack()){
webView.goBack();
}else{
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit!")
.setMessage("Are you sure you want to close?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
This is my C version:
void mergesort(int *a, int len) {
int temp, listsize, xsize;
for (listsize = 1; listsize <= len; listsize*=2) {
for (int i = 0, j = listsize; (j+listsize) <= len; i += (listsize*2), j += (listsize*2)) {
merge(& a[i], listsize, listsize);
}
}
listsize /= 2;
xsize = len % listsize;
if (xsize > 1)
mergesort(& a[len-xsize], xsize);
merge(a, listsize, xsize);
}
void merge(int *a, int sizei, int sizej) {
int temp;
int ii = 0;
int ji = sizei;
int flength = sizei+sizej;
for (int f = 0; f < (flength-1); f++) {
if (sizei == 0 || sizej == 0)
break;
if (a[ii] < a[ji]) {
ii++;
sizei--;
}
else {
temp = a[ji];
for (int z = (ji-1); z >= ii; z--)
a[z+1] = a[z];
ii++;
a[f] = temp;
ji++;
sizej--;
}
}
}
The Bitmap class is an implementation of the Image class. The Image class is an abstract class;
The Bitmap class contains 12 constructors that construct the Bitmap object from different parameters. It can construct the Bitmap from another bitmap, and the string address of the image.
See more in this comprehensive sample.
Sometimes diff
is the utility you need, but sometimes join
is more appropriate. The files need to be pre-sorted or, if you are using a shell which supports process substitution such as bash, ksh or zsh, you can do the sort on the fly.
join -v 1 <(sort file1) <(sort file2)
To further my answer, UPS and FedEx can not deliver to a PO BOX not without using the USPS as final handler. Most shipping software out there will not allow a PO Box zip for their standard services. Examples of PO Box zips are 00604 - RAMEY, PR and 06141 - HARTFORD, CT.
The the whole need to validate zip codes can really be a question of how far do you go, what is the budget, what is the time line.
Like anything with expressions test, test, test, and test again. I had an expression for State validation and found that YORK passed when it should fail. The one time in thousands someone entered New York, New York 10279, ugh.
Also keep in mind, USPS does not like punctuation such as N. Market St. and also has very specific acceptable abbreviations for things like Lane, Place, North, Corporation and the like.
&
is the Bash equivalent for ;
( run commands) and &&
is the Bash equivalent of &&
(run commands only when the previous has not caused an error).
Have you considered using:
where('date', '<', '2014-08-11')
You should avoid using the DATE()
function on indexed columns in MySQL, as this prevents the engine from using the index.
UPDATE
As there seems to be some disagreement about the importance of DATE()
and indexes, I have created a fiddle that demonstrates the difference, see POSSIBLE KEYS
.
Firstly you must define select2 like this:
$('#id').select2({
placeholder: "Select groups...",
allowClear: true,
width: '100%',
})
To reset select2, simply you may use the following code block:
$("#id > option").removeAttr("selected");
$("#id").trigger("change");
In polyfills.ts
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es7/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/weak-set';
import 'core-js/es6/set';
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import 'classlist.js'; // Run `npm install --save classlist.js`.
/** Evergreen browsers require these. **/
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
/**
* Required to support Web Animations `@angular/animation`.
* Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation
**/
import 'web-animations-js'; // Run `npm install --save web-animations-js`.
With Linq
var newList = GlobalStrings.Append(localStrings)
You can create a directory inside the camera folder and save the image. After that, you can simply perform your scan. It will instantly show your image in the gallery.
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString()+ "/Camera/Your_Directory_Name";
File myDir = new File(root);
myDir.mkdirs();
String fname = "Image-" + image_name + ".png";
File file = new File(myDir, fname);
System.out.println(file.getAbsolutePath());
if (file.exists()) file.delete();
Log.i("LOAD", root + fname);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(context, new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
Ted Hopp is correct, from the API Documentation :
public void copyPixelsToBuffer (Buffer dst)
"... After this method returns, the current position of the buffer is updated: the position is incremented by the number of elements written in the buffer. "
and
public ByteBuffer get (byte[] dst, int dstOffset, int byteCount)
"Reads bytes from the current position into the specified byte array, starting at the specified offset, and increases the position by the number of bytes read."
This can be quite easily achieved using the ProcessStartInfo.RedirectStandardOutput property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.
Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();
Console.WriteLine(compiler.StandardOutput.ReadToEnd());
compiler.WaitForExit();
Instead of stripping out the found character by its sole position, using Replace(Column, BadFoundCharacter, '')
could be substantially faster. Additionally, instead of just replacing the one bad character found next in each column, this replaces all those found.
WHILE 1 = 1 BEGIN
UPDATE dbo.YourTable
SET Column = Replace(Column, Substring(Column, PatIndex('%[^0-9.-]%', Column), 1), '')
WHERE Column LIKE '%[^0-9.-]%'
If @@RowCount = 0 BREAK;
END;
I am convinced this will work better than the accepted answer, if only because it does fewer operations. There are other ways that might also be faster, but I don't have time to explore those right now.
And if you are using python 3.X, you may apply the sorted
function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.
# using *sort method*
mylist.sort(lambda x: x[1])
# using *sorted function*
sorted(mylist, key = lambda x: x[1])
I would also like to point out that in case you are using command line arguments as part of a shell script (.sh file), then within the script, you would need to enclose the argument in quotes. So if your command looks like
>scriptName.sh arg1 arg2
And arg1 is your path that has spaces, then within the shell script, you would need to refer to it as "$arg1" instead of $arg1
Try this code
var path: String = NSBundle.mainBundle().pathForResource("nameOfFile", ofType: "svg")!
var url: NSURL = NSURL.fileURLWithPath(path) //Creating a URL which points towards our path
//Creating a page request which will load our URL (Which points to our path)
var request: NSURLRequest = NSURLRequest(URL: url)
webView.loadRequest(request) //Telling our webView to load our above request
Pretty sure you can't do that, as it violates the purpose of uniques.
However, this person seems to have a decent work around: http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html
With existing Hamcrest libraries (as of v.2.0.0.0) you are forced to use Collection.toArray() method on your Collection in order to use containsInAnyOrder Matcher. Far nicer would be to add this as a separate method to org.hamcrest.Matchers:
public static <T> org.hamcrest.Matcher<java.lang.Iterable<? extends T>> containsInAnyOrder(Collection<T> items) {
return org.hamcrest.collection.IsIterableContainingInAnyOrder.<T>containsInAnyOrder((T[]) items.toArray());
}
Actually I ended up adding this method to my custom test library and use it to increase readability of my test cases (due to less verbosity).
Old question but here is the approach we have used ever since Visual Studio 2005 with success. I just tested it using Visual Studio 2012 Update 4 as well (since we are finally updating our software from 2010 to 2012).
Since the Visual C++ Redistributable packages register their uninstaller with windows (so it shows up in the Control Panel "Programs and Features" list), we simply check for the Display Name of the uninstaller key in the registry.
Here is the relevant NSIS code:
ReadRegStr $0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{33d1fd90-4274-48a1-9bc1-97e33d9c2d6f}\" "DisplayName"
StrCmp $0 "Microsoft Visual C++ 2012 Redistributable (x86) - 11.0.61030" vs2012redistInstalled
DetailPrint "Microsoft Visual C++ 2012 Update 4 Redistributable not found!"
DetailPrint "Downloading from www.mywebsite.com"
; insert applicable download code here
ExecWait '"<downloaded redist exe>" /promptrestart /passive'
vs2012redistInstalled:
Note that since our installer is a 32bit exe, windows handles determining if the registry key is actually in the virtualized Wow6432Node instead of the above location so the above code works on both 64bit and 32bit windows installs without having to check both keys explicitly.
Also note that to update the above code to a different version of the VC++ Redist, simply change the GUID in the registry key path and the display name to whatever you need.
While this may not be the recommended method, It has worked on 10,000+ machines over the past 10 years running every flavor of windows from XP/XP64 Through Windows 10 using redists for 2005, 2010, 2010sp1, and now 2012u4.
Adding to @David Roussel answer, classes may be loaded by multiple class loaders.
Lets understand how class loader works.
From javin paul blog in javarevisited :
ClassLoader
follows three principles.
A class is loaded in Java, when its needed. Suppose you have an application specific class called Abc.class, first request of loading this class will come to Application ClassLoader which will delegate to its parent Extension ClassLoader which further delegates to Primordial or Bootstrap class loader
Bootstrap ClassLoader is responsible for loading standard JDK class files from rt.jar and it is parent of all class loaders in Java. Bootstrap class loader don't have any parents.
Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property
System or Application class loader and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.
Application class loader is a child of Extension ClassLoader and its implemented by sun.misc.Launcher$AppClassLoader
class.
NOTE: Except Bootstrap class loader, which is implemented in native language mostly in C, all Java class loaders are implemented using java.lang.ClassLoader
.
According to visibility principle, Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true.
According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again
If you aren’t using Auto Layout, have you tried setting the child view’s autoresize mask? Try this:
myChildeView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight);
Also, you may need to call
myParentView.autoresizesSubviews = YES;
to get the parent view to resize its subviews automatically when its frame changes.
If you’re still seeing the child view drawing outside of the parent view’s frame, there’s a good chance that the parent view is not clipping its contents. To fix that, call
myParentView.clipsToBounds = YES;
Use git reflog
to find the hashes of previously checked out commits.
A shortcut command to get to your last checked out branch (not sure if this work correctly with detached HEAD and intermediate commits though) is git checkout -
Well, I would do it like this:
select datediff(minute,'1990-1-1',datetime)
where '1990-1-1' is an arbitrary base datetime.
You can go to AdoptOpenJDK to download your binaries for all platforms provided by a great community.
If you run npm config edit
, you'll get an editor showing the current configuration, and also a list of options and their default values.
But I don't think there's a 'reset' command.
you can always use loadash functions ,like _.nil or _.undefined .They are pretty good to use.
If you know how to launch your program from the command line then you can run it from the platformio-ide-terminal
package's terminal. See platformio-ide-terminal
provides an embedded terminal within the Atom text editor. So you can issue commands, including commands to run your Java program, from within it. To install this package you can use APM with the command:
$ apm install platformio-ide-terminal --no-confirm
Alternatively, you can install it from the command palette with:
platformio-ide-terminal
. In Java 8 to get all your properties
public static Map<String, String> readPropertiesFile(String location) throws Exception {
Map<String, String> properties = new HashMap<>();
Properties props = new Properties();
props.load(new FileInputStream(new File(location)));
props.forEach((key, value) -> {
properties.put(key.toString(), value.toString());
});
return properties;
}
Are you sure you need a list in this case? If you are populating the list with many items, performance will suffer with myList.Contains
or myList.Any
; the run-time will be quadratic. You might want to consider using a better data structure. For example,
public class MyClass
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
public class MyClassComparer : EqualityComparer<MyClass>
{
public override bool Equals(MyClass x, MyClass y)
{
if(x == null || y == null)
return x == y;
return x.Property1 == y.Property1 && x.Property2 == y.Property2;
}
public override int GetHashCode(MyClass obj)
{
return obj == null ? 0 : (obj.Property1.GetHashCode() ^ obj.Property2.GetHashCode());
}
}
You could use a HashSet in the following manner:
var set = new HashSet<MyClass>(new MyClassComparer());
foreach(var myClass in ...)
set.Add(myClass);
Of course, if this definition of equality for MyClass
is 'universal', you needn't write an IEqualityComparer
implementation; you could just override GetHashCode
and Equals
in the class itself.
You can write in this way
<string name="you_me">You & Me<string>
Output: You & Me
Best approach is to import image in js file and use it. Adding images in public folder have some downside:
Files inside public folder not get minified or post-processed,
You can't use hashed name (need to set in webpack config) for images , if you do then you have to change names again and again,
Can't find files at runtime (compilation), result in 404 error at client side.
I don't think the status bar color has been implemented in AppCompat yet. These are the attributes which are available:
<!-- ============= -->
<!-- Color palette -->
<!-- ============= -->
<!-- The primary branding color for the app. By default, this is the color applied to the
action bar background. -->
<attr name="colorPrimary" format="color" />
<!-- Dark variant of the primary branding color. By default, this is the color applied to
the status bar (via statusBarColor) and navigation bar (via navigationBarColor). -->
<attr name="colorPrimaryDark" format="color" />
<!-- Bright complement to the primary branding color. By default, this is the color applied
to framework controls (via colorControlActivated). -->
<attr name="colorAccent" format="color" />
<!-- The color applied to framework controls in their normal state. -->
<attr name="colorControlNormal" format="color" />
<!-- The color applied to framework controls in their activated (ex. checked) state. -->
<attr name="colorControlActivated" format="color" />
<!-- The color applied to framework control highlights (ex. ripples, list selectors). -->
<attr name="colorControlHighlight" format="color" />
<!-- The color applied to framework buttons in their normal state. -->
<attr name="colorButtonNormal" format="color" />
<!-- The color applied to framework switch thumbs in their normal state. -->
<attr name="colorSwitchThumbNormal" format="color" />
(From \sdk\extras\android\support\v7\appcompat\res\values\attrs.xml)
Center x = x + 1/2 of width
Center y = y + 1/2 of height
If you know the width and height already then you only need one set of coordinates.
You have a couple of problems here.
First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.
Change:
<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/>
To:
<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/>
And:
Stock
Stock
So:
<xsd:element name="Stock">
<xsd:complexType>
To:
<xsd:complexType name="Stock">
Make sure you fix the xml closing tags.
The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:
INCORRECT: (the way you showed it)
<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
.....xmlns:external="http://stock.com/schemas/services/stock"
<import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
<message name="getStockQuoteResp">
<part name="parameters" element="external:getStockQuoteResponse" />
</message>
</definitions>
CORRECT:
<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
.....xmlns:external="http://stock.com/schemas/services/stock"
<types>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
<import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />
</schema>
</types>
<message name="getStockQuoteResp">
<part name="parameters" element="external:getStockQuoteResponse" />
</message>
</definitions>
SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.
It would be better if you go the WS-I way when it comes to WSDL authoring.
Other issues may be related to the use of relative vs. absolute URIs in locating external content.
just add your <script src="./custom.js"></script>
before </bod>
tag. that is supply time to d3.select(#chart)
detect your #chart
element in html body
function for sql server:
CREATE function NTSGetCinC(@Cadena nvarchar(4000), @UnChar nvarchar(100))
Returns int
as
begin
declare @t1 int
declare @t2 int
declare @t3 int
set @t1 = len(@Cadena)
set @t2 = len(replace(@Cadena,@UnChar,''))
set @t3 = len(@UnChar)
return (@t1 - @t2) / @t3
end
Code for visual basic and others:
Public Function NTSCuentaChars(Texto As String, CharAContar As String) As Long
NTSCuentaChars = (Len(Texto) - Len(Replace(Texto, CharAContar, ""))) / Len(CharAContar)
End Function
This is how I solved it based on this post with some minor tweaks. This solution does not require creation of any additional classes.
SSLContext sc = SSLContext.getInstance("SSLv3");
KeyManagerFactory kmf =
KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );
KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
ks.load(new FileInputStream( certPath ), certPasswd.toCharArray() );
kmf.init( ks, certPasswd.toCharArray() );
sc.init( kmf.getKeyManagers(), null, null );
((BindingProvider) webservicePort).getRequestContext()
.put(
"com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
sc.getSocketFactory() );
Switch is not same as if-else-if.
Switch is used when there is one expression that gets evaluated to a value and that value can be one of predefined set of values. If you need to perform multiple boolean / comparions operations run-time then if-else-if needs to be used.
I was getting this error when executing in python3,I got the same program working by simply executing in python2
I use this:
public class ReversedView<E> extends AbstractList<E>{
public static <E> List<E> of(List<E> list) {
return new ReversedView<>(list);
}
private final List<E> backingList;
private ReversedView(List<E> backingList){
this.backingList = backingList;
}
@Override
public E get(int i) {
return backingList.get(backingList.size()-i-1);
}
@Override
public int size() {
return backingList.size();
}
}
like this:
ReversedView.of(backingList) // is a fully-fledged generic (but read-only) list
The possible options are described below:
1. First option: sscanf()
#include <cstdio>
#include <string>
int i;
float f;
double d;
std::string str;
// string -> integer
if(sscanf(str.c_str(), "%d", &i) != 1)
// error management
// string -> float
if(sscanf(str.c_str(), "%f", &f) != 1)
// error management
// string -> double
if(sscanf(str.c_str(), "%lf", &d) != 1)
// error management
This is an error (also shown by cppcheck) because "scanf without field width limits can crash with huge input data on some versions of libc" (see here, and here).
2. Second option: std::sto*()
#include <iostream>
#include <string>
int i;
float f;
double d;
std::string str;
try {
// string -> integer
int i = std::stoi(str);
// string -> float
float f = std::stof(str);
// string -> double
double d = std::stod(str);
} catch (...) {
// error management
}
This solution is short and elegant, but it is available only on on C++11 compliant compilers.
3. Third option: sstreams
#include <string>
#include <sstream>
int i;
float f;
double d;
std::string str;
// string -> integer
std::istringstream ( str ) >> i;
// string -> float
std::istringstream ( str ) >> f;
// string -> double
std::istringstream ( str ) >> d;
// error management ??
However, with this solution is hard to distinguish between bad input (see here).
4. Fourth option: Boost's lexical_cast
#include <boost/lexical_cast.hpp>
#include <string>
std::string str;
try {
int i = boost::lexical_cast<int>( str.c_str());
float f = boost::lexical_cast<int>( str.c_str());
double d = boost::lexical_cast<int>( str.c_str());
} catch( boost::bad_lexical_cast const& ) {
// Error management
}
However, this is just a wrapper of sstream
, and the documentation suggests to use sstream
for better error management (see here).
5. Fifth option: strto*()
This solution is very long, due to error management, and it is described here. Since no function returns a plain int, a conversion is needed in case of integer (see here for how this conversion can be achieved).
6. Sixth option: Qt
#include <QString>
#include <string>
bool ok;
std::string;
int i = QString::fromStdString(str).toInt(&ok);
if (!ok)
// Error management
float f = QString::fromStdString(str).toFloat(&ok);
if (!ok)
// Error management
double d = QString::fromStdString(str).toDouble(&ok);
if (!ok)
// Error management
Conclusions
Summing up, the best solution is C++11 std::stoi()
or, as a second option, the use of Qt libraries. All other solutions are discouraged or buggy.
Based on suggestions from @jaimedash and @Old_Mortality I found a solution:
DF$Den <- ifelse(DF$Denial1 < 1 & !is.na(DF$Denial1) | DF$Denial2 < 1 &
!is.na(DF$Denial2) | DF$Denial3 < 1 & !is.na(DF$Denial3), "0", "1")
Then to ensure a value of NA if all values of the conditional variables are NA:
DF$Den <- ifelse(is.na(DF$Denial1) & is.na(DF$Denial2) & is.na(DF$Denial3),
NA, DF$Den)
A cookie is simply a short text string that is sent back and forth between the client and the server. You could store name=bob; password=asdfas
in a cookie and send that back and forth to identify the client on the server side. You could think of this as carrying on an exchange with a bank teller who has no short term memory, and needs you to identify yourself for each and every transaction. Of course using a cookie to store this kind information is horrible insecure. Cookies are also limited in size.
Now, when the bank teller knows about his/her memory problem, He/She can write down your information on a piece of paper and assign you a short id number. Then, instead of giving your account number and driver's license for each transaction, you can just say "I'm client 12"
Translating that to Web Servers: The server will store the pertinent information in the session object, and create a session ID which it will send back to the client in a cookie. When the client sends back the cookie, the server can simply look up the session object using the ID. So, if you delete the cookie, the session will be lost.
One other alternative is for the server to use URL rewriting to exchange the session id.
Suppose you had a link - www.myserver.com/myApp.jsp
You could go through the page and rewrite every URL as www.myserver.com/myApp.jsp?sessionID=asdf
or even www.myserver.com/asdf/myApp.jsp
and exchange the identifier that way. This technique is handled by the web application container and is usually turned on by setting the configuration to use cookieless sessions.
The alpha channel defines the transparency value of a color, so any color is 100% transparent as long as the alpha value is 0. Typically this four-channel color type is known as RGBA.
You can specify RGBA in CSS like so:
div {
background: rgba(200, 54, 54, 0.5); /* 50% transparent */
}
Note that not all browsers support RGBA, in which case you can specify a fallback:
div {
background: rgb(200, 54, 54); /* fallback */
background: rgba(200, 54, 54, 0.5); /* 50% transparent */
}
More information regarding browser support and workarounds can be found here.
In your eclipse.ini file simply put
–vm
/home/aniket/jdk1.7.0_11/bin(Your path to JDK 7)
before -vmargs
line.
MySQL 5.7 or newer generates a default temporary password after fresh install.
To use MySQL first you would be required to get that password from the log file which is present at the /var/log/mysqld.log
. So follow the following process:
grep 'temporary password' /var/log/mysqld.log
mysql_secure_installation
The second command is required to change the password for MySQL and also to make certain other changes like removing temporary databases, allow or disallow remote access to root user, delete anonymous users etc…
It might seem like a dirty hack.
grep "^\|highlight1\|highlight2\|highlight3" filename
Which means - match the beginning of the line(^) or highlight1 or highlight2 or highlight3. As a result, you will get highlighted all highlight* pattern matches, even in the same line.
Simply you can find index name and column names of a particular table using below command
SP_HELPINDEX 'tablename'
It work's for me
You use a compound key (a key with more than one attribute) whenever you want to ensure the uniqueness of a combination of several attributes. A single attribute key would not achieve the same thing.
without much ado:
this.router.navigate(['..'], {relativeTo: this.activeRoute, skipLocationChange: true});
parameter '..' makes navigation one level up, i.e. parent :)
They use regular CSS.
Just use your regular font family like this:
font-family: 'Open Sans', sans-serif;
Now you decide what "weight" the font should have by adding
for semi-bold
font-weight:600;
for bold (700)
font-weight:bold;
for extra bold (800)
font-weight:800;
Like this its fallback proof, so if the google font should "fail" your backup font Arial/Helvetica(Sans-serif) use the same weight as the google font.
Pretty smart :-)
Note that the different font weights have to be specifically imported via the link tag url (family query param of the google font url) in the header.
For example the following link will include both weights 400 and 700:
<link href='fonts.googleapis.com/css?family=Comfortaa:400,700'; rel='stylesheet' type='text/css'>
I've used it in the case where something may have gone awry in my @Before method.
public Object obj;
@Before
public void setUp() {
// Do some set up
obj = new Object();
}
@Test
public void testObjectManipulation() {
if(obj == null) {
fail("obj should not be null");
}
// Do some other valuable testing
}
Starting Java 8, there is support for unsigned long (unsigned 64 bits). The way you can use it is:
Long l1 = Long.parseUnsignedLong("17916881237904312345");
To print it, you can not simply print l1, but you have to first:
String l1Str = Long.toUnsignedString(l1)
Then
System.out.println(l1Str);
Neither restclient nor REST console support this but curl does.
The HTTP specification says in section 4.3
A message-body MUST NOT be included in a request if the specification of the request method (section 5.1.1) does not allow sending an entity-body in requests.
Section 5.1.1 redirects us to section 9.x for the various methods. None of them explicitly prohibit the inclusion of a message body. However...
Section 5.2 says
The exact resource identified by an Internet request is determined by examining both the Request-URI and the Host header field.
and Section 9.3 says
The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.
Which together suggest that when processing a GET request, a server is not required to examine anything other that the Request-URI and Host header field.
In summary, the HTTP spec doesn't prevent you from sending a message-body with GET but there is sufficient ambiguity that it wouldn't surprise me if it was not supported by all servers.
It is confusing in the beginning. But it helps in the situations below :
class SomeAction implements Action {
}
// Later in the code.
Class<Action> actionClass = Class.forName("SomeAction");
Action action = actionClass.newInstance();
// Notice you get an Action instance, there was no need to cast.
Since delegates are a 1-to-1 relationship and I might want to use it elsewhere for other reasons, I like to restrict textfield length adding this code within their setup:
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setup()
}
required override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
// your setup...
setMaxLength()
}
let maxLength = 10
private func setMaxLength() {
addTarget(self, action: #selector(textfieldChanged(_:)), for: UIControlEvents.editingChanged)
}
@objc private func textfieldChanged(_ textField: UITextField) {
guard let text = text else { return }
let trimmed = text.characters.prefix(maxLength)
self.text = String(trimmed)
}