There are multiple options available to reuse the existing powerful libraries that are standards based.
If you happen to use D3 in your project, then you can simply invoke:
d3.csv.format
or d3.csv.formatRows
functions to convert an array of objects into csv string.
d3.csv.formatRows
gives you greater control over which properties are converted to csv.
Please refer to d3.csv.format and d3.csv.formatRows wiki pages.
There are other libraries available too like jquery-csv, PapaParse. Papa Parse has no dependencies - not even jQuery.
For jquery based plugins, please check this.
<div style="width: 200px; height: 150px; border: 1px solid black;position:relative">
<div style="width: 100%; height: 50px; border: 1px solid red;position:absolute;bottom:0">
</div>
</div>
After much pulling out of hair I discovered that the foreach
loops were the culprits. What needs to happen is to call EF but return it into an IList<T>
of that target type then loop on the IList<T>
.
Example:
IList<Client> clientList = from a in _dbFeed.Client.Include("Auto") select a;
foreach (RivWorks.Model.NegotiationAutos.Client client in clientList)
{
var companyFeedDetailList = from a in _dbRiv.AutoNegotiationDetails where a.ClientID == client.ClientID select a;
// ...
}
What you are getting is the result of the toString() method of the Object class or, more precisely, the identityHashCode() as uzay95 has pointed out.
"When we create an object in java with new keyword, we are getting a memory address from the OS."
It is important to realize that everything you do in Java is handled by the Java Virtual Machine. It is the JVM that is giving this information. What actually happens in the RAM of the host operating system depends entirely on the implementation of the JRE.
You can create very easy a dropdown from this array (It was a time-consuming task to put this together and test it). We already use this list in some of our apps.
It is very important to store timezone identifiers in your database and not just the timezone offset like "GMT+2", because of Daylight Saving Times.
I updated/corrected the timezones list (also checkout: https://github.com/paptamas/timezones):
<?php
$timezones = array (
'(GMT-11:00) Midway Island' => 'Pacific/Midway',
'(GMT-11:00) Samoa' => 'Pacific/Samoa',
'(GMT-10:00) Hawaii' => 'Pacific/Honolulu',
'(GMT-09:00) Alaska' => 'US/Alaska',
'(GMT-08:00) Pacific Time (US & Canada)' => 'America/Los_Angeles',
'(GMT-08:00) Tijuana' => 'America/Tijuana',
'(GMT-07:00) Arizona' => 'US/Arizona',
'(GMT-07:00) Chihuahua' => 'America/Chihuahua',
'(GMT-07:00) La Paz' => 'America/Chihuahua',
'(GMT-07:00) Mazatlan' => 'America/Mazatlan',
'(GMT-07:00) Mountain Time (US & Canada)' => 'US/Mountain',
'(GMT-06:00) Central America' => 'America/Managua',
'(GMT-06:00) Central Time (US & Canada)' => 'US/Central',
'(GMT-06:00) Guadalajara' => 'America/Mexico_City',
'(GMT-06:00) Mexico City' => 'America/Mexico_City',
'(GMT-06:00) Monterrey' => 'America/Monterrey',
'(GMT-06:00) Saskatchewan' => 'Canada/Saskatchewan',
'(GMT-05:00) Bogota' => 'America/Bogota',
'(GMT-05:00) Eastern Time (US & Canada)' => 'US/Eastern',
'(GMT-05:00) Indiana (East)' => 'US/East-Indiana',
'(GMT-05:00) Lima' => 'America/Lima',
'(GMT-05:00) Quito' => 'America/Bogota',
'(GMT-04:00) Atlantic Time (Canada)' => 'Canada/Atlantic',
'(GMT-04:30) Caracas' => 'America/Caracas',
'(GMT-04:00) La Paz' => 'America/La_Paz',
'(GMT-04:00) Santiago' => 'America/Santiago',
'(GMT-03:30) Newfoundland' => 'Canada/Newfoundland',
'(GMT-03:00) Brasilia' => 'America/Sao_Paulo',
'(GMT-03:00) Buenos Aires' => 'America/Argentina/Buenos_Aires',
'(GMT-03:00) Georgetown' => 'America/Argentina/Buenos_Aires',
'(GMT-03:00) Greenland' => 'America/Godthab',
'(GMT-02:00) Mid-Atlantic' => 'America/Noronha',
'(GMT-01:00) Azores' => 'Atlantic/Azores',
'(GMT-01:00) Cape Verde Is.' => 'Atlantic/Cape_Verde',
'(GMT+00:00) Casablanca' => 'Africa/Casablanca',
'(GMT+00:00) Edinburgh' => 'Europe/London',
'(GMT+00:00) Greenwich Mean Time : Dublin' => 'Etc/Greenwich',
'(GMT+00:00) Lisbon' => 'Europe/Lisbon',
'(GMT+00:00) London' => 'Europe/London',
'(GMT+00:00) Monrovia' => 'Africa/Monrovia',
'(GMT+00:00) UTC' => 'UTC',
'(GMT+01:00) Amsterdam' => 'Europe/Amsterdam',
'(GMT+01:00) Belgrade' => 'Europe/Belgrade',
'(GMT+01:00) Berlin' => 'Europe/Berlin',
'(GMT+01:00) Bern' => 'Europe/Berlin',
'(GMT+01:00) Bratislava' => 'Europe/Bratislava',
'(GMT+01:00) Brussels' => 'Europe/Brussels',
'(GMT+01:00) Budapest' => 'Europe/Budapest',
'(GMT+01:00) Copenhagen' => 'Europe/Copenhagen',
'(GMT+01:00) Ljubljana' => 'Europe/Ljubljana',
'(GMT+01:00) Madrid' => 'Europe/Madrid',
'(GMT+01:00) Paris' => 'Europe/Paris',
'(GMT+01:00) Prague' => 'Europe/Prague',
'(GMT+01:00) Rome' => 'Europe/Rome',
'(GMT+01:00) Sarajevo' => 'Europe/Sarajevo',
'(GMT+01:00) Skopje' => 'Europe/Skopje',
'(GMT+01:00) Stockholm' => 'Europe/Stockholm',
'(GMT+01:00) Vienna' => 'Europe/Vienna',
'(GMT+01:00) Warsaw' => 'Europe/Warsaw',
'(GMT+01:00) West Central Africa' => 'Africa/Lagos',
'(GMT+01:00) Zagreb' => 'Europe/Zagreb',
'(GMT+02:00) Athens' => 'Europe/Athens',
'(GMT+02:00) Bucharest' => 'Europe/Bucharest',
'(GMT+02:00) Cairo' => 'Africa/Cairo',
'(GMT+02:00) Harare' => 'Africa/Harare',
'(GMT+02:00) Helsinki' => 'Europe/Helsinki',
'(GMT+02:00) Istanbul' => 'Europe/Istanbul',
'(GMT+02:00) Jerusalem' => 'Asia/Jerusalem',
'(GMT+02:00) Kyiv' => 'Europe/Helsinki',
'(GMT+02:00) Pretoria' => 'Africa/Johannesburg',
'(GMT+02:00) Riga' => 'Europe/Riga',
'(GMT+02:00) Sofia' => 'Europe/Sofia',
'(GMT+02:00) Tallinn' => 'Europe/Tallinn',
'(GMT+02:00) Vilnius' => 'Europe/Vilnius',
'(GMT+03:00) Baghdad' => 'Asia/Baghdad',
'(GMT+03:00) Kuwait' => 'Asia/Kuwait',
'(GMT+03:00) Minsk' => 'Europe/Minsk',
'(GMT+03:00) Nairobi' => 'Africa/Nairobi',
'(GMT+03:00) Riyadh' => 'Asia/Riyadh',
'(GMT+03:00) Volgograd' => 'Europe/Volgograd',
'(GMT+03:30) Tehran' => 'Asia/Tehran',
'(GMT+04:00) Abu Dhabi' => 'Asia/Muscat',
'(GMT+04:00) Baku' => 'Asia/Baku',
'(GMT+04:00) Moscow' => 'Europe/Moscow',
'(GMT+04:00) Muscat' => 'Asia/Muscat',
'(GMT+04:00) St. Petersburg' => 'Europe/Moscow',
'(GMT+04:00) Tbilisi' => 'Asia/Tbilisi',
'(GMT+04:00) Yerevan' => 'Asia/Yerevan',
'(GMT+04:30) Kabul' => 'Asia/Kabul',
'(GMT+05:00) Islamabad' => 'Asia/Karachi',
'(GMT+05:00) Karachi' => 'Asia/Karachi',
'(GMT+05:00) Tashkent' => 'Asia/Tashkent',
'(GMT+05:30) Chennai' => 'Asia/Calcutta',
'(GMT+05:30) Kolkata' => 'Asia/Kolkata',
'(GMT+05:30) Mumbai' => 'Asia/Calcutta',
'(GMT+05:30) New Delhi' => 'Asia/Calcutta',
'(GMT+05:30) Sri Jayawardenepura' => 'Asia/Calcutta',
'(GMT+05:45) Kathmandu' => 'Asia/Katmandu',
'(GMT+06:00) Almaty' => 'Asia/Almaty',
'(GMT+06:00) Astana' => 'Asia/Dhaka',
'(GMT+06:00) Dhaka' => 'Asia/Dhaka',
'(GMT+06:00) Ekaterinburg' => 'Asia/Yekaterinburg',
'(GMT+06:30) Rangoon' => 'Asia/Rangoon',
'(GMT+07:00) Bangkok' => 'Asia/Bangkok',
'(GMT+07:00) Hanoi' => 'Asia/Bangkok',
'(GMT+07:00) Jakarta' => 'Asia/Jakarta',
'(GMT+07:00) Novosibirsk' => 'Asia/Novosibirsk',
'(GMT+08:00) Beijing' => 'Asia/Hong_Kong',
'(GMT+08:00) Chongqing' => 'Asia/Chongqing',
'(GMT+08:00) Hong Kong' => 'Asia/Hong_Kong',
'(GMT+08:00) Krasnoyarsk' => 'Asia/Krasnoyarsk',
'(GMT+08:00) Kuala Lumpur' => 'Asia/Kuala_Lumpur',
'(GMT+08:00) Perth' => 'Australia/Perth',
'(GMT+08:00) Singapore' => 'Asia/Singapore',
'(GMT+08:00) Taipei' => 'Asia/Taipei',
'(GMT+08:00) Ulaan Bataar' => 'Asia/Ulan_Bator',
'(GMT+08:00) Urumqi' => 'Asia/Urumqi',
'(GMT+09:00) Irkutsk' => 'Asia/Irkutsk',
'(GMT+09:00) Osaka' => 'Asia/Tokyo',
'(GMT+09:00) Sapporo' => 'Asia/Tokyo',
'(GMT+09:00) Seoul' => 'Asia/Seoul',
'(GMT+09:00) Tokyo' => 'Asia/Tokyo',
'(GMT+09:30) Adelaide' => 'Australia/Adelaide',
'(GMT+09:30) Darwin' => 'Australia/Darwin',
'(GMT+10:00) Brisbane' => 'Australia/Brisbane',
'(GMT+10:00) Canberra' => 'Australia/Canberra',
'(GMT+10:00) Guam' => 'Pacific/Guam',
'(GMT+10:00) Hobart' => 'Australia/Hobart',
'(GMT+10:00) Melbourne' => 'Australia/Melbourne',
'(GMT+10:00) Port Moresby' => 'Pacific/Port_Moresby',
'(GMT+10:00) Sydney' => 'Australia/Sydney',
'(GMT+10:00) Yakutsk' => 'Asia/Yakutsk',
'(GMT+11:00) Vladivostok' => 'Asia/Vladivostok',
'(GMT+12:00) Auckland' => 'Pacific/Auckland',
'(GMT+12:00) Fiji' => 'Pacific/Fiji',
'(GMT+12:00) International Date Line West' => 'Pacific/Kwajalein',
'(GMT+12:00) Kamchatka' => 'Asia/Kamchatka',
'(GMT+12:00) Magadan' => 'Asia/Magadan',
'(GMT+12:00) Marshall Is.' => 'Pacific/Fiji',
'(GMT+12:00) New Caledonia' => 'Asia/Magadan',
'(GMT+12:00) Solomon Is.' => 'Asia/Magadan',
'(GMT+12:00) Wellington' => 'Pacific/Auckland',
'(GMT+13:00) Nuku\'alofa' => 'Pacific/Tongatapu'
);
?>
Best result for me so far:
div to be centered:
position: absolute;
top: 50%;
transform: translateY(-50%);
margin: 0 auto;
right: 0;
left: 0;
You need to subscribe to the observable and pass a callback that processes emitted values
this.myService.getConfig().subscribe(val => console.log(val));
Using io.Copy
package main
import (
"io"
"log"
"os"
)
func main () {
// open files r and w
r, err := os.Open("input.txt")
if err != nil {
panic(err)
}
defer r.Close()
w, err := os.Create("output.txt")
if err != nil {
panic(err)
}
defer w.Close()
// do the actual work
n, err := io.Copy(w, r)
if err != nil {
panic(err)
}
log.Printf("Copied %v bytes\n", n)
}
If you don't feel like reinventing the wheel, the io.Copy
and io.CopyN
may serve you well. If you check the source of the io.Copy function, it is nothing but one of the Mostafa's solutions (the 'basic' one, actually) packaged in the Go library. They are using a significantly larger buffer than he is, though.
This way works:
class A
{
struct Wrap
{
A& a;
Wrap(A& aa) aa(a) {}
operator int() { return a.value; }
operator std::string() { stringstream ss; ss << a.value; return ss.str(); }
}
Wrap operator*() { return Wrap(*this); }
};
The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.
>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
In the current version of Sublime Text 2 (Build: 2139), you can set the syntax for all files of a certain file extension using an option in the menu bar. Open a file with the extension you want to set a default for and navigate through the following menus: View -> Syntax -> Open all with current extension as... ->[your syntax choice]
.
Updated 2012-06-28: Recent builds of Sublime Text 2 (at least since Build 2181) have allowed the syntax to be set by clicking the current syntax type in the lower right corner of the window. This will open the syntax selection menu with the option to Open all with current extension as...
at the top of the menu.
Updated 2016-04-19: As of now, this also works for Sublime Text 3.
OK I found it.
=LARGE($E$4:$E$9;A12)
=large(array, k)
Array Required. The array or range of data for which you want to determine the k-th largest value.
K Required. The position (from the largest) in the array or cell range of data to return.
C# in .NET 3.5 using System.DirectoryServices.AccountManagement.
bool valid = false;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
valid = context.ValidateCredentials( username, password );
}
This will validate against the current domain. Check out the parameterized PrincipalContext constructor for other options.
Use slices instead of arrays for reading. For example, io.Reader
accepts a slice, not an array.
Use slicing instead of zero padding.
Example:
buf := make([]byte, 100)
n, err := myReader.Read(buf)
if n == 0 && err != nil {
log.Fatal(err)
}
consume(buf[:n]) // consume() will see an exact (not padded) slice of read data
Why? One almost never needs to update the statistics. Rebuilding an index is even more rarely needed.
OPTIMIZE TABLE tbl;
will rebuild the indexes and do ANALYZE
; it takes time.
ANALYZE TABLE tbl;
is fast for InnoDB to rebuild the stats. With 5.6.6 it is even less needed.
Much more easier from the above. Default alpha attribute is there for button
android:alpha="0.5"
The range is between 0 for complete transparent and 1 for complete opacity.
I had the same problem, in a simple app (with no routing and a simple ng-controller reference) and my controller's constructor did run twice. Finally, I found out that my problem was the following declaration to auto-bootstrap my AngularJS application in my Razor view
<html ng-app="mTest1">
I have also manually bootstrapped it using angular.bootstrap i.e.
angular.bootstrap(document, [this.app.name]);
so removing one of them, it worked for me.
Kotlin version with how much percent do you want to match.
Method call with percent optional argument
isMatchingColor(intColor1, intColor2, 95) // should match color if 95% similar
Method body
private fun isMatchingColor(intColor1: Int, intColor2: Int, percent: Int = 90): Boolean {
val threadSold = 255 - (255 / 100f * percent)
val diffAlpha = abs(Color.alpha(intColor1) - Color.alpha(intColor2))
val diffRed = abs(Color.red(intColor1) - Color.red(intColor2))
val diffGreen = abs(Color.green(intColor1) - Color.green(intColor2))
val diffBlue = abs(Color.blue(intColor1) - Color.blue(intColor2))
if (diffAlpha > threadSold) {
return false
}
if (diffRed > threadSold) {
return false
}
if (diffGreen > threadSold) {
return false
}
if (diffBlue > threadSold) {
return false
}
return true
}
I came to this page because I have sensitive information in my command line parameters, and didn't want them stored in the code repository. I was using System Environment variables to hold the values, which could be set on each build or development machine as needed for each purpose. Environment Variable Expansion works great in Shell Batch processes, but not Visual Studio.
Visual Studio Start Options:
However, Visual Studio wouldn't return the variable value, but the name of the variable.
Example of Issue:
My final solution after trying several here on S.O. was to write a quick lookup for the Environment variable in my Argument Processor. I added a check for % in the incoming variable value, and if it's found, lookup the Environment Variable and replace the value. This works in Visual Studio, and in my Build Environment.
foreach (string thisParameter in args)
{
if (thisParameter.Contains("="))
{
string parameter = thisParameter.Substring(0, thisParameter.IndexOf("="));
string value = thisParameter.Substring(thisParameter.IndexOf("=") + 1);
if (value.Contains("%"))
{ //Workaround for VS not expanding variables in debug
value = Environment.GetEnvironmentVariable(value.Replace("%", ""));
}
This allows me to use the same syntax in my sample batch files, and in debugging with Visual Studio. No account information or URLs saved in GIT.
Example Use in Batch
If you try using:
df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],***unit='s'***))
and receive an error :
"pandas.tslib.OutOfBoundsDatetime: cannot convert input with unit 's'"
This means the DATE_FIELD
is not specified in seconds.
In my case, it was milli seconds - EPOCH time
.
The conversion worked using below:
df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],unit='ms'))
You might get this error message if you've just installed the phpmyadmin package but haven't restarted apache yet; try restarting apache.
private Map<String, String> convertAttributes(final Map<String, Object> attributes) {
final Map<String, String> result = new HashMap<String, String>();
for (final Map.Entry<String, Object> entry : attributes.entrySet()) {
result.put(entry.getKey(), String.valueOf(entry.getValue()));
}
return result;
}
you have to do like this in your project level gradle file
allprojects {
repositories {
jcenter()
maven { url "http://dl.appnext.com/" }
maven { url "https://maven.google.com" }
}
}
For OGG on Windows: Theoraconverter
.NET DDD Sample from Domain-Driven Design Book by Eric Evans can be found here: http://dddsamplenet.codeplex.com
Cheers,
Jakub G
Shameless Plug:
Filepicker.io handles uploading for you and returns a url. It supports drag/drop, cross browser. Also, people can upload from Dropbox/Facebook/Gmail which is super handy on a mobile device.
I needed to have a button handler that created a form post to another application within the client's browser. I landed on this question but didn't see an answer that suited my scenario. This is what I came up with:
protected void Button1_Click(object sender, EventArgs e)
{
var formPostText = @"<html><body><div>
<form method=""POST"" action=""OtherLogin.aspx"" name=""frm2Post"">
<input type=""hidden"" name=""field1"" value=""" + TextBox1.Text + @""" />
<input type=""hidden"" name=""field2"" value=""" + TextBox2.Text + @""" />
</form></div><script type=""text/javascript"">document.frm2Post.submit();</script></body></html>
";
Response.Write(formPostText);
}
You can use below method :
Route::getCurrentRoute()->getPath();
In Laravel version > 6.0, You can use below methods:
$route = Route::current();
$name = Route::currentRouteName();
$action = Route::currentRouteAction();
Create a branch where you are, then switch to master and merge it:
git branch my-temporary-work
git checkout master
git merge my-temporary-work
Firefox and Chrome are different
Chrome ignores the TR's background-color
Example: http://jsfiddle.net/T4NK3R/9SE4p/
<tr style="background-color:#F00">
<td style="background-color:#FFF; border-radius:20px">
</tr>
In FF the TD gets red corners, in Chrome not
This is how it worked for me. For Windows users testing with Bracket and AngularJS
1) Go to your desktop
2) Right click on your desktop and look for "NEW" in the popup drop down dialog box and it will expand
3) Choose Shortcut
4) A dialog box will open
5) Click on Browse and look for Google Chrome.
6) Click Ok->Next->Finish and it will create the google shortcut on your desktop
7) Now Right Click on the Google Chrome icon you just created
8) Click properties
9) Enter this in the target path
"C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security
10) Save it
11) Double click on your newly created chrome shortcut and past your link in the address bar and it will work.
It can also be done the following way.
At first rename local branch, then remote branch.
Renaming the local branch:
If logged in another branch,
git branch -m old_branch new_branch
If logged in the same branch,
git branch -m new_branch
Renaming remote branch:
git push origin :old_branch // Delete the remote branch
git push --set-upstream origin new_branch // Create a new remote branch
I'd like to add a clarification...
A common misunderstanding, in fact one that I had for some time, is that a storyboard segue is triggered by the prepareForSegue:sender:
method. It is not. A storyboard segue will perform, regardless of whether you have implemented a prepareForSegue:sender:
method for that (departing from) view controller.
I learnt this from Paul Hegarty's excellent iTunesU lectures. My apologies but unfortunately cannot remember which lecture.
If you connect a segue between two view controllers in a storyboard, but do not implement a prepareForSegue:sender:
method, the segue will still segue to the target view controller. It will however segue to that view controller unprepared.
Hope this helps.
Another alternative is;
sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP
I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.
Edit**
According to Fernando comment and this link exclamation mark (
!
) will be placed before than-s
parameter:
sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP
char
means exactly one character. You can't assign zero characters to this type.
That means that there is no char value for which String.replace(char, char)
would return a string with a diffrent length.
Relocation R_X86_64_PC32 against undefined symbol , usually happens when LDFLAGS are set with hardening and CFLAGS not .
Maybe just user error:
If you are using -specs=/usr/lib/rpm/redhat/redhat-hardened-ld at link time,
you also need to use -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 at compile time, and as you are compiling and linking at the same time, you need either both, or drop the -specs=/usr/lib/rpm/redhat/redhat-hardened-ld .
Common fixes :
https://bugzilla.redhat.com/show_bug.cgi?id=1304277#c3
https://github.com/rpmfusion/lxdream/blob/master/lxdream-0.9.1-implicit.patch
If you have a number of image resource methods, it is well worth creating a MessageBodyWriter to output the BufferedImage:
@Produces({ "image/png", "image/jpg" })
@Provider
public class BufferedImageBodyWriter implements MessageBodyWriter<BufferedImage> {
@Override
public boolean isWriteable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
return type == BufferedImage.class;
}
@Override
public long getSize(BufferedImage t, Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
return -1; // not used in JAX-RS 2
}
@Override
public void writeTo(BufferedImage image, Class<?> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out) throws IOException, WebApplicationException {
ImageIO.write(image, mt.getSubtype(), out);
}
}
This MessageBodyWriter will be used automatically if auto-discovery is enabled for Jersey, otherwise it needs to be returned by a custom Application sub-class. See JAX-RS Entity Providers for more info.
Once this is set up, simply return a BufferedImage from a resource method and it will be be output as image file data:
@Path("/whatever")
@Produces({"image/png", "image/jpg"})
public Response getFullImage(...) {
BufferedImage image = ...;
return Response.ok(image).build();
}
A couple of advantages to this approach:
For some instrutions, like ALTER TABLE, this is not possible with MySQL, even with transactions (1 and 2).
You only need to force cscript instead wscript. I always use this template. The function ForceConsole() will execute your vbs into cscript, also you have nice alias to print and scan text.
Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"
Call ForceConsole()
Function printf(txt)
WScript.StdOut.WriteLine txt
End Function
Function printl(txt)
WScript.StdOut.Write txt
End Function
Function scanf()
scanf = LCase(WScript.StdIn.ReadLine)
End Function
Function wait(n)
WScript.Sleep Int(n * 1000)
End Function
Function ForceConsole()
If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
WScript.Quit
End If
End Function
Function cls()
For i = 1 To 50
printf ""
Next
End Function
printf " _____ _ _ _____ _ _____ _ _ "
printf "| _ |_| |_ ___ ___| |_ _ _ _| | | __|___ ___|_|___| |_ "
printf "| | | '_| . | | --| | | | . | |__ | _| _| | . | _|"
printf "|__|__|_|_,_|___|_|_|_____|_____|___| |_____|___|_| |_| _|_| "
printf " |_| v1.0"
printl " Enter your name:"
MyVar = scanf
cls
printf "Your name is: " & MyVar
wait(5)
This is a simple one line way to do it:
try {
URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch(IOException e) {
System.out.println(e);
}
Just had to do something incredible similar to this. My code:
public T IsNull<T>(this object value, T nullAlterative)
{
if(value != DBNull.Value)
{
Type type = typeof(T);
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition())
{
type = Nullable.GetUnderlyingType(type);
}
return (T)(type.IsEnum ? Enum.ToObject(type, Convert.ToInt32(value)) :
Convert.ChangeType(value, type));
}
else
return nullAlternative;
}
:focus is when an element is able to accept input - the cursor in a input box or a link that has been tabbed to.
:active is when an element is being activated by a user - the time between when a user presses a mouse button and then releases it.
As per the latest bootstrap v3.3.7 xs-offseting is allowed. See the documentation here bootstrap offseting. So you can use
<div class="col-xs-2 col-xs-offset-1">.col-xs-2 .col-xs-offset-1</div>
Assignment in bash scripts cannot have spaces around the =
and you probably want your date commands enclosed in backticks $()
:
#!/bin/bash
folder="ABC"
useracct='test'
day=$(date "+%d")
month=$(date "+%B")
year=$(date "+%Y")
folderToBeMoved="/users/$useracct/Documents/Archive/Primetime.eyetv"
newfoldername="/Volumes/Media/Network/$folder/$month$day$year"
ECHO "Network is $network" $network
ECHO "day is $day"
ECHO "Month is $month"
ECHO "YEAR is $year"
ECHO "source is $folderToBeMoved"
ECHO "dest is $newfoldername"
mkdir $newfoldername
cp -R $folderToBeMoved $newfoldername
if [-f $newfoldername/Primetime.eyetv]; then rm $folderToBeMoved; fi
With the last three lines commented out, for me this outputs:
Network is
day is 16
Month is March
YEAR is 2010
source is /users/test/Documents/Archive/Primetime.eyetv
dest is /Volumes/Media/Network/ABC/March162010
Converting from java.lang.Object
directly to ArrayList<T>
which has elements of T is not recommended as it can lead to casting Exceptions. The recommended way is to first convert to a primitive array of T
and then use Arrays.asList(T[])
One of the ways how you get entity from a java javax.ws.rs.core.Response
is as follows -
T[] t_array = response.readEntity(object);
ArrayList<T> t_arraylist = Arrays.asList(t_array);
You will still get Unchecked cast warnings.
From what I've read (and please correct me if Im wrong):
Phonegap claim that they started trying to make this but couldn't, so they passed it to the Apache Software Foundation.
Apache in their awesomeness (Long live Apache) fixed it, developed it, and made it supremely awesome.
Now Phonegap are trying to maintain and enhance a copy they took back, but keep stuffing it up.
So, by my thinking, I want a solid and trustworthy dev platform made by seasoned professionals that I can trust, rather than a patched upon sub-version of said. Therefore Id say I am a Cordova developer NOT a Phonegap developer.
Iv also read that in a second desperate attempt to gain popularity and control over the great works of Apache, Phonegap has now been sold under the Adobe flag. You know Adobe, they are the guys who do nothing for free and are so bad at maintaining software life-cycles that their apps need to perform updates every time you blink, and for some reason each of their apps are about 100 times the size you would expect.
I guess that is the summary of my research if I didn't read it wrongly.
And if true, then lets all drop this whole Phonegap nonsense and just stick with Cordova.
First, verify that the mod_rewrite module is installed. Then, be careful to understand how it works, many people get it backwards.
You don't hide urls or extensions. What you do is create a NEW url that directs to the old one, for example
The URL to put on your web site will be yoursite.com/play?m=asdf
or better yet
yoursite.com/asdf
Even though the directory asdf doesn't exist. Then with mod_rewrite installed you put this in .htaccess. Basically it says, if the requested URL is NOT a file and is NOT a directory, direct it to my script:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /play.php [L]
Almost done - now you just have to write some stuff into your PHP script to parse out the new URL. You want to do this so that the OLD ones work too - what you do is maintain a system by which the variable is always exactly the same OR create a database table that correlates the "SEO friendly URL" with the product id. An example might be
/Some-Cool-Video (which equals product ID asdf)
The advantage to this? Search engines will index the keywords "Some Cool Video." asdf? Who's going to search for that?
I can't give you specifics of how to program this, but take the query string, strip off the end
yoursite.com/Some-Cool-Video
turns into "asdf"
Then set the m variable to this
m=asdf
So both URL's will still go to the same product
yoursite.com/play.php?m=asdf
yoursite.com/Some-Cool-Video
mod_rewrite can do lots of other important stuff too, Google for it and get it activated on your server (it's probably already installed.)
When you run the Windows Command Prompt, and type in python
, it starts the Python interpreter.
Typing it again tries to interpret python
as a variable, which doesn't exist and thus won't work:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line
C:\Users\USER>
If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python
is interpreted as a variable, which you have not defined.
You don't say what class you are using, but I'm guessing it is the standard book
. In which case the page clearing is a feature of he class which you can override as Mica suggests, or solve by switching to another class. The standard report
class is similar to book
, or the memoir
class is an improved book
and is very flexible indeed.
The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.
As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:
/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml
The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.
BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is
@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
public void bussinesMethod(){
}
}
No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.
Now in your client code you need to lookup "MyComponentName".
For Mac OS X, save your CSV file in "Windows Comma Separated (.csv)" format.
Some of the answers involve creating a new public
method. Without doing this, use the Lazy<T>
class:
public class ViewModel
{
private Lazy<ObservableCollection<TData>> Data;
async public ViewModel()
{
Data = new Lazy<ObservableCollection<TData>>(GetDataTask);
}
public ObservableCollection<TData> GetDataTask()
{
Task<ObservableCollection<TData>> task;
//Create a task which represents getting the data
return task.GetAwaiter().GetResult();
}
}
To use Data
, use Data.Value
.
In EF Core 5.0, you will be able to define it at entity level also.
[Keyless]
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public int Zip { get; set; }
}
Your code is correct. Kindly mark small correction.
#rightcolumn {
width: 750px;
background-color: #777;
display: block;
**float: left;(wrong)**
**float: right; (corrected)**
border: 1px solid white;
}
Try to use keyup.enter
but make sure to use it inside your input
tag
<input
matInput
placeholder="enter key word"
[(ngModel)]="keyword"
(keyup.enter)="addToKeywords()"
/>
If you want to add html content to your email, url encode your html code for the message body and include it in your mailto link code, but trouble is you can't set the type of the email from this link from plaintext to html, the client using the link needs their mail client to send html emails by default. In case you want to test here is the code for a simple mailto link, with an image wrapped in a link (angular style urls added for visibility):
<a href="mailto:?body=%3Ca%20href%3D%22{{ scope.url }}%22%3E%3Cimg%20src%3D%22{{ scope.url }}%22%20width%3D%22300%22%20%2F%3E%3C%2Fa%3E">
The html tags are url encoded.
Hmmm, perhaps another option would be to use something like sshfs (there an sshfs for Mac too). Once your router is mounted you can just copy the files outright. I'm not sure if that works for your particular application but it's a nice solution to keep handy.
To return true or false depending on whether a checkbox is checked or not, I use this in JQuery
let checkState = $("#checkboxId").is(":checked") ? "true" : "false";
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
to just look at a tables layout from the cli. you would do
desc mytable
or
show table mytable
In my case it was the use of the call_command
module that posed a problem.
I added set DJANGO_SETTINGS_MODULE=mysite.settings
but it didn't work.
I finally found it:
add these lines at the top of the script, and the order matters.
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
import django
django.setup()
from django.core.management import call_command
Something like this (sounds like you just need to change your SMTP server):
String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
to_address[i] = new InternetAddress(to[i]);
i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {
message.addRecipient(Message.RecipientType.TO, to_address[i]);
i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
Hashicorp's https://github.com/mitchellh/mapstructure library does this out of the box:
import "github.com/mitchellh/mapstructure"
mapstructure.Decode(myData, &result)
The second result
parameter has to be an address of the struct.
A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char[] passwordArray = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
I tried to do sudo apt-get install wkhtmltopdf
but without any success.
Instead I recommend you try:
Download the latest executable (.11 rc1) :
wget https://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.11.0_rc1-static-i386.tar.bz2
uncompress it :
tar -vxf wkhtmltopdf-0.11.0_rc1-static-i386.tar.bz2
rename it :
mv wkhtmltopdf-i386 wkhtmltopdf
chmod it to executable :
chmod a+x wkhtmltopdf
place it into /usr/bin :
sudo mv wkhtmltopdf /usr/bin
Please Try This one:
Try Adding input
Css like this:
-webkit-appearance: none;
border-radius: 0;
You should \usepackage{longtable}
.
Usage:
sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");
If you are looking to just do this on YOUR browser (a.k.a. not forcing this on your users), then I would NOT set your code to not utilize the cache. As José said, there is a performance loss.
And I wouldn't turn off caching on IE altogether, because you lose that performance gain for every website you visit. You can tell IE to always refresh from the server for a specific site or browsing session:
Or, for the keyboard-shortcut-philes (like myself) out there..
NOTE OF CAUTION : Having said this... Keep in mind that anytime you develop/test in a different way than the site will be viewed in production, you run the risk of getting mixed results. A good example is this caching issue. We found an issue where IE was caching our Ajax calls and not updating results from a GET method. If we HAD disabled caching in IE, we would have never seen this problem in development, and would have deployed it to production like this.
Using jquery you can do this by following code:
<input type="text" id="tbxEmail" name="Email" placeholder="Some Text"/>
$('#tbxEmail').attr('placeholder','Some New Text');
In addition to @odano 's answer, it seems using d.clear()
is faster if you would like to clear the dict for many times.
import timeit
p1 = '''
d = {}
for i in xrange(1000):
d[i] = i * i
for j in xrange(100):
d = {}
for i in xrange(1000):
d[i] = i * i
'''
p2 = '''
d = {}
for i in xrange(1000):
d[i] = i * i
for j in xrange(100):
d.clear()
for i in xrange(1000):
d[i] = i * i
'''
print timeit.timeit(p1, number=1000)
print timeit.timeit(p2, number=1000)
The result is:
20.0367929935
19.6444659233
So here is the controller code.
public IActionResult AddURLTest()
{
return ViewComponent("AddURL");
}
You can load it using JQuery load method.
$(document).ready (function(){
$("#LoadSignIn").click(function(){
$('#UserControl').load("/Home/AddURLTest");
});
});
source code link
I would tackle the problem like this:
BufferedWriter output;
output = new BufferedWriter(new FileWriter("file.txt", true));
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
output.append(sizeX);
output.append(sizeY);
output.newLine();
output.close();
The true in the FileWriter constructor allows to append.
The method newLine() is provided by BufferedWriter
Could be ok as solution?
You can use the net send command to send a message over a network.
example:
net send * How Are You
you can use the above statement to send a message to all members of your domain.But if you want to send a message to a single user named Mike, you can use
net send mike hello!
this will send hello! to the user named Mike.
Based on @AdilSoomro's great answer. I have come up with this:
@interface MKMapView (ZoomLevel)
- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
zoomLevel:(NSUInteger)zoomLevel
animated:(BOOL)animated;
-(double) getZoomLevel;
@end
@implementation MKMapView (ZoomLevel)
- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
zoomLevel:(NSUInteger)zoomLevel animated:(BOOL)animated {
MKCoordinateSpan span = MKCoordinateSpanMake(0, 360/pow(2, zoomLevel)*self.frame.size.width/256);
[self setRegion:MKCoordinateRegionMake(centerCoordinate, span) animated:animated];
}
-(double) getZoomLevel {
return log2(360 * ((self.frame.size.width/256) / self.region.span.longitudeDelta));
}
@end
DataGridViewColumn column0 = dataGridViewGroup.Columns[0];
DataGridViewColumn column1 = dataGridViewGroup.Columns[1];
column1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
column1.Width = 120;
Easiest way is:
First create a label named label1. Go to label1's events > mouse events > Label1_Mouse Move and write these:
if (e.Button == MouseButtons.Left){
Left += e.X;
Top += e.Y;`
}
read from assets html file
ViewGroup webGroup;
String content = readContent("content/ganji.html");
final WebView webView = new WebView(this);
webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
webGroup.addView(webView);
I recommend using NS_OPTIONS or NS_ENUM. You can read more about it here: http://nshipster.com/ns_enum-ns_options/
Here's an example from my own code using NS_OPTIONS, I have an utility that sets a sublayer (CALayer) on a UIView's layer to create a border.
The h. file:
typedef NS_OPTIONS(NSUInteger, BSTCMBorder) {
BSTCMBOrderNoBorder = 0,
BSTCMBorderTop = 1 << 0,
BSTCMBorderRight = 1 << 1,
BSTCMBorderBottom = 1 << 2,
BSTCMBOrderLeft = 1 << 3
};
@interface BSTCMBorderUtility : NSObject
+ (void)setBorderOnView:(UIView *)view
border:(BSTCMBorder)border
width:(CGFloat)width
color:(UIColor *)color;
@end
The .m file:
@implementation BSTCMBorderUtility
+ (void)setBorderOnView:(UIView *)view
border:(BSTCMBorder)border
width:(CGFloat)width
color:(UIColor *)color
{
// Make a left border on the view
if (border & BSTCMBOrderLeft) {
}
// Make a right border on the view
if (border & BSTCMBorderRight) {
}
// Etc
}
@end
Double check that the foreign keys have exactly the same type as the field you've got in this table. For example, both should be Integer(10), or Varchar (8), even the number of characters.
By looking into SQL SERVER log file in "C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Log\ERRORLOG", it says "Login failed for user 'XXXXX'. Reason: An attempt to login using SQL authentication failed. Server is configured for Windows authentication only. [CLIENT: ]"
The fixing method is to open "Microsoft SQL Server Management Studio" -> Right click the SQL server and then select "Properties" -> Security -> Change the authentication to mixed mode. -> Restart SQL server.
Being a VB.NET programmer that needs to use a C++ program with 50+ exposed functions, and a .h file that sporadically uses the const qualifier, it is difficult to know when to access a variable using ByRef or ByVal.
Of course the program tells you by generating an exception error on the line where you made the mistake, but then you need to guess which of the 2-10 parameters is wrong.
So now I have the distasteful task of trying to convince a developer that they should really define their variables (in the .h file) in a manner that allows an automated method of creating all of the VB.NET function definitions easily. They will then smugly say, "read the ... documentation."
I have written an awk script that parses a .h file, and creates all of the Declare Function commands, but without an indicator as to which variables are R/O vs R/W, it only does half the job.
EDIT:
At the encouragement of another user I am adding the following;
Here is an example of a (IMO) poorly formed .h entry;
typedef int (EE_STDCALL *Do_SomethingPtr)( int smfID, const char* cursor_name, const char* sql );
The resultant VB from my script;
Declare Function Do_Something Lib "SomeOther.DLL" (ByRef smfID As Integer, ByVal cursor_name As String, ByVal sql As String) As Integer
Note the missing "const" on the first parameter. Without it, a program (or another developer) has no Idea the 1st parameter should be passed "ByVal." By adding the "const" it makes the .h file self documenting so that developers using other languages can easily write working code.
For those needing a dynamically added favicon here is what I did with an app initializer:
import { APP_INITIALIZER, FactoryProvider } from '@angular/core'
export function faviconInitFactory () {
return () => {
const link: any = document.querySelector(`link[rel*='icon']`) || document.createElement('link')
link.type = 'image/x-icon'
link.rel = 'shortcut icon'
if (someExpression) {
link.href = 'url' || 'base64'
} else {
link.href = 'url' || 'base64'
}
document.getElementsByTagName('head')[ 0 ].appendChild(link)
}
}
export const FAVICON_INIT_PROVIDER: FactoryProvider = {
provide: APP_INITIALIZER,
multi: true,
useFactory: faviconInitFactory,
deps: []
}
Just remove fav.ico file under src/ and add this. The favicon will be added before app start
If in jquery the dateformat option is not working then we can handle this situation in html page in input field of your date:
<input type="text" data-date-format='yyyy-mm-dd' id="selectdateadmin" class="form-control" required>
_x000D_
And in javascript below this page add your date picker code:
$('#selectdateadmin').focusin( function()_x000D_
{_x000D_
$("#selectdateadmin").datepicker();_x000D_
_x000D_
});
_x000D_
Well, just do what the error message tells you.
Don't call setContentView()
before requestFeature()
.
Note:
As said in comments, for both ActionBarSherlock
and AppCompat
library, it's necessary to call requestFeature()
before super.onCreate()
Just do
openssl x509 -req -days 365 -in server.cer -signkey server.key -out server.crt
There are a thousand and one ways to do it. Here's one using dc
(a reverse-polish desk calculator which supports unlimited precision arithmetic):
dc <<<"$num1 $num2 + p"
But if that's too bash-y for you (or portability matters) you could say
echo $num1 $num2 + p | dc
But maybe you're one of those people who thinks RPN is icky and weird; don't worry! bc
is here for you:
bc <<< "$num1 + $num2"
echo $num1 + $num2 | bc
That said, there are some unrelated improvements you could be making to your script:
#!/bin/bash
num=0
metab=0
for ((i=1; i<=2; i++)); do
for j in output-$i-* ; do # 'for' can glob directly, no need to ls
echo "$j"
# 'grep' can read files, no need to use 'cat'
metab=$(grep EndBuffer "$j" | awk '{sum+=$2} END { print sum/120}')
num=$(( $num + $metab ))
done
echo "$num"
done
As described in Bash FAQ 022, Bash does not natively support floating point numbers. If you need to sum floating point numbers the use of an external tool (like bc
or dc
) is required.
In this case the solution would be
num=$(dc <<<"$num $metab + p")
To add accumulate possibly-floating-point numbers into num
.
This line add in TableView
cell:
static var nib : UINib{
return UINib(nibName: identifier, bundle: nil)
}
static var identifier : String{
return String(describing: self)
}
And register in viewcontroller like
//This line use in viewdid load
tableview.register(TopDealLikedTableViewCell.nib, forCellReuseIdentifier: TopDealLikedTableViewCell.identifier)
// cell for row at indexpath
if let cell = tableView.dequeueReusableCell(withIdentifier:
TopDealLikedTableViewCell.identifier) as? TopDealLikedTableViewCell{
return cell
}
return UITableViewCell()
SELECT Computer.Computer_Name, Application1.Name, Max(Soft.[Version]) as Version1
FROM Application1
inner JOIN Software
ON Application1.ID = Software.Application_Id
cross join Computer
Left JOIN Software_Computer
ON Software_Computer.Computer_Id = Computer.ID and Software_Computer.Software_Id = Software.Id
Left JOIN Software as Soft
ON Soft.Id = Software_Computer.Software_Id
WHERE Computer.ID = 1
GROUP BY Computer.Computer_Name, Application1.Name
You may wish to also consider the class java.util.concurrent.FutureTask
.
If you are using Java 5 or later, FutureTask is a turnkey implementation of "A cancellable asynchronous computation."
There are even richer asynchronous execution scheduling behaviors available in the java.util.concurrent
package (for example, ScheduledExecutorService
), but FutureTask
may have all the functionality you require.
I would even go so far as to say that it is no longer advisable to use the first code pattern you gave as an example ever since FutureTask
became available. (Assuming you are on Java 5 or later.)
I doubt anything is killing the process just because it takes a long time. Killed generically means something from the outside terminated the process, but probably not in this case hitting Ctrl-C since that would cause Python to exit on a KeyboardInterrupt exception. Also, in Python you would get MemoryError exception if that was the problem. What might be happening is you're hitting a bug in Python or standard library code that causes a crash of the process.
If you already have a dataframe, you can extract the metadata (column names and types) from a dataframe (e.g. if you are controlling a BUG which is only triggered with certain inputs and need a empty dummy Dataframe):
colums_and_types <- sapply(df, class)
# prints: "c('col1', 'col2')"
print(dput(as.character(names(colums_and_types))))
# prints: "c('integer', 'factor')"
dput(as.character(as.vector(colums_and_types)))
And then use the read.table
to create the empty dataframe
read.table(text = "",
colClasses = c('integer', 'factor'),
col.names = c('col1', 'col2'))
keys=[i for i in mydictionary.keys()]
or
keys = list(mydictionary.keys())
I think you need the SCHEDULER_ADMIN role to see the dba_scheduler tables (however this may grant you too may rights)
see: http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/schedadmin001.htm
Just do this:
<Window x:class...
...
...
FocusManager.FocusedElement="{Binding ElementName=myTextBox}"
>
<Grid>
<TextBox Name="myTextBox"/>
...
One solution is to use the command line;
mysql -h yourhostname -u username -p databasename < yoursqlfile.sql
Just ensure the path to the SQL file to import is stated explicitly.
In my case, I used this;
mysql -h localhost -u root -p databasename < /home/ejalee/dumps/mysqlfile.sql
Voila! you are good to go.
The shortest version I found is to use the --cat
option of parallel
like below. This version avoids using xargs, only relying on features of parallel
:
cat files.txt | \
parallel -n 500 --lb --pipe --cat rsync --files-from={} user@remote:/dir /dir -avPi
#### Arg explainer
# -n 500 :: split input into chunks of 500 entries
#
# --cat :: create a tmp file referenced by {} containing the 500
# entry content for each process
#
# user@remote:/dir :: the root relative to which entries in files.txt are considered
#
# /dir :: local root relative to which files are copied
Sample content from files.txt
:
/dir/file-1
/dir/subdir/file-2
....
Note that this doesn't use -j 50
for job count, that didn't work on my end here. Instead I've used -n 500
for record count per job, calculated as a reasonable number given the total number of records.
Updated 10-second countdown using Hooks (a new feature proposal that lets you use state and other React features without writing a class. They’re currently in React v16.7.0-alpha).
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
const Clock = () => {
const [currentCount, setCount] = useState(10);
const timer = () => setCount(currentCount - 1);
useEffect(
() => {
if (currentCount <= 0) {
return;
}
const id = setInterval(timer, 1000);
return () => clearInterval(id);
},
[currentCount]
);
return <div>{currentCount}</div>;
};
const App = () => <Clock />;
ReactDOM.render(<App />, document.getElementById('root'));
Depending on the hibernate flush mode that you are using (AUTO
is the default) save
may or may not write your changes to the DB straight away. When you call saveAndFlush
you are enforcing the synchronization of your model state with the DB.
If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save()
and saveAndFlush()
because the select triggers a flush first. See the documention.
Well I tried all the above methods. None worked for me. The following worked for me:
here you go Sir :-)
1
.myElement{
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
2
.myElement{
text-shadow: rgba(0,0,0,.01) 0 0 1px;
}
Typically you need to do 5 things to include a library in your project:
1) Add #include statements necessary files with declarations/interfaces, e.g.:
#include "library.h"
2) Add an include directory for the compiler to look into
-> Configuration Properties/VC++ Directories/Include Directories (click and edit, add a new entry)
3) Add a library directory for *.lib files:
-> project(on top bar)/properties/Configuration Properties/VC++ Directories/Library Directories (click and edit, add a new entry)
4) Link the lib's *.lib files
-> Configuration Properties/Linker/Input/Additional Dependencies (e.g.: library.lib;
5) Place *.dll files either:
-> in the directory you'll be opening your final executable from or into Windows/system32
A few comments:
import sun.misc.*;
Don't do this. It is non-standard and not guaranteed to be the same between implementations. There are other libraries with Base64 conversion available.
byte[] encVal = c.doFinal(Data.getBytes());
You are relying on the default character encoding here. Always specify what character encoding you are using: byte[] encVal = c.doFinal(Data.getBytes("UTF-8"));
Defaults might be different in different places.
As @thegrinner pointed out, you need to explicitly check the length of your byte arrays. If there is a discrepancy, then compare them byte by byte to see where the difference is creeping in.
Though it won't work for numbers, you can check if the lowercase and uppercase values are same or not, For non-alphabetic characters they will be same, You should check for number before this for better usability
if the benefit of using a static-class was not to instantiate an object and using a method then just declare the class as public and this method as static.
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
You can use boost::posix_time::time_duration
to get the time range. E.g like this
boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();
And to get a higher resolution you can change the clock you are using. For example to the boost::posix_time::microsec_clock
, though this can be OS dependent. On Windows, for example, boost::posix_time::microsecond_clock
has milisecond resolution, not microsecond.
An example which is a little dependent on the hardware.
int main(int argc, char* argv[])
{
boost::posix_time::ptime t1 = boost::posix_time::second_clock::local_time();
boost::this_thread::sleep(boost::posix_time::millisec(500));
boost::posix_time::ptime t2 = boost::posix_time::second_clock::local_time();
boost::posix_time::time_duration diff = t2 - t1;
std::cout << diff.total_milliseconds() << std::endl;
boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time();
boost::this_thread::sleep(boost::posix_time::millisec(500));
boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration msdiff = mst2 - mst1;
std::cout << msdiff.total_milliseconds() << std::endl;
return 0;
}
On my win7 machine. The first out is either 0 or 1000. Second resolution. The second one is nearly always 500, because of the higher resolution of the clock. I hope that help a little.
Extern is the keyword you use to declare that the variable itself resides in another translation unit.
So you can decide to use a variable in a translation unit and then access it from another one, then in the second one you declare it as extern and the symbol will be resolved by the linker.
If you don't declare it as extern you'll get 2 variables named the same but not related at all, and an error of multiple definitions of the variable.
This example shows how to you promises instead of callback.
Model.destroy({
where: {
id: 123 //this will be your id that you want to delete
}
}).then(function(rowDeleted){ // rowDeleted will return number of rows deleted
if(rowDeleted === 1){
console.log('Deleted successfully');
}
}, function(err){
console.log(err);
});
Check this link out for more info http://docs.sequelizejs.com/en/latest/api/model/#destroyoptions-promiseinteger
why do these two different operators, [ ]
, and [[ ]]
, return the same result?
x = list(1, 2, 3, 4)
[ ]
provides sub setting operation. In general sub set of any object
will have the same type as the original object. Therefore, x[1]
provides a list. Similarly x[1:2]
is a subset of original list,
therefore it is a list. Ex.
x[1:2]
[[1]] [1] 1
[[2]] [1] 2
[[ ]]
is for extracting an element from the list. x[[1]]
is valid
and extract the first element from the list. x[[1:2]]
is not valid as [[ ]]
does not provide sub setting like [ ]
.
x[[2]] [1] 2
> x[[2:3]] Error in x[[2:3]] : subscript out of bounds
%~dp0 - return the path from where script executed
But, important to know also below one:
%CD% - return the current path in runtime, for example if you get into other folders using "cd folder1", and then "cd folder2", it will return the full path until folder2 and not the original path where script located
#element1 {float:left;}
#element2 {padding-left : 20px; float:left;}
fiddle : http://jsfiddle.net/sKqZJ/
or
#element1 {float:left;}
#element2 {margin-left : 20px;float:left;}
fiddle : http://jsfiddle.net/sKqZJ/1/
or
#element1 {padding-right : 20px; float:left;}
#element2 {float:left;}
fiddle : http://jsfiddle.net/sKqZJ/2/
or
#element1 {margin-right : 20px; float:left;}
#element2 {float:left;}
fiddle : http://jsfiddle.net/sKqZJ/3/
reference : The Difference Between CSS Margins and Padding
preg_replace("/[[:blank:]]+/"," ",$input)
tightVNC 2.5.X and even pre 2.5 supports multi monitor. When you connect, you get a huge virtual monitor. However, this is also has disadvantages. UltaVNC (Tho when I tried it, was buggy in this area) allows you to connect to one huge virtual monitor or just to 1 screen at a time. (With a button to cycle through them) TightVNC also plan to support such a feature.. (When , no idea) This feature is important as if you have large multi monitors and connecting over a reasonably slow link.. The screen updates are just to slow.. Cutting down to one monitor to focus on is desirable.
I like tightVNC, but UltraVNC seems to have a few more features right now..
I have found tightVNC more solid. And that is why I have stuck with it.
I would try both. They both work well, but I imagine one would suite slightly more then the other.
In addition to Daniel Howard's answer, here is what new
does (or at least seems to do):
function New(func) {
var res = {};
if (func.prototype !== null) {
res.__proto__ = func.prototype;
}
var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));
if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {
return ret;
}
return res;
}
While
var obj = New(A, 1, 2);
is equivalent to
var obj = new A(1, 2);
Because I kept finding this page when looking for a way to remove a field using MongoEngine, I guess it might be helpful to post the MongoEngine way here too:
Example.objects.all().update(unset__tags__words=1)
HC-way :)
DECLARE
rt_mytable mytable%ROWTYPE;
CURSOR update_mytable_cursor(p_rt_mytable IN mytable%ROWTYPE) IS
SELECT *
FROM mytable
WHERE ID = p_rt_mytable.ID
FOR UPDATE;
BEGIN
rt_mytable.ID := 1;
rt_mytable.NAME := 'x';
INSERT INTO mytable VALUES (rt_mytable);
EXCEPTION WHEN DUP_VAL_ON_INDEX THEN
<<update_mytable>>
FOR i IN update_mytable_cursor(rt_mytable) LOOP
UPDATE mytable SET
NAME = p_rt_mytable.NAME
WHERE CURRENT OF update_mytable_cursor;
END LOOP update_mytable;
END;
I did that mistake once - embedding PDF files in HTML pages. I will suggest that you use a JavaScript library for displaying the content of the PDF. Like https://github.com/mozilla/pdf.js/
You can also use glob2 to recursively collect all paths (using ** subfolders wildcard) and then use shutil.copyfile, saving the paths
glob2 link: https://code.activestate.com/pypm/glob2/
The to_sql method works for me.
However, keep in mind that the it looks like it's going to be deprecated in favor of SQLAlchemy:
FutureWarning: The 'mysql' flavor with DBAPI connection is deprecated and will be removed in future versions. MySQL will be further supported with SQLAlchemy connectables. chunksize=chunksize, dtype=dtype)
The documentation says:
When you need to set attributes that are also mapped to a JavaScript dot-property (such as href, style, src or event-handlers), favour that mapping instead.
So, just change id, value assignment and you should be done.
If you are certain you want to wait and never get interrupted then use sleep in POSIX or Sleep in Windows. In POSIX sleep takes time in seconds so if you want the time to be shorter there are varieties like usleep()
which uses microseconds. Sleep in Windows takes milliseconds, it is rare you need finer granularity than that.
It may be that you wish to wait a period of time but want to allow interrupts, maybe in the case of an emergency. sleep can be interrupted by signals but there is a better way of doing it in this case.
Therefore I actually found in practice what you do is wait for an event or a condition variable with a timeout.
In Windows your call is WaitForSingleObject
. In POSIX it is pthread_cond_timedwait
.
In Windows you can also use WaitForSingleObjectEx
and then you can actually "interrupt" your thread with any queued task by calling QueueUserAPC
. WaitForSingleObject(Ex) will return a code determining why it exited, so you will know when it returns a "TIMEDOUT" status that it did indeed timeout. You set the Event it is waiting for when you want it to terminate.
With pthread_cond_timedwait
you can signal broadcast the condition variable. (If several threads are waiting on the same one, you will need to broadcast to wake them all up). Each time it loops it should check the condition. Your thread can get the current time and see if it has passed or it can look to see if some condition has been met to determine what to do. If you have some kind of queue you can check it. (Your thread will automatically have a mutex locked that it used to wait on the condition variable, so when it checks the condition it has sole access to it).
I have 2 solutions to resolve your problem
ngDoCheck
to detect object
data changed or not object
to a new memory address by object = Object.create(object)
from parent component.With Python 3.8 this workes for me. For instance to execute a python script within the venv:
import subprocess
import sys
res = subprocess.run([
sys.executable, # venv3.8/bin/python
'main.py', '--help',],
stdout=PIPE,
text=True)
print(res.stdout)
In my case I had installed a new version of netbeans and upgraded from java 7 to 8. The new netbeans had a different version of glassfish, so I opened the properties of my project and pointed it to the right glassfish version and set the jdk to version 8.
On XAMPP use
D:\xampp\apache\bin>httpd -t -D DUMP_VHOSTS
This will yield errors in your configuration of the virtual hosts
You can use the Distinct
method to return an IEnumerable<T>
of distinct items:
var uniqueItems = yourList.Distinct();
And if you need the sequence of unique items returned as a List<T>
, you can add a call to ToList
:
var uniqueItemsList = yourList.Distinct().ToList();
Using Zxing this way requires a user to also install the barcode scanner app, which isn't ideal. What you probably want is to bundle Zxing into your app directly.
I highly recommend using this library: https://github.com/dm77/barcodescanner
It takes all the crazy build issues you're going to run into trying to integrate Xzing or Zbar directly. It uses those libraries under the covers, but wraps them in a very simple to use API.
js-xlsx library makes it easy to convert Excel/CSV files into JSON objects.
Download the xlsx.full.min.js file from here. Write below code on your HTML page Edit the referenced js file link (xlsx.full.min.js) and link of Excel file
<!doctype html>
<html>
<head>
<title>Excel to JSON Demo</title>
<script src="xlsx.full.min.js"></script>
</head>
<body>
<script>
/* set up XMLHttpRequest */
var url = "http://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {
type: "binary"
});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
console.log(XLSX.utils.sheet_to_json(worksheet, {
raw: true
}));
}
oReq.send();
</script>
</body>
</html>
Input:
Output:
Alternatively you can use the Protected Attributes gem, however this defeats the purpose of requiring strong params. However if you're upgrading an older app, Protected Attributes does provide an easy pathway to upgrade until such time that you can refactor the attr_accessible to strong params.
The guys have given the simple solution, which will do be you should have a look at the help - it's good, looks like a lot in one go but it's actually quick to read:
get-help about_Remote_Troubleshooting | more
This is how you can color a specific menu item with color, works for all API levels:
public static void setToolbarMenuItemTextColor(final Toolbar toolbar,
final @ColorRes int color,
@IdRes final int resId) {
if (toolbar != null) {
for (int i = 0; i < toolbar.getChildCount(); i++) {
final View view = toolbar.getChildAt(i);
if (view instanceof ActionMenuView) {
final ActionMenuView actionMenuView = (ActionMenuView) view;
// view children are accessible only after layout-ing
actionMenuView.post(new Runnable() {
@Override
public void run() {
for (int j = 0; j < actionMenuView.getChildCount(); j++) {
final View innerView = actionMenuView.getChildAt(j);
if (innerView instanceof ActionMenuItemView) {
final ActionMenuItemView itemView = (ActionMenuItemView) innerView;
if (resId == itemView.getId()) {
itemView.setTextColor(ContextCompat.getColor(toolbar.getContext(), color));
}
}
}
}
});
}
}
}
}
By doing that you loose the background selector effect, so here is the code to apply a custom background selector to all of the menu item children.
public static void setToolbarMenuItemsBackgroundSelector(final Context context,
final Toolbar toolbar) {
if (toolbar != null) {
for (int i = 0; i < toolbar.getChildCount(); i++) {
final View view = toolbar.getChildAt(i);
if (view instanceof ImageButton) {
// left toolbar icon (navigation, hamburger, ...)
UiHelper.setViewBackgroundSelector(context, view);
} else if (view instanceof ActionMenuView) {
final ActionMenuView actionMenuView = (ActionMenuView) view;
// view children are accessible only after layout-ing
actionMenuView.post(new Runnable() {
@Override
public void run() {
for (int j = 0; j < actionMenuView.getChildCount(); j++) {
final View innerView = actionMenuView.getChildAt(j);
if (innerView instanceof ActionMenuItemView) {
// text item views
final ActionMenuItemView itemView = (ActionMenuItemView) innerView;
UiHelper.setViewBackgroundSelector(context, itemView);
// icon item views
for (int k = 0; k < itemView.getCompoundDrawables().length; k++) {
if (itemView.getCompoundDrawables()[k] != null) {
UiHelper.setViewBackgroundSelector(context, itemView);
}
}
}
}
}
});
}
}
}
}
Here is the helper function also:
public static void setViewBackgroundSelector(@NonNull Context context, @NonNull View itemView) {
int[] attrs = new int[]{R.attr.selectableItemBackgroundBorderless};
TypedArray ta = context.obtainStyledAttributes(attrs);
Drawable drawable = ta.getDrawable(0);
ta.recycle();
ViewCompat.setBackground(itemView, drawable);
}
<link rel="stylesheet" href="/css/style.css" type="text/css">
<link rel="stylesheet" href="/css/print.css" type="text/css" media="print">
In your normal style.css
:
table.tableclassname {
width: 400px;
}
In your print.css
:
table.tableclassname {
width: 16 cm;
}
Just for completeness, the || and && are the conditional version of the | and & operators.
A reference to the ECMA C# Language specification is here.
From the specification:
3 The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is false.
In the |
version both sides are evaluated.
The conditional version short circuits evaluation and so allows for code like:
if (x == null || x.Value == 5)
// Do something
Or (no pun intended) using your example:
if (title == "User greeting" || title == "User name")
// {do stuff}
Array vs. List choice is not so important (considering performance) in the case of storing string objects. Because both array and list will store string object references, not the actual objects.
You use css to change the opacity. To cope with IE you'd need something like:
.opaque {
opacity : 0.3;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";
filter: alpha(opacity=30);
}
But the only problem with this is that it means anything inside the container will also be 0.3 opacity. Thus you'll have to change your HTML to have another container, not inside the transparent one, that holds your content.
Otherwise the png technique, would work. Except you'd need a fix for IE6, which in itself could cause problems.
As per the official installation page of skimage (skimage Installation) : python-skimage package depends on matplotlib, scipy, pil, numpy and six.
So install them first using
sudo apt-get install python-matplotlib python-numpy python-pil python-scipy
Apparently skimage is a part of Cython which in turn is a superset of python and hence you need to install Cython to be able to use skimage.
sudo apt-get install build-essential cython
Now install skimage package using
sudo apt-get install python-skimage
This solved the Import error for me.
As an aside, when trying to diagnose a similar bug I realised that jquery's ajax error callback returns a status of "timeout" if it failed due to a timeout.
Here's an example:
$.ajax({
url: "/ajax_json_echo/",
timeout: 500,
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus); // this will be "timeout"
}
});
These are some pros of the two most used libraries I would have benefit to know before choosing between them.
standalone="no"
? .node
.sourceline
allows to easily get the line of the XML element you are using.There might be performance issues, std::endl
forces a flush of the output stream.
Here is the process that I ended up using. The main tool I used was Inkscape which was able to convert text alright.
Using Adobe Acrobat Pro Actions (formerly Batch Processing) create a custom action to separate PDF pages into separate files. Alternatively you may be able to split up PDFs with GhostScript
/* Extract Pages to Folder */
var re = /.*\/|\.pdf$/ig;
var filename = this.path.replace(re,"");
{
for ( var i = 0; i < this.numPages; i++ )
this.extractPages
({
nStart: i,
nEnd: i,
cPath : filename + "_s" + ("000000" + (i+1)).slice (-3) + ".pdf"
});
};
Using Windows Cmd created batch file to loop through all PDF files in a folder and convert them to SVG
:: ===== SETUP =====
@echo off
CLS
echo Starting SVG conversion...
echo.
:: setup working directory (if different)
REM set "_work_dir=%~dp0"
set "_work_dir=%CD%"
:: setup counter
set "count=1"
:: setup file search and save string
set "_work_x1=pdf"
set "_work_x2=svg"
set "_work_file_str=*.%_work_x1%"
:: setup inkscape commands
set "_inkscape_path=D:\InkscapePortable\App\Inkscape\"
set "_inkscape_cmd=%_inkscape_path%inkscape.exe"
:: ===== FIND FILES IN WORKING DIRECTORY =====
:: Output from DIR last element is single carriage return character.
:: Carriage return characters are directly removed after percent expansion,
:: but not with delayed expansion.
pushd "%_work_dir%"
FOR /f "tokens=*" %%A IN ('DIR /A:-D /O:N /B %_work_file_str%') DO (
CALL :subroutine "%%A"
)
popd
:: ===== CONVERT PDF TO SVG WITH INKSCAPE =====
:subroutine
echo.
IF NOT [%1]==[] (
echo %count%:%1
set /A count+=1
start "" /D "%_work_dir%" /W "%_inkscape_cmd%" --without-gui --file="%~n1.%_work_x1%" --export-dpi=300 --export-plain-svg="%~n1.%_work_x2%"
) ELSE (
echo End of output
)
echo.
GOTO :eof
:: ===== INKSCAPE REFERENCE =====
:: print inkscape help
REM "%_inkscape_cmd%" --help > "%~dp0\inkscape_help.txt"
REM "%_inkscape_cmd%" --verb-list > "%~dp0\inkscape_verb_list.txt"
I realize it is not best practice to manually brute force edit SVG or XML tags or attributes due to potential variations and should use an XML parser instead. However I had a simple issue where the stroke width on one drawing was very small, and on another the font family was being incorrectly identified, so I basically modified the previous Windows Cmd batch script to do a simple find and replace. The only changes were to the search string definitions and changing to call a PowerShell command. The PowerShell command will perform a find and replace and save the modified file with an added suffix. I did find some other references that could be better used to parse or modify the resultant SVG files if some other minor cleanup is needed to be performed.
:: setup file search and save string
set "_work_x1=svg"
set "_work_x2=svg"
set "_work_s2=_mod"
set "_work_file_str=*.%_work_x1%"
powershell -Command "(Get-Content '%~n1.%_work_x1%') | ForEach-Object {$_ -replace 'stroke-width:0.06', 'stroke-width:1'} | ForEach-Object {$_ -replace 'font-family:Times Roman','font-family:Times New Roman'} | Set-Content '%~n1%_work_s2%.%_work_x2%'"
Hope this might help someone
The only way not to capture something is using look-around assertions:
(?<=123-)((apple|banana)(?=-456)|(?=456))
Because even with non-capturing groups (?:…)
the whole regular expression captures their matched contents. But this regular expression matches only apple
or banana
if it’s preceded by 123-
and followed by -456
, or it matches the empty string if it’s preceded by 123-
and followed by 456
.
|Lookaround | Name | What it Does |
-----------------------------------------------------------------------
|(?=foo) | Lookahead | Asserts that what immediately FOLLOWS the |
| | | current position in the string is foo |
-------------------------------------------------------------------------
|(?<=foo) | Lookbehind | Asserts that what immediately PRECEDES the|
| | | current position in the string is foo |
-------------------------------------------------------------------------
|(?!foo) | Negative | Asserts that what immediately FOLLOWS the |
| | Lookahead | current position in the string is NOT foo|
-------------------------------------------------------------------------
|(?<!foo) | Negative | Asserts that what immediately PRECEDES the|
| | Lookbehind | current position in the string is NOT foo|
-------------------------------------------------------------------------
Suppose the pattern you want is abc+d. You want to match the second occurrence of this pattern in a string.
You would construct the following regex:
abc+d.*?(abc+d)
This would match strings of the form: <your-pattern>...<your-pattern>
. Since we're using the reluctant qualifier *? we're safe that there cannot be another match of between the two. Using matcher groups which pretty much all regex implementations provide you would then retrieve the string in the bracketed group which is what you want.
Because one moderator deleted my detailed image-supported answer on this question, just because I copied and pasted from another question, I am forced to put a less detailed answer and I will link the original answer if you want a more visual way to see the solution.
For Visual Studio 2019 and Visual Studio 2017 Users
For People who are missing this old feature in VS2019 (or maybe VS2017) from the old versions of Visual Studio
This feature still available, but it is NOT available by default, you have to install it separately.
see this answer also to see an image associated
https://stackoverflow.com/a/66289543/4390133
(whish that the moderator realized this is the same question and instead of deleting my answer, he could mark one of the questions as duplicated to the other)
Update to create a class-diagram for the whole project
I received a downvote because I did not mention how to generate a diagram for the whole project, here is how to do it (after applying the previous steps)
Preview Selected Items
is enabled in the solution explorer, disabled it temporarily, you can re-enable it lateryou could be shocked by the results to the point that you can change your mind and remove your downvote (please do NOT upvote, it is enough to remove your downvote)
<input type="number" onkeydown="return FilterInput(event)" onpaste="handlePaste(event)" >
function FilterInput(event) {
var keyCode = ('which' in event) ? event.which : event.keyCode;
isNotWanted = (keyCode == 69 || keyCode == 101);
return !isNotWanted;
};
function handlePaste (e) {
var clipboardData, pastedData;
// Get pasted data via clipboard API
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text').toUpperCase();
if(pastedData.indexOf('E')>-1) {
//alert('found an E');
e.stopPropagation();
e.preventDefault();
}
};
If you haven't actually registered any users with your existing format then you would be best to switch to using the BCrypt password encoder instead.
It's a lot less hassle, as you don't have to worry about salt at all - the details are completely encapsulated within the encoder. Using BCrypt is stronger than using a plain hash algorithm and it's also a standard which is compatible with applications using other languages.
There's really no reason to choose any of the other options for a new application.
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,
$this->db->where_in()
ex : $this->db->where_in('id', array('1','2','3'));
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate
$this->db->or_where_in()
ex : $this->db->where_in('id', array('1','2','3'));
I've continued my research and have not found any reasonable way to do this. The Columns property on the DataGrid isn't something I can bind against, in fact it's read only.
Bryan suggested something might be done with AutoGenerateColumns so I had a look. It uses simple .Net reflection to look at the properties of the objects in ItemsSource and generates a column for each one. Perhaps I could generate a type on the fly with a property for each column but this is getting way off track.
Since this problem is so easily sovled in code I will stick with a simple extension method I call whenever the data context is updated with new columns:
public static void GenerateColumns(this DataGrid dataGrid, IEnumerable<ColumnSchema> columns)
{
dataGrid.Columns.Clear();
int index = 0;
foreach (var column in columns)
{
dataGrid.Columns.Add(new DataGridTextColumn
{
Header = column.Name,
Binding = new Binding(string.Format("[{0}]", index++))
});
}
}
// E.g. myGrid.GenerateColumns(schema);
You have to make custom function for html entities:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g,'>').replace(/"/g, '"');
}
Switch to Branch2
git checkout Branch2
Apply the current (Branch2) changes on top of the Branch1 changes, staying in Branch2:
git rebase Branch1
Which would leave you with the desired result in Branch2:
a -- b -- c <-- Master
\
d -- e <-- Branch1
\
d -- e -- f' -- g' <-- Branch2
You can delete Branch1.
Install Postman native app, Chrome extension has been deprecated. (Mine was opening in own window but still ran as Chrome app)
check this out.
String name validation only accept alphabets and spaces
public static boolean validateLetters(String txt) {
String regx = "^[a-zA-Z\\s]+$";
Pattern pattern = Pattern.compile(regx,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(txt);
return matcher.find();
}
I have never encountered a C#->Java conversion tool. The syntax would be easy enough, but the frameworks are dramatically different. Even if there were a tool, I would strongly advise against it. I have worked on several "migration" projects, and can't say emphatically enough that while conversion seems like a good choice, conversion projects always always always turn in to money pits. It's not a shortcut, what you end up with is code that is not readable, and doesn't take advantage of the target language. speaking from personal experience, assume that a rewrite is the cheaper option.
I've just created CloneExtensions
library project. It performs fast, deep clone using simple assignment operations generated by Expression Tree runtime code compilation.
How to use it?
Instead of writing your own Clone
or Copy
methods with a tone of assignments between fields and properties make the program do it for yourself, using Expression Tree. GetClone<T>()
method marked as extension method allows you to simply call it on your instance:
var newInstance = source.GetClone();
You can choose what should be copied from source
to newInstance
using CloningFlags
enum:
var newInstance
= source.GetClone(CloningFlags.Properties | CloningFlags.CollectionItems);
What can be cloned?
Following class/struct members are cloned internally:
How fast it is?
The solution is faster then reflection, because members information has to be gathered only once, before GetClone<T>
is used for the first time for given type T
.
It's also faster than serialization-based solution when you clone more then couple instances of the same type T
.
and more...
Read more about generated expressions on documentation.
Sample expression debug listing for List<int>
:
.Lambda #Lambda1<System.Func`4[System.Collections.Generic.List`1[System.Int32],CloneExtensions.CloningFlags,System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Object,System.Object]],System.Collections.Generic.List`1[System.Int32]]>(
System.Collections.Generic.List`1[System.Int32] $source,
CloneExtensions.CloningFlags $flags,
System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Object,System.Object]] $initializers) {
.Block(System.Collections.Generic.List`1[System.Int32] $target) {
.If ($source == null) {
.Return #Label1 { null }
} .Else {
.Default(System.Void)
};
.If (
.Call $initializers.ContainsKey(.Constant<System.Type>(System.Collections.Generic.List`1[System.Int32]))
) {
$target = (System.Collections.Generic.List`1[System.Int32]).Call ($initializers.Item[.Constant<System.Type>(System.Collections.Generic.List`1[System.Int32])]
).Invoke((System.Object)$source)
} .Else {
$target = .New System.Collections.Generic.List`1[System.Int32]()
};
.If (
((System.Byte)$flags & (System.Byte).Constant<CloneExtensions.CloningFlags>(Fields)) == (System.Byte).Constant<CloneExtensions.CloningFlags>(Fields)
) {
.Default(System.Void)
} .Else {
.Default(System.Void)
};
.If (
((System.Byte)$flags & (System.Byte).Constant<CloneExtensions.CloningFlags>(Properties)) == (System.Byte).Constant<CloneExtensions.CloningFlags>(Properties)
) {
.Block() {
$target.Capacity = .Call CloneExtensions.CloneFactory.GetClone(
$source.Capacity,
$flags,
$initializers)
}
} .Else {
.Default(System.Void)
};
.If (
((System.Byte)$flags & (System.Byte).Constant<CloneExtensions.CloningFlags>(CollectionItems)) == (System.Byte).Constant<CloneExtensions.CloningFlags>(CollectionItems)
) {
.Block(
System.Collections.Generic.IEnumerator`1[System.Int32] $var1,
System.Collections.Generic.ICollection`1[System.Int32] $var2) {
$var1 = (System.Collections.Generic.IEnumerator`1[System.Int32]).Call $source.GetEnumerator();
$var2 = (System.Collections.Generic.ICollection`1[System.Int32])$target;
.Loop {
.If (.Call $var1.MoveNext() != False) {
.Call $var2.Add(.Call CloneExtensions.CloneFactory.GetClone(
$var1.Current,
$flags,
$initializers))
} .Else {
.Break #Label2 { }
}
}
.LabelTarget #Label2:
}
} .Else {
.Default(System.Void)
};
.Label
$target
.LabelTarget #Label1:
}
}
what has the same meaning like following c# code:
(source, flags, initializers) =>
{
if(source == null)
return null;
if(initializers.ContainsKey(typeof(List<int>))
target = (List<int>)initializers[typeof(List<int>)].Invoke((object)source);
else
target = new List<int>();
if((flags & CloningFlags.Properties) == CloningFlags.Properties)
{
target.Capacity = target.Capacity.GetClone(flags, initializers);
}
if((flags & CloningFlags.CollectionItems) == CloningFlags.CollectionItems)
{
var targetCollection = (ICollection<int>)target;
foreach(var item in (ICollection<int>)source)
{
targetCollection.Add(item.Clone(flags, initializers));
}
}
return target;
}
Isn't it quite like how you'd write your own Clone
method for List<int>
?
You could try using a casting operator to convert it to an integer:
$page = (int) $_GET['p'];
if($page == "")
{
$page = 1;
}
if(empty($page) || !$page)
{
setcookie("error", "Invalid page.", time()+3600);
header("location:somethingwentwrong.php");
die();
}
//else continue with code
Open a connection to your server first (SQL IDE) from the home screen. Then use the context menu in the schema tree to run a query that simply selects rows from the selected table. The LIMIT attached to that is to avoid reading too many rows by accident. This limit can be switched off (or adjusted) in the preferences dialog.
This quick way to select rows is however not very flexible. Normally you would run a query (File / New Query Tab) in the editor with additional conditions, like a sort order:
You can also use binding
<TextBlock Text="{Binding MyText}"/>
And set MyText like this:
Public string MyText
{
get{return string.Format("My Text \n Your Text");}
}
Since the count is the intended final value, in your query pass
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get()->result_array();
return count($query);
The count the retuned value
A better solution would be using Kendo ui draw dom to export to pdf-
Suppose the following html file which contains the canvas tag:
<script src="http://kendo.cdn.telerik.com/2017.2.621/js/kendo.all.min.js"></script>
<script type="x/kendo-template" id="page-template">
<div class="page-template">
<div class="header">
</div>
<div class="footer" style="text-align: center">
<h2> #:pageNum# </h2>
</div>
</div>
</script>
<canvas id="myCanvas" width="500" height="500"></canvas>
<button onclick="ExportPdf()">download</button>
Now after that in your script write down the following and it will be done:
function ExportPdf(){
kendo.drawing
.drawDOM("#myCanvas",
{
forcePageBreak: ".page-break",
paperSize: "A4",
margin: { top: "1cm", bottom: "1cm" },
scale: 0.8,
height: 500,
template: $("#page-template").html(),
keepTogether: ".prevent-split"
})
.then(function(group){
kendo.drawing.pdf.saveAs(group, "Exported_Itinerary.pdf")
});
}
And that is it, Write anything in that canvas and simply press that download button all exported into PDF. Here is a link to Kendo UI - http://docs.telerik.com/kendo-ui/framework/drawing/drawing-dom And a blog to better understand the whole process - https://www.cronj.com/blog/export-htmlcss-pdf-using-javascript/
In your example, You don't need to. As a standard programming practice, all variables being referred to inside some code block, say for example try{} catch(){}
, and being referred to outside the block as well, you need to declare the variables outside the try block first e.g.
This is helpful when your equals method call throws some exception e.g. NullPointerException
;
boolean isMatch = false;
try{
isMatch = email1.equals (email2);
}catch(NullPointerException npe){
.....
}
System.out.print("Match=="+isMatch);
if(isMatch){
......
}
Since my related question was removed by a righteous hand after I had killed the whole day searching how to beat the "macro not found or disabled" error, posting here the only syntax that worked for me (application.run didn't, no matter what I tried)
Set objExcel = CreateObject("Excel.Application")
' Didn't run this way from the Modules
'objExcel.Application.Run "c:\app\Book1.xlsm!Sub1"
' Didn't run this way either from the Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Sheet1.Sub1"
' Nor did it run from a named Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Named_Sheet.Sub1"
' Only ran like this (from the Module1)
Set objWorkbook = objExcel.Workbooks.Open("c:\app\Book1.xlsm")
objExcel.Run "Sub1"
Excel 2010, Win 7
This post is now nearly 5 years old! Python-2.7 will stop receiving official updates from python.org in 2020. Also, Python-3.7 has been released. Check out Python-Future on how to make your Python-2 code compatible with Python-3. For updating conda, the documentation now recommends using conda update --all
in each of your conda environments to update all packages and the Python executable for that version. Also, since they changed their name to Anaconda, I don't know if the Windows registry keys are still the same.
There have been no updates to Python(x,y) since June of 2015, so I think it's safe to assume it has been abandoned.
UPDATE: 2016-11-11As @cxw comments below, these answers are for the same bit-versions, and by bit-version I mean 64-bit vs. 32-bit. For example, these answers would apply to updating from 64-bit Python-2.7.10 to 64-bit Python-2.7.11, ie: the same bit-version. While it is possible to install two different bit versions of Python together, it would require some hacking, so I'll save that exercise for the reader. If you don't want to hack, I suggest that if switching bit-versions, remove the other bit-version first.
UPDATES: 2016-05-16PATH
and Registry. After extraction, create a symlink to conda
in your bin
or install conda from PyPI. Then create another symlink called conda-activate
to activate
in the Anaconda/Miniconda root bin folder. Now Anaconda/Miniconda is just like Ruby RVM. Just use conda-activate root
to enable Anaconda/Miniconda.conda update --all
to keep each conda environment updated,$ ln /c/Python33/python.exe python3
).If OP has 2.7.x and wants to install newer version of 2.7.x, then
It is recommended to uninstall any other Python distribution before installing Python(x,y)
Program Files\Enthought
or home\AppData\Local\Enthought\Canopy\App
for all users or per user respectively. Newer installations are updated by using the built in update tool. See their documentation.Other Python 2.7 Installations On Windows, ActivePython 2.7 cannot coexist with other Python 2.7 installations (for example, a Python 2.7 build from python.org). Uninstall any other Python 2.7 installations before installing ActivePython 2.7.
sage -upgrade
command.Anaconda can be updated by using the conda
command:
conda update --all
Anaconda/Miniconda lets users create environments to manage multiple Python versions including Python-2.6, 2.7, 3.3, 3.4 and 3.5. The root Anaconda/Miniconda installations are currently based on either Python-2.7 or Python-3.5.
Anaconda will likely disrupt any other Python installations. Installation uses MSI installer.
[UPDATE: 2016-05-16] Anaconda and Miniconda now use .exe
installers and provide options to disable Windows PATH
and Registry alterations.
Therefore Anaconda/Miniconda can be installed without disrupting existing Python installations depending on how it was installed and the options that were selected during installation. If the .exe
installer is used and the options to alter Windows PATH
and Registry are not disabled, then any previous Python installations will be disabled, but simply uninstalling the Anaconda/Miniconda installation should restore the original Python installation, except maybe the Windows Registry Python\PythonCore
keys.
Anaconda/Miniconda makes the following registry edits regardless of the installation options: HKCU\Software\Python\ContinuumAnalytics\
with the following keys: Help
, InstallPath
, Modules
and PythonPath
- official Python registers these keys too, but under Python\PythonCore
. Also uninstallation info is registered for Anaconda\Miniconda. Unless you select the "Register with Windows" option during installation, it doesn't create PythonCore
, so integrations like Python Tools for Visual Studio do not automatically see Anaconda/Miniconda. If the option to register Anaconda/Miniconda is enabled, then I think your existing Python Windows Registry keys will be altered and uninstallation will probably not restore them.
App\lib\site-packages
and App\Scripts
could be copied to the new installation, but if this didn't work then reinstalling all packages might have been necessary. Use pip list
to see what packages were installed and their versions. Some were installed by PortablePython. Use easy_install pip
to install pip if it wasn't installed.If OP has 2.7.x and wants to install a different version, e.g. <=2.6.x or >=3.x.x, then installing different versions side-by-side is fine. You must choose which version of Python (if any) to associate with *.py
files and which you want on your path, although you should be able to set up shells with different paths if you use BASH. AFAIK 2.7.x is backwards compatible with 2.6.x, so IMHO side-by-side installs is not necessary, however Python-3.x.x is not backwards compatible, so my recommendation would be to put Python-2.7 on your path and have Python-3 be an optional version by creating a shortcut to its executable called python3 (this is a common setup on Linux). The official Python default install path on Windows is
If OP is not updating Python, but merely updating packages, they may wish to look into virtualenv to keep the different versions of packages specific to their development projects separate. Pip is also a great tool to update packages. If packages use binary installers I usually uninstall the old package before installing the new one.
I hope this clears up any confusion.
You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.
import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))
I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse()
and fromstring()
methods.
If I understand what you need, try this:
SELECT id, pass, AVG(val) AS val_1
FROM data_r1
GROUP BY id, pass;
Or, if you want just one row for every id, this:
SELECT d1.id,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 1) as val_1,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 2) as val_2,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 3) as val_3,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 4) as val_4,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 5) as val_5,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 6) as val_6,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id
The reason is that your are defining your imageSegment
outside of a function in your source code (static variable).
In such cases, the initialization cannot include execution of code, like calling a function or allocation a class. Initializer must be a constant whose value is known at compile time.
You can then initialize your static variable inside of your init
method (if you postpone its declaration to init).
On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:
yumdb search from_repo repoid
(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:
http://james.fedorapeople.org/yum/commands/find-repos-of-install.py
As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?
You'll find it in the AppData
folder if you choose to install it in the default location. Otherwise, it will be located at the folder where you installed your Android SDK/platform-tools
folder.
Just in case someone is working with Eclipse
Windows 8.1 OS | Eclipse Idle Luna
Declare top level variable private String username
Eclipse kindly generate a warning on the left of your screen click that warning and couple of suggestions show up, then select generate.
$scope.popoverPostion = function(event){
$scope.pos = '';
if(event.x <= 207 && event.x >= 140){
$scope.pos = 'top';
event.x = '';
}
else if(event.x < 140){
$scope.pos = 'top-left';
event.x = '';
}
else if(event.x > 207){
$scope.pos = 'top-right';
event.x = '';
}
};
You don't need to do it in the foreach
.
Just use count($Contents)
.
This worked for me and does not require background color behind the text to hide a border line, instead uses actual hr tag. You can play around with the widths to get different sizes of hr lines.
<div>
<div style="display:inline-block;width:45%"><hr width='80%' /></div>
<div style="display:inline-block;width: 9%;text-align: center;vertical-align:90%;text-height: 24px"><h4>OR</h4></div>
<div style="display:inline-block;width:45%;float:right" ><hr width='80%'/></div>
</div>
You can try my suggestion for a work around in Doug's approach.
But if you want to stick with your logic though, you can try this:
Option Explicit
Sub GetUnique()
Dim rng As Range
Dim myarray, myunique
Dim i As Integer
ReDim myunique(1)
With ThisWorkbook.Sheets("Sheet1")
Set rng = .Range(.Range("A1"), .Range("A" & .Rows.Count).End(xlUp))
myarray = Application.Transpose(rng)
For i = LBound(myarray) To UBound(myarray)
If IsError(Application.Match(myarray(i), myunique, 0)) Then
myunique(UBound(myunique)) = myarray(i)
ReDim Preserve myunique(UBound(myunique) + 1)
End If
Next
End With
For i = LBound(myunique) To UBound(myunique)
Debug.Print myunique(i)
Next
End Sub
This uses array instead of range.
It also uses Match
function instead of a nested For Loop
.
I didn't have the time to check the time difference though.
So I leave the testing to you.
From the official angular documentation
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
As you can see first parameter for error callback is data an status is second.
<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
<tr bgcolor="#CCC">
<td width="100">xxxxx</td>
<td width="700">xxxxxx</td>
<td width="170">xxxxxx</td>
<td width="30">xxxxxx</td>
</tr>
<tr bgcolor="#FFFFFF">
<td><?php
$date = date_create($row_Recordset3['fecha']);
echo date_format($date, 'd-m-Y');
?></td>
<td><?php echo $row_Recordset3['descripcion']; ?></td>
<td><?php echo $row_Recordset3['producto']; ?></td>
<td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
</tr>
</table>
<input type="hidden" id="datatodisplay" name="datatodisplay">
<input type="submit" value="Export to Excel">
exporttable.php
<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>
You've missed the id out before the NOT; it needs to be specified.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
You do not specify why you think it is wrong but I can se two dangers:
BETWEEN can be implemented differently in different databases sometimes it is including the border values and sometimes excluding, resulting in that 1 and 31 of january would end up NOTHING. You should test how you database does this.
Also, if RATE_DATE contains hours also 2010-01-31 might be translated to 2010-01-31 00:00 which also would exclude any row with an hour other that 00:00.
You can use VBA - something like
Range("A1:A6").Interior.Color = RGB(127,187,199)
Just pass in the cell value.
You can use the <button>
tag. For a submit, simply add type="submit"
. Then use a background image when you want the button to appear as a graphic.
Like so:
<button type="submit" style="border: 0; background: transparent">
<img src="/images/Btn.PNG" width="90" height="50" alt="submit" />
</button>
I have seen JMS used in different commercial and academic projects. JMS can easily come into your picture, whenever you want to have a totally decoupled distributed systems. Generally speaking, when you need to send your request from one node, and someone in your network takes care of it without/with giving the sender any information about the receiver.
In my case, I have used JMS in developing a message-oriented middleware (MOM) in my thesis, where specific types of object-oriented objects are generated in one side as your request, and compiled and executed on the other side as your response.
It's possible to pass multiple parameters as a single model as vijay suggested. This works for GET when you use the FromUri parameter attribute. This tells WebAPI to fill the model from the query parameters.
The result is a cleaner controller action with just a single parameter. For more information see: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
public class BooksController : ApiController
{
// GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
public string GetFindBooks([FromUri]BookQuery query)
{
// ...
}
}
public class BookQuery
{
public string Author { get; set; }
public string Title { get; set; }
public string ISBN { get; set; }
public string SomethingElse { get; set; }
public DateTime? Date { get; set; }
}
It even supports multiple parameters, as long as the properties don't conflict.
// GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
public string GetFindBooks([FromUri]BookQuery query, [FromUri]Paging paging)
{
// ...
}
public class Paging
{
public string Sort { get; set; }
public int Skip { get; set; }
public int Take { get; set; }
}
Update:
In order to ensure the values are optional make sure to use reference types or nullables (ex. int?) for the models properties.
Newer versions of the DOMTokenList spec allow for multiple arguments to add()
and remove()
, as well as a second argument to toggle()
to force state.
At the time of writing, Chrome supports multiple arguments to add()
and remove()
, but none of the other browsers do. IE 10 and lower, Firefox 23 and lower, Chrome 23 and lower and other browsers do not support the second argument to toggle()
.
I wrote the following small polyfill to tide me over until support expands:
(function () {
/*global DOMTokenList */
var dummy = document.createElement('div'),
dtp = DOMTokenList.prototype,
toggle = dtp.toggle,
add = dtp.add,
rem = dtp.remove;
dummy.classList.add('class1', 'class2');
// Older versions of the HTMLElement.classList spec didn't allow multiple
// arguments, easy to test for
if (!dummy.classList.contains('class2')) {
dtp.add = function () {
Array.prototype.forEach.call(arguments, add.bind(this));
};
dtp.remove = function () {
Array.prototype.forEach.call(arguments, rem.bind(this));
};
}
// Older versions of the spec didn't have a forcedState argument for
// `toggle` either, test by checking the return value after forcing
if (!dummy.classList.toggle('class1', true)) {
dtp.toggle = function (cls, forcedState) {
if (forcedState === undefined)
return toggle.call(this, cls);
(forcedState ? add : rem).call(this, cls);
return !!forcedState;
};
}
})();
A modern browser with ES5 compliance and DOMTokenList
are expected, but I'm using this polyfill in several specifically targeted environments, so it works great for me, but it might need tweaking for scripts that will run in legacy browser environments such as IE 8 and lower.
First I think you need to fix your lists, as the first node of a <ul>
must be a <li>
(stackoverflow ref). Once that is setup you can do this:
// note this array has outer scope
var phrases = [];
$('.phrase').each(function(){
// this is inner scope, in reference to the .phrase element
var phrase = '';
$(this).find('li').each(function(){
// cache jquery var
var current = $(this);
// check if our current li has children (sub elements)
// if it does, skip it
// ps, you can work with this by seeing if the first child
// is a UL with blank inside and odd your custom BLANK text
if(current.children().size() > 0) {return true;}
// add current text to our current phrase
phrase += current.text();
});
// now that our current phrase is completely build we add it to our outer array
phrases.push(phrase);
});
// note the comma in the alert shows separate phrases
alert(phrases);
Working jsfiddle.
One thing is if you get the .text()
of an upper level li
you will get all sub level text with it.
Keeping an array will allow for many multiple phrases to be extracted.
EDIT:
This should work better with an empty UL
with no LI
:
// outer scope
var phrases = [];
$('.phrase').each(function(){
// inner scope
var phrase = '';
$(this).find('li').each(function(){
// cache jquery object
var current = $(this);
// check for sub levels
if(current.children().size() > 0) {
// check is sublevel is just empty UL
var emptyULtest = current.children().eq(0);
if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
phrase += ' -BLANK- '; //custom blank text
return true;
} else {
// else it is an actual sublevel with li's
return true;
}
}
// if it gets to here it is actual li
phrase += current.text();
});
phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);
Maybe this will help others in the future - I had the same error while trying to multiple a float and a list of floats. The thing is that everyone here talked about multiplying a float with a string (but here all my element were floats all along) so the problem was actually using the * operator on a list.
For example:
import math
import numpy as np
alpha = 0.2
beta=1-alpha
C = (-math.log(1-beta))/alpha
coff = [0.0,0.01,0.0,0.35,0.98,0.001,0.0]
coff *= C
The error:
coff *= C
TypeError: can't multiply sequence by non-int of type 'float'
The solution - convert the list to numpy array:
coff = np.asarray(coff) * C
I had this issue and implemented lruCache. I believe you need API 12 and above or use the compatiblity v4 library. lurCache is fast memory, but it also has a budget, so if you're worried about that you can use a diskcache... It's all described in Caching Bitmaps.
I'll now provide my implementation which is a singleton I call from anywhere like this:
//Where the first is a string and the other is a imageview to load.
DownloadImageTask.getInstance().loadBitmap(avatarURL, iv_avatar);
Here's the ideal code to cache and then call the above in getView of an adapter when retrieving the web image:
public class DownloadImageTask {
private LruCache<String, Bitmap> mMemoryCache;
/* Create a singleton class to call this from multiple classes */
private static DownloadImageTask instance = null;
public static DownloadImageTask getInstance() {
if (instance == null) {
instance = new DownloadImageTask();
}
return instance;
}
//Lock the constructor from public instances
private DownloadImageTask() {
// Get max available VM memory, exceeding this amount will throw an
// OutOfMemory exception. Stored in kilobytes as LruCache takes an
// int in its constructor.
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
}
public void loadBitmap(String avatarURL, ImageView imageView) {
final String imageKey = String.valueOf(avatarURL);
final Bitmap bitmap = getBitmapFromMemCache(imageKey);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageResource(R.drawable.ic_launcher);
new DownloadImageTaskViaWeb(imageView).execute(avatarURL);
}
}
private void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
private Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
/* A background process that opens a http stream and decodes a web image. */
class DownloadImageTaskViaWeb extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTaskViaWeb(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
}
catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
addBitmapToMemoryCache(String.valueOf(urldisplay), mIcon);
return mIcon;
}
/* After decoding we update the view on the main UI. */
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
For those trying to make the connection between SNR and a normal random variable generated by numpy:
[1] , where it's important to keep in mind that P is average power.
Or in dB:
[2]
In this case, we already have a signal and we want to generate noise to give us a desired SNR.
While noise can come in different flavors depending on what you are modeling, a good start (especially for this radio telescope example) is Additive White Gaussian Noise (AWGN). As stated in the previous answers, to model AWGN you need to add a zero-mean gaussian random variable to your original signal. The variance of that random variable will affect the average noise power.
For a Gaussian random variable X, the average power , also known as the second moment, is
[3]
So for white noise, and the average power is then equal to the variance .
When modeling this in python, you can either
1. Calculate variance based on a desired SNR and a set of existing measurements, which would work if you expect your measurements to have fairly consistent amplitude values.
2. Alternatively, you could set noise power to a known level to match something like receiver noise. Receiver noise could be measured by pointing the telescope into free space and calculating average power.
Either way, it's important to make sure that you add noise to your signal and take averages in the linear space and not in dB units.
Here's some code to generate a signal and plot voltage, power in Watts, and power in dB:
# Signal Generation
# matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(1, 100, 1000)
x_volts = 10*np.sin(t/(2*np.pi))
plt.subplot(3,1,1)
plt.plot(t, x_volts)
plt.title('Signal')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()
x_watts = x_volts ** 2
plt.subplot(3,1,2)
plt.plot(t, x_watts)
plt.title('Signal Power')
plt.ylabel('Power (W)')
plt.xlabel('Time (s)')
plt.show()
x_db = 10 * np.log10(x_watts)
plt.subplot(3,1,3)
plt.plot(t, x_db)
plt.title('Signal Power in dB')
plt.ylabel('Power (dB)')
plt.xlabel('Time (s)')
plt.show()
Here's an example for adding AWGN based on a desired SNR:
# Adding noise using target SNR
# Set a target SNR
target_snr_db = 20
# Calculate signal power and convert to dB
sig_avg_watts = np.mean(x_watts)
sig_avg_db = 10 * np.log10(sig_avg_watts)
# Calculate noise according to [2] then convert to watts
noise_avg_db = sig_avg_db - target_snr_db
noise_avg_watts = 10 ** (noise_avg_db / 10)
# Generate an sample of white noise
mean_noise = 0
noise_volts = np.random.normal(mean_noise, np.sqrt(noise_avg_watts), len(x_watts))
# Noise up the original signal
y_volts = x_volts + noise_volts
# Plot signal with noise
plt.subplot(2,1,1)
plt.plot(t, y_volts)
plt.title('Signal with noise')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()
# Plot in dB
y_watts = y_volts ** 2
y_db = 10 * np.log10(y_watts)
plt.subplot(2,1,2)
plt.plot(t, 10* np.log10(y_volts**2))
plt.title('Signal with noise (dB)')
plt.ylabel('Power (dB)')
plt.xlabel('Time (s)')
plt.show()
And here's an example for adding AWGN based on a known noise power:
# Adding noise using a target noise power
# Set a target channel noise power to something very noisy
target_noise_db = 10
# Convert to linear Watt units
target_noise_watts = 10 ** (target_noise_db / 10)
# Generate noise samples
mean_noise = 0
noise_volts = np.random.normal(mean_noise, np.sqrt(target_noise_watts), len(x_watts))
# Noise up the original signal (again) and plot
y_volts = x_volts + noise_volts
# Plot signal with noise
plt.subplot(2,1,1)
plt.plot(t, y_volts)
plt.title('Signal with noise')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()
# Plot in dB
y_watts = y_volts ** 2
y_db = 10 * np.log10(y_watts)
plt.subplot(2,1,2)
plt.plot(t, 10* np.log10(y_volts**2))
plt.title('Signal with noise')
plt.ylabel('Power (dB)')
plt.xlabel('Time (s)')
plt.show()
You can run your program by: Debug -> Start Without Debugging
. It will keep a console opened after the program will be finished.
Best way to convert your string into int is :
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
int converted=Integer.parseInt(hello);
Create a function as such...
def clear():
os.system('clear')
and then when you get to the bottom of the Python IDLE you can just use
clear()
:)
Here is a good example -
ul li{
list-style-type: disc;
list-style-position: inside;
padding: 10px 0 10px 20px;
text-indent: -1em;
}
Working Demo: http://jsfiddle.net/d9VNk/
You can configure it globally:
git config --global core.filemode false
If the above doesn't work for you, the reason might be your local configuration overrides the global configuration.
Remove your local configuration to make the global configuration take effect:
git config --unset core.filemode
Alternatively, you could change your local configuration to the right value:
git config core.filemode false
"Why do i get that error?" - probably, you don't have "using System.Collections;
" at the top of the file - only "using System.Collections.Generic;
" - however, generics are probably safer - see below:
static bool ArraysEqual<T>(T[] a1, T[] a2)
{
if (ReferenceEquals(a1,a2))
return true;
if (a1 == null || a2 == null)
return false;
if (a1.Length != a2.Length)
return false;
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < a1.Length; i++)
{
if (!comparer.Equals(a1[i], a2[i])) return false;
}
return true;
}
There are various approaches that you can take to accomplish deserialization of a JSON object to an enum. My favorite style is to make an inner class:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.fasterxml.jackson.annotation.JsonFormat.Shape.OBJECT;
@JsonFormat(shape = OBJECT)
public enum FinancialAccountSubAccountType {
MAIN("Main"),
MAIN_DISCOUNT("Main Discount");
private final static Map<String, FinancialAccountSubAccountType> ENUM_NAME_MAP;
static {
ENUM_NAME_MAP = Arrays.stream(FinancialAccountSubAccountType.values())
.collect(Collectors.toMap(
Enum::name,
Function.identity()));
}
private final String displayName;
FinancialAccountSubAccountType(String displayName) {
this.displayName = displayName;
}
@JsonCreator
public static FinancialAccountSubAccountType fromJson(Request request) {
return ENUM_NAME_MAP.get(request.getCode());
}
@JsonProperty("name")
public String getDisplayName() {
return displayName;
}
private static class Request {
@NotEmpty(message = "Financial account sub-account type code is required")
private final String code;
private final String displayName;
@JsonCreator
private Request(@JsonProperty("code") String code,
@JsonProperty("name") String displayName) {
this.code = code;
this.displayName = displayName;
}
public String getCode() {
return code;
}
@JsonProperty("name")
public String getDisplayName() {
return displayName;
}
}
}
You're comparing the message with the empty string using ==
.
First, your comparison is wrong because the message will be null (and not the empty string).
Second, it's wrong because Objects must be compared with equals()
and not with ==
.
Third, it's wrong because you should avoid scriptlets in JSP, and use the JSP EL, the JSTL, and other custom tags instead:
<c:id test="${!empty message}">
<c:out value="${message}"/>
</c:if>
(Is it because this is Java and therefore I shouldn't be doing evil nonportable obsolete things like touching my environment?)
I think you've hit the nail on the head.
A possible way to ease the burden would be to factor out a method
void setUpEnvironment(ProcessBuilder builder) {
Map<String, String> env = builder.environment();
// blah blah
}
and pass any ProcessBuilder
s through it before starting them.
Also, you probably already know this, but you can start more than one process with the same ProcessBuilder
. So if your subprocesses are the same, you don't need to do this setup over and over.
String str1,str2;
Scanner S=new Scanner(System.in);
str1=S.nextLine();
System.out.println(str1);
str2=S.nextLine();
str1=str1.concat(str2);
System.out.println(str1.toLowerCase());
You might have a look at the Symja framework:
ExprEvaluator util = new ExprEvaluator();
IExpr result = util.evaluate("10-40");
System.out.println(result.toString()); // -> "-30"
Take note that definitively more complex expressions can be evaluated:
// D(...) gives the derivative of the function Sin(x)*Cos(x)
IAST function = D(Times(Sin(x), Cos(x)), x);
IExpr result = util.evaluate(function);
// print: Cos(x)^2-Sin(x)^2
I found that
<a href="link/to/My_Image_File.jpeg" download>Download Image File</a>
did not work for me. I'm not sure why.
I have found that you can include a ?download=true
parameter at the end of your link to force a download. I think I noticed this technique being used by Google Drive.
In your link, include ?download=true
at the end of your href.
You can also use this technique to set the filename at the same time.
In your link, include ?download=true&filename=My_Image_File.jpeg
at the end of your href.
You can use the dictionary type of formatting:
s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}
With <button>
, you can use img tags, etc. where text is
<button type='submit'> text -- can be img etc. </button>
with <input>
type, you are limited to text
Your question does not ask for a Python solution, but here is one using PyYAML.
PyYAML allows you to attach custom constructors (such as !include
) to the YAML loader. I've included a root directory that can be set so that this solution supports relative and absolute file references.
Here is a class-based solution, that avoids the global root variable of my original response.
See this gist for a similar, more robust Python 3 solution that uses a metaclass to register the custom constructor.
import yaml
import os
class Loader(yaml.SafeLoader):
def __init__(self, stream):
self._root = os.path.split(stream.name)[0]
super(Loader, self).__init__(stream)
def include(self, node):
filename = os.path.join(self._root, self.construct_scalar(node))
with open(filename, 'r') as f:
return yaml.load(f, Loader)
Loader.add_constructor('!include', Loader.include)
An example:
foo.yaml
a: 1
b:
- 1.43
- 543.55
c: !include bar.yaml
bar.yaml
- 3.6
- [1, 2, 3]
Now the files can be loaded using:
>>> with open('foo.yaml', 'r') as f:
>>> data = yaml.load(f, Loader)
>>> data
{'a': 1, 'b': [1.43, 543.55], 'c': [3.6, [1, 2, 3]]}
Several possiblies that causes this problem. The root cause is mismatched of compiler version between projects and IDE. For windows environment you can refer to this blog to do the detail troubleshooting.
Pressing ctrl+M causes the ? Tab key to move focus instead of inserting a ? Tab character.
Turn it off by pressing the shortcut again.
toggle tab key moves focus
.Remove Keybinding
.I had the same issue:
But the situation was, every time i try to enter:
/usr/local/mysql/support-files/mysql.server start
a file named localhost.pid
is created instead of iMax0.local.pid
which was stated in the error:
ERROR! The server quit without updating PID file (/usr/local/mysql/data/iMax0.local.pid).
Solution that works for me was copying localhost.pid
and renaming it to iMax0.local.pid
.
A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label
See this link for more on the differences between a TextBlock and other Controls