The most recent versions of the PicklingTools libraries (1.3.0 and 1.3.1) support tools for converting from XML to a Python dict.
The download is available here: PicklingTools 1.3.1
There is quite a bit of documentation for the converters here: the documentation describes in detail all of the decisions and issues that will arise when converting between XML and Python dictionaries (there are a number of edge cases: attributes, lists, anonymous lists, anonymous dicts, eval, etc. that most converters don't handle). In general, though, the converters are easy to use. If an 'example.xml' contains:
<top>
<a>1</a>
<b>2.2</b>
<c>three</c>
</top>
Then to convert it to a dictionary:
>>> from xmlloader import *
>>> example = file('example.xml', 'r') # A document containing XML
>>> xl = StreamXMLLoader(example, 0) # 0 = all defaults on operation
>>> result = xl.expect XML()
>>> print result
{'top': {'a': '1', 'c': 'three', 'b': '2.2'}}
There are tools for converting in both C++ and Python: the C++ and Python do indentical conversion, but the C++ is about 60x faster
I think I have found a better way. You don't have to put attributes into your classes. I've made two methods for serialization and deserialization which take generic list as parameter.
Take a look (it works for me):
private void SerializeParams<T>(XDocument doc, List<T> paramList)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(paramList.GetType());
System.Xml.XmlWriter writer = doc.CreateWriter();
serializer.Serialize(writer, paramList);
writer.Close();
}
private List<T> DeserializeParams<T>(XDocument doc)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<T>));
System.Xml.XmlReader reader = doc.CreateReader();
List<T> result = (List<T>)serializer.Deserialize(reader);
reader.Close();
return result;
}
So you can serialize whatever list you want! You don't need to specify the list type every time.
List<AssemblyBO> list = new List<AssemblyBO>();
list.Add(new AssemblyBO());
list.Add(new AssemblyBO() { DisplayName = "Try", Identifier = "243242" });
XDocument doc = new XDocument();
SerializeParams<T>(doc, list);
List<AssemblyBO> newList = DeserializeParams<AssemblyBO>(doc);
Your classes should look like this
[XmlRoot("StepList")]
public class StepList
{
[XmlElement("Step")]
public List<Step> Steps { get; set; }
}
public class Step
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Desc")]
public string Desc { get; set; }
}
Here is my testcode.
string testData = @"<StepList>
<Step>
<Name>Name1</Name>
<Desc>Desc1</Desc>
</Step>
<Step>
<Name>Name2</Name>
<Desc>Desc2</Desc>
</Step>
</StepList>";
XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
StepList result = (StepList) serializer.Deserialize(reader);
}
If you want to read a text file you should load the file into a FileStream and deserialize this.
using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open))
{
StepList result = (StepList) serializer.Deserialize(fileStream);
}
See if this helps:
[Serializable()]
[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)]
public class Cars
{
[XmlArrayItem(typeof(Car))]
public Car[] Car { get; set; }
}
.
[Serializable()]
public class Car
{
[System.Xml.Serialization.XmlElement()]
public string StockNumber{ get; set; }
[System.Xml.Serialization.XmlElement()]
public string Make{ get; set; }
[System.Xml.Serialization.XmlElement()]
public string Model{ get; set; }
}
And failing that use the xsd.exe program that comes with visual studio to create a schema document based on that xml file, and then use it again to create a class based on the schema document.
I tried
Document.getElementsByClassName('option0')
Which resulted in the error: Uncaught TypeError: Document.getElementsByClass is not a function
After that I tried:
document.getElementsByClassName('option0')
And it works!
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
See LINQ: How to get the latest/last record with a group by clause
var firstItemsInGroup = from b in mainButtons
group b by b.category into g
select g.First();
I assume that mainButtons are already sorted correctly.
If you need to specify custom sort order, use OrderBy override with Comparer.
var firstsByCompareInGroups = from p in rows
group p by p.ID into grp
select grp.OrderBy(a => a, new CompareRows()).First();
See an example in my post "Select First Row In Group using Custom Comparer"
You could do something like this
String[] myStrings = { "One", "Two", "Three" };
or in expression
functionCall(new String[] { "One", "Two", "Three" });
or
String myStrings[];
myStrings = new String[] { "One", "Two", "Three" };
this worked for me..
<Location />
Allow from all
Order Deny,Allow
</Location>
I have included this code in my /etc/apache2/apache2.conf
use
pattern.compile("\"");
String s= p.toString()+"yourcontent"+p.toString();
will give result as yourcontent
as is
If you're using version 3.x of Bootstrap, the correct way to do this now is:
$('#myModal').on('hidden.bs.modal', function (e) {
// do something...
})
Scroll down to the events section to learn more.
http://getbootstrap.com/javascript/#modals-usage
This appears to remain unchanged for whenever version 4 releases (http://v4-alpha.getbootstrap.com/components/modal/#events), but if it does I'll be sure to update this post with the relevant information.
Asp.Net Core 2.2 with AutoMapper.Extensions.Microsoft.DependencyInjection.
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Domain, DomainDto>();
}
}
In Startup.cs
services.AddAutoMapper(typeof(List.Handler));
This is happening because of the CORS error. CORS stands for Cross Origin Resource Sharing. In simple words, this error occurs when we try to access a domain/resource from another domain.
Read More about it here: CORS error with jquery
To fix this, if you have access to the other domain, you will have to allow Access-Control-Allow-Origin in the server. This can be added in the headers. You can enable this for all the requests/domains or a specific domain.
How to get a cross-origin resource sharing (CORS) post request working
These links may help
Try
$(document).ready(function(){
//Register click events to all checkboxes inside question element
$(document).on('click', '.question input:checkbox', function() {
//Find the next answer element to the question and based on the checked status call either show or hide method
$(this).closest('.question').next('.answer')[this.checked? 'show' : 'hide']()
});
});
Demo: Fiddle
Or
$(document).ready(function(){
//Register click events to all checkboxes inside question element
$(document).on('click', '.question input:checkbox', function() {
//Find the next answer element to the question and based on the checked status call either show or hide method
var answer = $(this).closest('.question').next('.answer');
if(this.checked){
answer.show(300);
} else {
answer.hide(300);
}
});
});
Following the JSON-P 1.0 specs (JSR-353) a more current solution for a given JsonStructure
(JsonObject
or JsonArray
) could look like this:
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonStructure;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;
public class PrettyJson {
private static JsonWriterFactory FACTORY_INSTANCE;
public static String toString(final JsonStructure status) {
final StringWriter stringWriter = new StringWriter();
final JsonWriter jsonWriter = getPrettyJsonWriterFactory()
.createWriter(stringWriter);
jsonWriter.write(status);
jsonWriter.close();
return stringWriter.toString();
}
private static JsonWriterFactory getPrettyJsonWriterFactory() {
if (null == FACTORY_INSTANCE) {
final Map<String, Object> properties = new HashMap<>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
FACTORY_INSTANCE = Json.createWriterFactory(properties);
}
return FACTORY_INSTANCE;
}
}
collection.ToList().ForEach(c => c.PropertyToSet = value);
Following query helped me. Instead of using LIKE
, you can use ~*
.
select id, name from hosts where name ~* 'julia|lena|jack';
Use method=POST then it will pass key&value.
When you use DISTINCT
think of it as a distinct row, not column. It will return only rows where the columns do not match exactly the same.
SELECT DISTINCT ID, Email, ProductName, ProductModel
FROM Products
----------------------
1 | [email protected] | ProductName1 | ProductModel1
2 | [email protected] | ProductName1 | ProductModel1
The query would return both rows because the ID
column is different. I'm assuming that the ID
column is an IDENTITY
column that is incrementing, if you want to return the last then I recommend something like this:
SELECT DISTINCT TOP 1 ID, Email, ProductName, ProductModel
FROM Products
ORDER BY ID DESC
The TOP 1
will return only the first record, by ordering it by the ID
descending it will return the results with the last row first. This will give you the last record.
The function I use currently:
/**
* Serializes form or any other element with jQuery.serialize
* @param el
*/
serialize: function(el) {
var serialized = $(el).serialize();
if (!serialized) // not a form
serialized = $(el).
find('input[name],select[name],textarea[name]').serialize();
return serialized;
}
try this....
public void buildPushNotification(Context ctx, String content, int icon, CharSequence text, boolean silent) {
Intent intent = new Intent(ctx, Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 1410, intent, PendingIntent.FLAG_ONE_SHOT);
Bitmap bm = BitmapFactory.decodeResource(ctx.getResources(), //large drawable);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
.setSmallIcon(icon)
.setLargeIcon(bm)
.setContentTitle(content)
.setContentText(text)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
if(!silent)
notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1410, notificationBuilder.build());
}
and in onMessageReceived, call it
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("Msg", "Message received [" + remoteMessage.getNotification().getBody() + "]");
buildPushNotification(/*your param*/);
}
or follow KongJing, Is also correct as he says, but you can use a Firebase Console.
Instead of using the instance with the scope resolution operator :: because it wasn't defined like static function.
$r=Page::getInstanceByName($page);
change it to :
$r=Page->getInstanceByName($page);
And it will work like a charm.
the following bitwise operators: &, |, ^, and ~ return values (based on their input) in the same way logic gates affect signals. You could use them to emulate circuits.
select convert(varchar(11), transfer_date, 106)
got me my desired result of date formatted as 07 Mar 2018
My column 'transfer_date' is a datetime type column and I am using SQL Server 2017 on azure
while true; do foo; sleep 2; done
By the way, if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.
$ while true
> do
> echo "hello"
> sleep 2
> done
hello
hello
hello
^C
$ <arrow up> while true; do echo "hello"; sleep 2; done
The shift can be implement with data types (char, int and long int). The float and double data connot be shifted.
value= value >> steps // Right shift, signed data.
value= value << steps // Left shift, signed data.
Not possible with vanilla CSS. However you can use something like:
Sass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.
Or
Rather than constructing long selector names to specify inheritance, in Less you can simply nest selectors inside other selectors. This makes inheritance clear and style sheets shorter.
Example:
#header {
color: red;
a {
font-weight: bold;
text-decoration: none;
}
}
=IF(B2="X",IF(B3="Y", TRUE, FALSE),FALSE)
, and choose to fill green when this is true=IF(B2="X",IF(B3="W", TRUE, FALSE),FALSE)
and choose to fill red when this is true.More details - conditional formatting with a formula applies the format when the formula evaluates to TRUE. You can use a compound IF
formula to return true or false based on the values of any cells.
WARNING: Not for git newbies.
This comes up enough in my workflow that I've almost tried to write a new git command for it. The usual git stash
flow is the way to go but is a little awkward. I usually make a new commit first since if I have been looking at the changes, all the information is fresh in my mind and it's better to just start git commit
-ing what I found (usually a bugfix belonging on master that I discover while working on a feature branch) right away.
It is also helpful—if you run into situations like this a lot—to have another working directory alongside your current one that always have the
master
branch checked out.
So how I achieve this goes like this:
git commit
the changes right away with a good commit message.git reset HEAD~1
to undo the commit from current branch.Sometimes later (asynchronously), or immediately in another terminal window:
cd my-project-master
which is another WD sharing the same .git
git reflog
to find the bugfix I've just made.git cherry-pick SHA1
of the commit.Optionally (still asynchronous) you can then rebase (or merge) your feature branch to get the bugfix, usually when you are about to submit a PR and have cleaned your feature branch and WD already:
cd my-project
which is the main WD I'm working on.git rebase master
to get the bugfixes.This way I can keep working on the feature uninterrupted and not have to worry about git stash
-ing anything or having to clean my WD before a git checkout
(and then having the check the feature branch backout again.) and still have all my bugfixes goes to master
instead of hidden in my feature branch.
IMO git stash
and git checkout
is a real PIA when you are in the middle of working on some big feature.
Thanks for the solution !
It works, but in a french Excel environment, you should apply something like
TEXTE(F2;"jj/mm/aaaa")
to get the date preserved as it is displayed in F2 cell, after concatenation. Best Regards
I have a different take on this. I could do a docker ps
and see that there is a docker container running, I even tried to restart it, but as soon as I tried to get a session for it with New-PSSession -ContainerId $containerId -RunAsAdministrator
It would error out, saying:
##[error]New-PSSession : The input ContainerId xxx does not exist, ##[error]or the corresponding container is not running.
My problem was I was running with network service and it did not have enough permissions to see the container, even though I had given it permissions to run docker commands (with docker security group configuration)
I didn't know how to enable working with containers, so I had to revert to running it as an admin user instead
Tangential: String.format() rocks:
public String toString() {
return String.format("%s %s", getMake(), getReg());
}
private static void printAll() {
for (Car car: cars)
System.out.println(car); // invokes Car.toString()
}
Asterisk (*
) works with alias. Ex:
from pyspark.sql.functions import *
df1 = df1.alias('df1')
df2 = df2.alias('df2')
df1.join(df2, df1.id == df2.id).select('df1.*')
You need to have a Reference to the System.Web.Http
assembly which has the HTTPClient
class, your trying to use. Try adding the below line before your class declaration
using System.Web.Http;
If you still get the Error, try doing this in Visual Studio
System.Web.Http.dll
).For guys like me, who aren't minimalistic, there is a PECL extension called "intl". I use it for idn conversion since it works way better than the "idn" extension and some other n1 classes like "IntlDateFormatter".
Well, what I want to say is, the "intl" extension has a class called "IntlCalendar" which can handle many international countries (e.g. in Saudi Arabia, sunday is not a weekend day). The IntlCalendar has a method IntlCalendar::isWeekend for that. Maybe you guys give it a shot, I like that "it works for almost every country" fact on these intl-classes.
EDIT: Not quite sure but since PHP 5.5.0, the intl extension is bundled with PHP (--enable-intl).
A language itself is neither compiled nor interpreted, only a specific implementation of a language is. Java is a perfect example. There is a bytecode-based platform (the JVM), a native compiler (gcj) and an interpeter for a superset of Java (bsh). So what is Java now? Bytecode-compiled, native-compiled or interpreted?
Other languages, which are compiled as well as interpreted, are Scala, Haskell or Ocaml. Each of these languages has an interactive interpreter, as well as a compiler to byte-code or native machine code.
So generally categorizing languages by "compiled" and "interpreted" doesn't make much sense.
If you just need to resync
windows time, open an elevated command prompt and type:
w32tm /resync
C:\WINDOWS\system32>w32tm /resync
Sending resync command to local computer
The command completed successfully.
If somehow you want a simple, yet different solution, you can use the {**dict}
syntax:
from collections import OrderedDict
ordered = OrderedDict([('method', 'constant'), ('data', '1.225')])
regular = {**ordered}
1-press CTRL F
2-paste the copied text in search bar
3-press CTRL A followed by CTRL C to copy the text again from search
4-paste in Notepad++
5-replace 'space'
with ','
Perhaps the best two browser techs for this are Canvas, with Flash as a back up.
We tried VML on IE as backup for Canvas, but it was much slower than Flash. SVG was slower then all the rest.
With jSignature ( http://willowsystems.github.com/jSignature/ ) we used Canvas as primary, with fallback to Flash-based Canvas emulator (FlashCanvas) for IE8 and less. Id' say worked very well for us.
One liner, useful for stdout redirect with ">":
@for /f %%i in ('type yourfile.txt') do @echo %%i & exit
I was having Same error. While I run Reactjs app. What I do is just remove the node_modules folder and type and install node_modules again. This remove the error.
Insert Into FEMALE(ID, Image)
Select '1', BulkColumn
from Openrowset (Bulk 'D:\thepathofimage.jpg', Single_Blob) as Image
You will also need admin rights to run the query.
If you already have the target object, so you don't want to create it anew (like if updating an array) you must copy the properties.
If have done it this way:
Object.keys(source).forEach((key) => {
copy[key] = source[key]
})
You are iterating over one string (word
), but then using the index into that to look up a character in so_far
. There is no guarantee that these two strings have the same length.
In bootstrap 4.1, the w-100 class is required along with img-fluid for images smaller than the page to be stretched:
<div class="container">
<div class="row">
<img class='img-fluid w-100' src="#" alt="" />
</div>
</div>
see closed issue: https://github.com/twbs/bootstrap/issues/20830
(As of 2018-04-20, the documentation is wrong: https://getbootstrap.com/docs/4.1/content/images/ says that img-fluid applies max-width: 100%; height: auto;" but img-fluid does not resolve the issue, and neither does manually adding those style attributes with or without bootstrap classes on the img tag.)
From: http://www.sql-server-helper.com/error-messages/msg-536.aspx
To use function LEFT if not all data is in the form '1/12' you need this in the second line above:
Set Col2 = LEFT(Col1, ISNULL(NULLIF(CHARINDEX('/', Col1) - 1, -1), LEN(Col1)))
function nextFormInput() {
var focused = $(':focus');
var inputs = $(focused).closest('form').find(':input');
inputs.eq(inputs.index(focused) + 1).focus();
}
Just wanted to add to this since I ran into the same problem and nothing I could find anywhere would work (e.g downloading the cacert.pem file, setting cafile in php.ini etc.)
If you are using NGINX and your SSL certificate comes with an "intermediate certificate", you need to combine the intermediate cert file with your main "mydomain.com.crt" file and it should work. Apache has a setting specific for intermediate certs, but NGINX does not so it must be within same file as your regular cert.
You may be able to use the JAVA_TOOL_OPTIONS
environment variable to set options. It worked for me with Rasbian. See Environment Variables and System Properties which has this to say:
In many environments, the command line is not readily accessible to start the application with the necessary command-line options.
This often happens with applications that use embedded VMs (meaning they use the Java Native Interface (JNI) Invocation API to start the VM), or where the startup is deeply nested in scripts. In these environments the JAVA_TOOL_OPTIONS environment variable can be useful to augment a command line.
When this environment variable is set, the JNI_CreateJavaVM function (in the JNI Invocation API), the JNI_CreateJavaVM function adds the value of the environment variable to the options supplied in its JavaVMInitArgs argument.
However this environment variable use may be disabled for security reasons.
In some cases, this option is disabled for security reasons. For example, on the Oracle Solaris operating system, this option is disabled when the effective user or group ID differs from the real ID.
See this example showing the difference between specifying on the command line versus using the JAVA_TOOL_OPTIONS
environment variable.
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
String someString = new String("Love thy neighbor");
System.out.println(someString);
char[] someChar = someString.toCharArray();
int j = someChar.length - 1;
char temp;
for (int i = 0; i <= someChar.length / 2; i++) {
temp = someChar[i];
someChar[i] = someChar[j];
someChar[j] = temp;
j--;
}
someString = new String(someChar);
System.out.println(someString);
Run:
Love thy neighbor
robhgien yht evoL
We've seen in our projects that a post request with JSON and files is creating a lot of confusion between the frontend and backend developers, leading to unnecessary wastage of time.
Here's a better approach: convert file bytes array to Base64 string and send it in the JSON.
public Class UserDTO {
private String firstName;
private String lastName;
private FileDTO profilePic;
}
public class FileDTO {
private String base64;
// just base64 string is enough. If you want, send additional details
private String name;
private String type;
private String lastModified;
}
@PostMapping("/user")
public String saveUser(@RequestBody UserDTO user) {
byte[] fileBytes = Base64Utils.decodeFromString(user.getProfilePic().getBase64());
....
}
JS code to convert file to base64 string:
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
const userDTO = {
firstName: "John",
lastName: "Wick",
profilePic: {
base64: reader.result,
name: file.name,
lastModified: file.lastModified,
type: file.type
}
}
// post userDTO
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
np.isnan
can be applied to NumPy arrays of native dtype (such as np.float64):
In [99]: np.isnan(np.array([np.nan, 0], dtype=np.float64))
Out[99]: array([ True, False], dtype=bool)
but raises TypeError when applied to object arrays:
In [96]: np.isnan(np.array([np.nan, 0], dtype=object))
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Since you have Pandas, you could use pd.isnull
instead -- it can accept NumPy arrays of object or native dtypes:
In [97]: pd.isnull(np.array([np.nan, 0], dtype=float))
Out[97]: array([ True, False], dtype=bool)
In [98]: pd.isnull(np.array([np.nan, 0], dtype=object))
Out[98]: array([ True, False], dtype=bool)
Note that None
is also considered a null value in object arrays.
it is easy! you are downloading the binary file?. download the rpm latest package openssl-1.0.1e-30.el6.x86_64 check what was the current version using rpm -q openssl. if this is older then do rpm -U openssl-1.0.1e-30.el6.x86_64 . if yum is configured updated this package in the repo and do yum update openssl if your repo in RHN do simply yum update openssl-1.0.1g is very old and valnuarable
Yes, but the syntax is different than what you have
SELECT
<fields>
FROM
<table1>
LEFT JOIN <table2>
ON <criteria for join>
AND <other criteria for join>
LEFT JOIN <table3>
ON <criteria for join>
AND <other criteria for join>
As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
It's easy enough to write the equivalent of CopyTo
in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream
.
For efficient purposes you could check whether the stream returned is already a MemoryStream
:
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
You can temporarily disable timestamps
$timestamps = $user->timestamps;
$user->timestamps=false; // avoid view updating the timestamp
$user->last_logged_in_at = now();
$user->save();
$user->timestamps=$timestamps; // restore timestamps
The accepted answer by @Meherzad only works if the data is in a particular order. It happens to work with the data from the OP question. In my case, I had to modify it to work with my data.
Note This only works when every record's "id" (col1 in the question) has a value GREATER THAN that record's "parent id" (col3 in the question). This is often the case, because normally the parent will need to be created first. However if your application allows changes to the hierarchy, where an item may be re-parented somewhere else, then you cannot rely on this.
This is my query in case it helps someone; note it does not work with the given question because the data does not follow the required structure described above.
select t.col1, t.col2, @pv := t.col3 col3
from (select * from table1 order by col1 desc) t
join (select @pv := 1) tmp
where t.col1 = @pv
The difference is that table1
is being ordered by col1
so that the parent will be after it (since the parent's col1
value is lower than the child's).
The accepted answer is wrong. The quote is correct, the assertion that PUT and POST must have it is incorrect. There is no requirement that PUT or POST actually have additional content. Nor is there a prohibition against GET actually having content.
The RFCs say exactly what they mean .. IFF your side (client OR origin server) will be sending additional content, beyond the HTTP headers, it SHOULD specify a Content-Type header. But note it is allowable to omit the Content-Type and still include content (say, by using a Content-Length header).
For Each row As DataRow In dtDataTable.Rows
strDetail = row.Item("Detail")
Next row
There's also a shorthand:
For Each row As DataRow In dtDataTable.Rows
strDetail = row("Detail")
Next row
Note that Microsoft's style guidelines for .Net now specifically recommend against using hungarian type prefixes for variables. Instead of "strDetail", for example, you should just use "Detail".
I also ran into the similar issue and was using CNTLM for proxy configuration. In my case HTTP_PROXY
and HTTPS_PROXY
are taking higher precedence over http_proxy
and https_proxy
so be aware of changing all proxy variables.
env|grep -i proxy
and make sure all of the below proxy variables should point to the same proxy.
HTTP-PROXY = "http://localhost:3128"
HTTPS-PROXY = "https://localhost:3128"
HTTPS_PROXY = "http://localhost:3128"
HTTP_PROXY = "http://localhost:3128"
PROXY = "http://localhost:3128"
http-proxy = "http://localhost:3128"
http_proxy = "http://localhost:3128"
https-proxy = "https://localhost:3128/"
https_proxy = "https://localhost:3128"
proxy = "http://localhost:3128/"
I know some variables are unneccessary but I'm not sure which is using what.
One way to get the list of distinct column names from the database is to use distinct()
in conjunction with values()
.
In your case you can do the following to get the names of distinct categories:
q = ProductOrder.objects.values('Category').distinct()
print q.query # See for yourself.
# The query would look something like
# SELECT DISTINCT "app_productorder"."category" FROM "app_productorder"
There are a couple of things to remember here. First, this will return a ValuesQuerySet
which behaves differently from a QuerySet
. When you access say, the first element of q
(above) you'll get a dictionary, NOT an instance of ProductOrder
.
Second, it would be a good idea to read the warning note in the docs about using distinct()
. The above example will work but all combinations of distinct()
and values()
may not.
PS: it is a good idea to use lower case names for fields in a model. In your case this would mean rewriting your model as shown below:
class ProductOrder(models.Model):
product = models.CharField(max_length=20, primary_key=True)
category = models.CharField(max_length=30)
rank = models.IntegerField()
Primary keys are for uniquely identifying rows. This is done by comparing all parts of a key to the input.
Per definition, NULL cannot be part of a successful comparison. Even a comparison to itself (NULL = NULL
) will fail. This means a key containing NULL would not work.
Additonally, NULL is allowed in a foreign key, to mark an optional relationship.(*) Allowing it in the PK as well would break this.
(*)A word of caution: Having nullable foreign keys is not clean relational database design.
If there are two entities A
and B
where A
can optionally be related to B
, the clean solution is to create a resolution table (let's say AB
). That table would link A
with B
: If there is a relationship then it would contain a record, if there isn't then it would not.
Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the
public ActionResult SomeActionMethod(int id)
{
return Json(new {foo="bar", baz="Blech"});
}
Method from the jquery getJSON method by simply...
$.getJSON("../SomeActionMethod", { id: someId },
function(data) {
alert(data.foo);
alert(data.baz);
}
);
You can definitely go for typeid(x).name()
where x is the variable name. It actually returns a const char pointer to the data type. Now, look at the following code.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n = 36;
char c = 'A';
double d = 1.2;
if(*(typeid(n).name()) == 'i'){
cout << "I am an Integer variable" << endl;
}
if(*((char *) typeid(d).name()) == 'd'){
cout << "I am a Double variable" << endl;
}
if(*((char *) typeid(c).name()) == 'c'){
cout << "I am a Char variable" << endl;
}
return 0;
}
Notice how first and second both if works.
Executing seq(1, 10, 1)
does what 1:10
does. You can change the last parameter of seq
, i.e. by
, to be the step of whatever size you like.
> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability
> [1] 0 2 4 6 8 10
Get the current URL including the query string.
echo url()->full();
INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count
FROM batch
WHERE NOT EXISTS (
SELECT * FROM target t2, batch b2
WHERE t2.userid = b2.userid
-- ... other keyfields ...
)
;
BTW: if you want the whole batch to fail in case of a duplicate, then (given a primary key constraint)
INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count
FROM batch
;
will do exactly what you want: either it succeeds, or it fails.
Found the fix for the problem here.
xcode-select --install
This will bring up a prompt to install the necessary command line tools.
In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.
7 modulo 3 --> 1
7 modulo -3 --> -2
-7 modulo 3 --> 2
-7 modulo -3 --> -1
It can depend on what your are initialising, for example you cannot just use field initialisation if a checked exception is involved. For example, the following:
public class Foo {
FileInputStream fis = new FileInputStream("/tmp"); // throws FileNotFoundException
}
Will cause a compile-time error unless you also include a constructor declaring that checked exception, or extend a superclass which does, e.g.:
public Foo() throws FileNotFoundException {}
I think the reason may be that mock object libraries typically create mocks by dynamically creating classes at runtime (using cglib). This means they either implement an interface at runtime (that's what EasyMock does if I'm not mistaken), or they inherit from the class to mock (that's what Mockito does if I'm not mistaken). Both approaches do not work for static members, since you can't override them using inheritance.
The only way to mock statics is to modify a class' byte code at runtime, which I suppose is a little more involved than inheritance.
That's my guess at it, for what it's worth...
The broken pipe error usually occurs if your request is blocked or takes too long and after request-side timeout, it'll close the connection and then, when the respond-side (server) tries to write to the socket, it will throw a pipe broken error.
{{ (ability.id in company_abilities) ? 'selected' : '' }}
The ternary operator is documented under 'other operators'
You can do it with a sub-query:
SELECT * FROM (
SELECT * FROM table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC
This will select the last 50 rows from table
, and then order them in ascending order.
I've written a gem that does this for Rails ActiveRecord objects. The example uses created_at, but it will also work on updated_at or anything with the class ActiveSupport::TimeWithZone.
Just gem install and call the 'pretty' method on your TimeWithZone instance.
The workaround is simple. Just use the Uri().ToString() method and percent-encode white-spaces, if any, afterwards.
string path = new Uri("C:\my example?.txt").ToString().Replace(" ", "%20");
properly returns file:///C:/my%20example?.txt
Select JoiningDate ,Dateadd (day , 30 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (month , 10 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (year , 10 , JoiningDate )
from Emp
Select DateAdd(Hour, 10 , JoiningDate )
from emp
Select dateadd (hour , 10 , getdate()), getdate()
Select dateadd (hour , 10 , joiningDate)
from Emp
Select DateAdd (Second , 120 , JoiningDate ) , JoiningDate
From EMP
Install all thru terminal:
npm install lodash --save
tsd install lodash --save
Add paths in index.html
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
},
paths: {
lodash: './node_modules/lodash/lodash.js'
}
});
System.import('app/init').then(null, console.error.bind(console));
</script>
Import lodash at the top of the .ts file
import * as _ from 'lodash'
I know it's working for you now @Vantheman6 but this is what worked for me in case it's the same for someone else.
I added to my .env file the details of the mail service I am using. So make sure the following details
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=MyPassword
in the .env file are accurate.
NOTE: Don't forget to restart your server after editing the .env file so it will pick the new data that you put in there.
Clear config cache with below command:
php artisan config:cache
If you don't restart your server, the .env file will still continue to present the old mail data to the app even though you have made changes that can cause this error.
SELECT CONVERT( VARCHAR(24), GETDATE(), 113)
UPDATE
PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))
There is no semantic difference in the generic constraint language between whether a class 'implements' or 'extends'. The constraint possibilities are 'extends' and 'super' - that is, is this class to operate with assignable to that other one (extends), or is this class assignable from that one (super).
encode function can help you here, encode returns an encoded version of the string
In [44]: str = "ABCD"
In [45]: [elem.encode("hex") for elem in str]
Out[45]: ['41', '42', '43', '44']
or you can use array module
In [49]: import array
In [50]: print array.array('B', "ABCD")
array('B', [65, 66, 67, 68])
Try Editra It's free, has a lot of cool features and plug-ins, it runs on most platforms, and it is written in Python. I use it for all my non-XCode development at home and on Windows/Linux at work.
If you anticipate this rather unwanted behaviour, then one away around it would be to pass an extra parameter from the jQuery.trigger() to the checkbox's click handler. This extra parameter is to notify the click handler that click has been triggered programmatically, rather than by the user directly clicking on the checkbox itself. The checkbox's click handler can then invert the reported check status.
So here's how I'd trigger the click event on a checkbox with the ID "myCheckBox". Note that I'm also passing an object parameter with an single member, nonUI, which is set to true:
$("#myCheckbox").trigger('click', {nonUI : true})
And here's how I handle that in the checkbox's click event handler. The handler function checks for the presence of the nonUI object as its second parameter. (The first parameter is always the event itself.) If the parameter is present and set to true then I invert the reported .checked status. If no such parameter is passed in - which there won't be if the user simply clicked on the checkbox in the UI - then I report the actual .checked status:
$("#myCheckbox").click(function(e, parameters) {
var nonUI = false;
try {
nonUI = parameters.nonUI;
} catch (e) {}
var checked = nonUI ? !this.checked : this.checked;
alert('Checked = ' + checked);
});
JSFiddle version at http://jsfiddle.net/BrownieBoy/h5mDZ/
I've tested with Chrome, Firefox and IE 8.
I tried the top-most answers to this question, but encountered error messages. Then I found the answer here:
PowerShell says "execution of scripts is disabled on this system."
What worked well for me was to use this solution:
powershell -ExecutionPolicy Bypass -File script.ps1
You can paste that into a .bat file and double-click on it.
I have encountered the same problem, but with an additional constraint: I had no control over the code that appended new elements to the scroll container. None of the examples I found here allowed me to do just that. Here is the solution I ended up with .
It uses Mutation Observers
(https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) which makes it usable only on modern browsers (though polyfills exist)
So basically the code does just that :
var scrollContainer = document.getElementById("myId");
// Define the Mutation Observer
var observer = new MutationObserver(function(mutations) {
// Compute sum of the heights of added Nodes
var newNodesHeight = mutations.reduce(function(sum, mutation) {
return sum + [].slice.call(mutation.addedNodes)
.map(function (node) { return node.scrollHeight || 0; })
.reduce(function(sum, height) {return sum + height});
}, 0);
// Scroll to bottom if it was already scrolled to bottom
if (scrollContainer.clientHeight + scrollContainer.scrollTop + newNodesHeight + 10 >= scrollContainer.scrollHeight) {
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}
});
// Observe the DOM Element
observer.observe(scrollContainer, {childList: true});
I made a fiddle to demonstrate the concept : https://jsfiddle.net/j17r4bnk/
FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :
strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"
The cleanest approach is to copy the list and then insert the object into the copy. On Python 3 this can be done via list.copy
:
new = old.copy()
new.insert(index, value)
On Python 2 copying the list can be achieved via new = old[:]
(this also works on Python 3).
In terms of performance there is no difference to other proposed methods:
$ python --version
Python 3.8.1
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b.insert(500, 3)"
100000 loops, best of 5: 2.84 µsec per loop
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b[500:500] = (3,)"
100000 loops, best of 5: 2.76 µsec per loop
Use Timer for every second...
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//your method
}
}, 0, 1000);//put here time 1000 milliseconds=1 second
Use these raw values and copy in info.plist
<key>NSCalendarsUsageDescription</key>
<string>$(PRODUCT_NAME) calendar events</string>
<key>NSRemindersUsageDescription</key>
<string>$(PRODUCT_NAME) reminder use</string>
<key>NSCameraUsageDescription</key>
<string>This app requires to access your photo library to show image on profile and send via chat</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app requires to access your microphone to record video with your voice send via chat</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app requires to access your photo library to show image on profile and send via chat</string>
<key>NSContactsUsageDescription</key>
<string>$(PRODUCT_NAME) contact use</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>$(PRODUCT_NAME) location use</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>$(PRODUCT_NAME) location use</string>
The tabularx
package gives you
X
, all X
columns will grow to fill up the total width.For your example:
\usepackage{tabularx}
% ...
\begin{document}
% ...
\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF & simulation & jsp\\
\hline
\end{tabularx}
Just call plt.show()
at the end:
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0,50,60,80])
for i in np.arange(1,5):
z = 68 + 4 * np.random.randn(50)
zm = np.cumsum(z) / range(1,len(z)+1)
plt.plot(zm)
n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)
plt.plot(n,su,n,sl)
plt.show()
To drop a UNIQUE constraint, you don’t need the name of the constraint, just the list of columns that are included in the constraint.
The syntax would be:
ALTER TABLE table_name DROP UNIQUE (column1, column2, . . . )
I would suggest the following pattern:
document.getElementById("foo").onsubmit = function(e) {
if (document.getElementById("test").value == "test") {
return true;
} else {
e.preventDefault();
}
}
<form id="foo">
<input id="test"/>
<input type="submit"/>
</form>
...unless I'm missing something.
The Barack Obama app took 22 days to develop from first code to release. Three developers (although not all of them were full time). 10 people total. Figure 500-1000 man hours. Contracting rates are $100-150/hr. Figure $50000-$150000. Compare your app to Obama.app and scale accordingly.
Below is an action method that returns a json string (cameCase) by serializing an array of objects.
public string GetSerializedCourseVms()
{
var courses = new[]
{
new CourseVm{Number = "CREA101", Name = "Care of Magical Creatures", Instructor ="Rubeus Hagrid"},
new CourseVm{Number = "DARK502", Name = "Defence against dark arts", Instructor ="Severus Snape"},
new CourseVm{Number = "TRAN201", Name = "Transfiguration", Instructor ="Minerva McGonal"}
};
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
return JsonConvert.SerializeObject(courses, camelCaseFormatter);
}
Note the JsonSerializerSettings instance passed as the second parameter. That's what makes the camelCase happen.
Use the following code:
if(processing == success) {
header("Location:filename");
exit();
}
And you are good to go.
I think the answer is here (possibly duplicate):
How to test if a file is a directory in a batch script?
IF EXIST %VAR%\NUL ECHO It's a directory
Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.
As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)
if exist "c:\folder\" echo folder exists
should be enough for modern windows.
Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
}
return rtn;
}
To use it, simply do something like this:
var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);
The var alteredURL
will be the output you desire.
Hope it helps!
The simplest way would be to directly subtract the date objects from one another.
For example:
var hours = Math.abs(date1 - date2) / 36e5;
The subtraction returns the difference between the two dates in milliseconds. 36e5
is the scientific notation for 60*60*1000
, dividing by which converts the milliseconds difference into hours.
git-pull - Fetch from and integrate with another repository or a local branch GIT PULL
Basically you are pulling remote branch to your local, example:
git pull origin master
Will pull master branch into your local repository
git-rebase - Forward-port local commits to the updated upstream head GIT REBASE
This one is putting your local changes on top of changes done remotely by other users. For example:
SOME-FEATURE
Now you want to see his and your changes on your local branch.
So then you checkout master
branch:
git checkout master
then you can pull:
git pull origin master
and then you go to your branch:
git checkout SOME-FEATURE
and you can do rebase master
to get lastest changes from it and put your branch commits on top:
git rebase master
I hope now it's a bit more clear for you.
Above answers are pretty sufficient. Additional to the onChange
, if you upload a file using drag and drop events, you can get the file in drop
event by accessing eventArgs.dataTransfer.files
.
You just need this:
$(".hidden").attr("placeholder", "Type here to search");
classList
is used for manipulating classes and not attributes.
The major difference is time-out, WCF Service has timed-out when there is no response, but web-service does not have this property.
You can use this
(new SelectElement(driver.FindElement(By.Id(""))).SelectByText("");
If you intend to write your own daemon, then I recommend calling setuid(). This way, your process can
This one worked for me:
@MetricMonthNumber (some number)
SELECT
(DateName( month , DateAdd( month , @MetricMonthNumber - 1 , '1900-01-01' ) )) AS MetricMonthName
FROM TableName
From a post above from @leoinfo and @Valentino Vranken. Just did a quick select and it works.
This API has been available for a long time and enables to get access to market data (including live) if you are running a Bloomberg Terminal or have access to a Bloomberg Server, which is chargeable.
The only difference is that the API (not its code) has been open sourced, so it can now be used as a dependency in an open source project for example, without any copyrights issues, which was not the case before.
<inf.h>
/* IEEE positive infinity. */
#if __GNUC_PREREQ(3,3)
# define INFINITY (__builtin_inff())
#else
# define INFINITY HUGE_VALF
#endif
and
<bits/nan.h>
#ifndef _MATH_H
# error "Never use <bits/nan.h> directly; include <math.h> instead."
#endif
/* IEEE Not A Number. */
#if __GNUC_PREREQ(3,3)
# define NAN (__builtin_nanf (""))
#elif defined __GNUC__
# define NAN \
(__extension__ \
((union { unsigned __l __attribute__ ((__mode__ (__SI__))); float __d; }) \
{ __l: 0x7fc00000UL }).__d)
#else
# include <endian.h>
# if __BYTE_ORDER == __BIG_ENDIAN
# define __nan_bytes { 0x7f, 0xc0, 0, 0 }
# endif
# if __BYTE_ORDER == __LITTLE_ENDIAN
# define __nan_bytes { 0, 0, 0xc0, 0x7f }
# endif
static union { unsigned char __c[4]; float __d; } __nan_union
__attribute_used__ = { __nan_bytes };
# define NAN (__nan_union.__d)
#endif /* GCC. */
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
You can synchronize your code over the class. That would be simplest.
public class Test
{
private static int count = 0;
private static final Object lock= new Object();
public synchronized void foo()
{
synchronized(Test.class)
{
count++;
}
}
}
Hope you find this answer useful.
It sounds like you already know the unique column names. If that's the case, then df = df['Time', 'Time Relative', 'N2']
would work.
If not, your solution should work:
In [101]: vals = np.random.randint(0,20, (4,3))
vals
Out[101]:
array([[ 3, 13, 0],
[ 1, 15, 14],
[14, 19, 14],
[19, 5, 1]])
In [106]: df = pd.DataFrame(np.hstack([vals, vals]), columns=['Time', 'H1', 'N2', 'Time Relative', 'N2', 'Time'] )
df
Out[106]:
Time H1 N2 Time Relative N2 Time
0 3 13 0 3 13 0
1 1 15 14 1 15 14
2 14 19 14 14 19 14
3 19 5 1 19 5 1
In [107]: df.T.drop_duplicates().T
Out[107]:
Time H1 N2
0 3 13 0
1 1 15 14
2 14 19 14
3 19 5 1
You probably have something specific to your data that's messing it up. We could give more help if there's more details you could give us about the data.
Edit: Like Andy said, the problem is probably with the duplicate column titles.
For a sample table file 'dummy.csv' I made up:
Time H1 N2 Time N2 Time Relative
3 13 13 3 13 0
1 15 15 1 15 14
14 19 19 14 19 14
19 5 5 19 5 1
using read_table
gives unique columns and works properly:
In [151]: df2 = pd.read_table('dummy.csv')
df2
Out[151]:
Time H1 N2 Time.1 N2.1 Time Relative
0 3 13 13 3 13 0
1 1 15 15 1 15 14
2 14 19 19 14 19 14
3 19 5 5 19 5 1
In [152]: df2.T.drop_duplicates().T
Out[152]:
Time H1 Time Relative
0 3 13 0
1 1 15 14
2 14 19 14
3 19 5 1
If your version doesn't let your, you can hack together a solution to make them unique:
In [169]: df2 = pd.read_table('dummy.csv', header=None)
df2
Out[169]:
0 1 2 3 4 5
0 Time H1 N2 Time N2 Time Relative
1 3 13 13 3 13 0
2 1 15 15 1 15 14
3 14 19 19 14 19 14
4 19 5 5 19 5 1
In [171]: from collections import defaultdict
col_counts = defaultdict(int)
col_ix = df2.first_valid_index()
In [172]: cols = []
for col in df2.ix[col_ix]:
cnt = col_counts[col]
col_counts[col] += 1
suf = '_' + str(cnt) if cnt else ''
cols.append(col + suf)
cols
Out[172]:
['Time', 'H1', 'N2', 'Time_1', 'N2_1', 'Time Relative']
In [174]: df2.columns = cols
df2 = df2.drop([col_ix])
In [177]: df2
Out[177]:
Time H1 N2 Time_1 N2_1 Time Relative
1 3 13 13 3 13 0
2 1 15 15 1 15 14
3 14 19 19 14 19 14
4 19 5 5 19 5 1
In [178]: df2.T.drop_duplicates().T
Out[178]:
Time H1 Time Relative
1 3 13 0
2 1 15 14
3 14 19 14
4 19 5 1
This one will work, I am sure!
<embed src="application.swf" quality="high" pluginspage="http://www.macromedia.com/go/getfashplayer" type="application/x-shockwave-flash" width="690" height="430">
This is for longs, but you can modify it easily to work with ints.
private static long[] ConvertStringArrayToLongArray(string str)
{
return str.Split(",".ToCharArray()).Select(x => long.Parse(x.ToString())).ToArray();
}
Whereas @jbarrueta answer is perfect, in the 2.12 version of Jackson was introduced a new long-awaited type for the @JsonTypeInfo
annotation, DEDUCTION
.
It is useful for the cases when you have no way to change the incoming json or must not do so. I'd still recommend to use use = JsonTypeInfo.Id.NAME
, as the new way may throw an exception in complex cases when it has no way to determine which subtype to use.
Now you can simply write
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
@JsonSubTypes({
@JsonSubTypes.Type(Dog.class),
@JsonSubTypes.Type(Cat.class) }
)
public abstract class Animal {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And it will produce {"name":"ruffus", "breed":"english shepherd"}
and {"name":"goya", "favoriteToy":"mice"}
Once again, it's safer to use NAME
if some of the fields may be not present, like breed
or favoriteToy
.
Try this,
for (char[] temp : box) {
System.err.println(Arrays.toString(temp).replaceAll(",", " ").replaceAll("\\[|\\]", ""));
}
✕ is another great one that's not too thick. The HTML code is ✕
, or 2715
in hex.
SMTP -> FROM SERVER:
SMTP -> FROM SERVER:
SMTP -> ERROR: EHLO not accepted from server:
that's typical of trying to connect to a SSL service with a client that's not using SSL
SMTP Error: Could not authenticate.
no suprise there having failed to start an SMTP conversation authentigation is not an option,.
phpmailer doesn't do implicit SSL (aka TLS on connect, SMTPS) Short of rewriting smtp.class.php to include support for it there it no way to do what you ask.
Use port 587 with explicit SSL (aka TLS, STARTTLS) instead.
This can be achieved in a very simple way 1. Write this in the view.
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Width="50" Height="30">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsHide}" Value="True">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
The following is the Boolean property which holds the true/ false value. The following is the code snippet. In my example this property is in UserNote class.
public bool _isHide = false;
public bool IsHide
{
get { return _isHide; }
set
{
_isHide = value;
OnPropertyChanged("IsHide");
}
}
This is the way the IsHide property gets the value.
userNote.IsHide = userNote.IsNoteDeleted;
It's browser dependent. "By default, Internet Explorer has a KeepAliveTimeout value of one minute and an additional limiting factor (ServerInfoTimeout) of two minutes. Either setting can cause Internet Explorer to reset the socket." - from IE support http://support.microsoft.com/kb/813827
Firefox is around the same value I think as well.
Usually though server timeout are set lower than browser timeouts, but at least you can control that and set it higher.
You'd rather handle the timeout though, so that way you can act upon such an event. See this thread: How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?
Are you debugging on console? There are various options for debugging PHP. The most common function used for quick & dirty debugging is var_dump.
That being said and out of the way, although var_dump is awesome and a lot of people do everything with just that, there are other tools and techniques that can spice it up a bit.
Things to help out if debugging in a webpage, wrap <pre> </pre>
tags around your dump statement to give you proper formatting on arrays and objects.
Ie:
<div> some html code ....
<a href="<?php $tpl->link;?>">some link to test</a>
</div>
dump $tpl like this:
<pre><?php var_dump($tpl); ?></pre>
And, last but not least make sure if debugging your error handling is set to display errors. Adding this at the top of your script may be needed if you cannot access server configuration to do so.
error_reporting(E_ALL);
ini_set('display_errors', '1');
Good luck!
The iFrame attribute does not support percent in HTML5. It only supports pixels. http://www.w3schools.com/tags/att_iframe_height.asp
you can use triggers. works very well
CREATE TABLE MyTable(
ID INTEGER PRIMARY KEY,
Name TEXT,
Other STUFF,
Timestamp DATETIME);
CREATE TRIGGER insert_Timestamp_Trigger
AFTER INSERT ON MyTable
BEGIN
UPDATE MyTable SET Timestamp =STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') WHERE id = NEW.id;
END;
CREATE TRIGGER update_Timestamp_Trigger
AFTER UPDATE On MyTable
BEGIN
UPDATE MyTable SET Timestamp = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') WHERE id = NEW.id;
END;
Delete the most recent commit, keeping the work you've done:
git reset --soft HEAD~1
Delete the most recent commit, destroying the work you've done:
git reset --hard HEAD~1
Use a Java 8 Stream
.
myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());
Breakdown:
myString
.chars() // Convert to an IntStream
.mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
.collect(Collectors.toList()); // Collect in a List<Character>
(I have absolutely no idea why String#chars()
returns an IntStream
.)
You can change checkbox
color using singe line of code
android:buttonTint="@color/app_color" //whatever color
Node.js supports circular dependencies.
Making use of circular dependencies instead of require('./routes')(app) cleans up a lot of code and makes each module less interdependent on its loading file:
var app = module.exports = express(); //now app.js can be required to bring app into any file
//some app/middleware setup, etc, including
app.use(app.router);
require('./routes'); //module.exports must be defined before this line
var app = require('../app');
app.get('/', function(req, res, next) {
res.render('index');
});
//require in some other route files...each of which requires app independently
require('./user');
require('./blog');
Example from their new generator:
Writing the route:
https://github.com/expressjs/generator/blob/master/templates/js/routes/index.js
Adding/namespacing it to the app:
https://github.com/expressjs/generator/blob/master/templates/js/app.js#L24
There are still usecases for accessing app from other resources, so circular dependencies are still a valid solution.
I originally intentionally never learned how to use eval, because most people will recommend to stay away from it like the plague. However I recently discovered a use case that made me facepalm for not recognizing it sooner.
If you have cron jobs that you want to run interactively to test, you might view the contents of the file with cat, and copy and paste the cron job to run it. Unfortunately, this involves touching the mouse, which is a sin in my book.
Lets say you have a cron job at /etc/cron.d/repeatme with the contents:
*/10 * * * * root program arg1 arg2
You cant execute this as a script with all the junk in front of it, but we can use cut to get rid of all the junk, wrap it in a subshell, and execute the string with eval
eval $( cut -d ' ' -f 6- /etc/cron.d/repeatme)
The cut command only prints out the 6th field of the file, delimited by spaces. Eval then executes that command.
I used a cron job here as an example, but the concept is to format text from stdout, and then evaluate that text.
The use of eval in this case is not insecure, because we know exactly what we will be evaluating before hand.
SingleOrDefault
method throws an Exception
if there is more than one element in the sequence.
Apparently, your query in GetCustomer
is finding more than one match. So you will either need to refine your query or, most likely, check your data to see why you're getting multiple results for a given customer number.
Try this:
<input type="number" max="???" min="???" step="0.5" id="myInput"/>
$("#myInput").attr({
"max" : 10,
"min" : 2
});
Note:This will set max and min value only to single input
Make file executable:
chmod +x file
Find location of perl:
which perl
This should return something like
/bin/perl sometimes /usr/local/bin
Then in the first line of your script add:
#!"path"/perl with path from above e.g.
#!/bin/perl
Then you can execute the file
./file
There may be some issues with the PATH, so you may want to change that as well ...
Actually it has been worked but
just try this.
take the value /\s/g into a string variable like
String a = /\s/g;
str = str.replaceAll(a,"X");
It is possible to pass arrays to functions, and there are no special requirements for dealing with them. Are you sure that the array you are passing to to your function actually has an element at [0]
?
class key
{
int m_value;
public:
bool operator<(const key& src)const
{
return (this->m_value < src.m_value);
}
};
int main()
{
key key1;
key key2;
map<key,int> mymap;
mymap.insert(pair<key,int>(key1,100));
mymap.insert(pair<key,int>(key2,200));
map<key,int>::iterator iter=mymap.begin();
for(;iter!=mymap.end();++iter)
{
cout<<iter->second<<endl;
}
}
If you use RAC then you need to use GV$*
views instead V$*
.
Try to find your session by
select * from gv$session where username = 'test';
and then you can kill the session by
alter system kill session 'sid, serial#, @inst_id' immediate;
Assuming you are trying to pass the command line arguments as well.
import sys
import myModule
def main():
# this will just pass all of the system arguments as is
myModule.main(*sys.argv)
# all the argv but the script name
myModule.main(*sys.argv[1:])
There is no official datepicker for bootstrap; as such, you should explicitly state which one you're using.
If you're using eternicode/bootstrap-datepicker, there's a startDate option. As discussed directly under the Options section in the README:
All options that take a "Date" can handle a Date object; a String formatted according to the given format; or a timedelta relative to today, eg '-1d', '+6m +1y', etc, where valid units are 'd' (day), 'w' (week), 'm' (month), and 'y' (year).
So you would do:
$('#datepicker').datepicker({
startDate: '+1d'
})
fgets would work for you. here is very good documentation on this :-
http://www.cplusplus.com/reference/cstdio/fgets/
If you don't want to use fgets, following method will work for you :-
int readline(FILE *f, char *buffer, size_t len)
{
char c;
int i;
memset(buffer, 0, len);
for (i = 0; i < len; i++)
{
int c = fgetc(f);
if (!feof(f))
{
if (c == '\r')
buffer[i] = 0;
else if (c == '\n')
{
buffer[i] = 0;
return i+1;
}
else
buffer[i] = c;
}
else
{
//fprintf(stderr, "read_line(): recv returned %d\n", c);
return -1;
}
}
return -1;
}
The problem was that I had some other normal error messages in my project, and apparently after I fixed those and when I cleaned and built my project AGAIN, then all .dlls succeeded.
Make sure you don't have any other error messages in your project and if you do, fix those first!
Alternatively, consider using a document databases (such as MongoDB) which natively support rich data structures and nesting.
The files managed by git are shown by git ls-files
. Check out its manual page.
Martin Joiner's problem is caused by a misunderstanding of the <caption>
tag.
The <caption>
tag defines a table caption.
The <caption>
tag must be the first child of the <table>
tag.
You can specify only one caption per table.
Also, note that the scope
attribute should be placed on a <th>
element and not on a <tr>
element.
The proper way to write a multi-header multi-tbody table would be something like this :
<table id="dinner_table">_x000D_
<caption>This is the only correct place to put a caption.</caption>_x000D_
<tbody>_x000D_
<tr class="header">_x000D_
<th colspan="2" scope="col">First Half of Table (British Dinner)</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">1</th>_x000D_
<td>Fish</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">2</th>_x000D_
<td>Chips</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">3</th>_x000D_
<td>Peas</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">4</th>_x000D_
<td>Gravy</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
<tbody>_x000D_
<tr class="header">_x000D_
<th colspan="2" scope="col">Second Half of Table (Italian Dinner)</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">5</th>_x000D_
<td>Pizza</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">6</th>_x000D_
<td>Salad</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">7</th>_x000D_
<td>Oil</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">8</th>_x000D_
<td>Bread</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
I meet this error when integrate modal bootstrap in angular.
This is my solution to solve this issue.
I share for whom concern.
First step you need install jquery
and bootstrap
by npm
command.
Second you need add declare var $ : any;
in component
And use can use $('#myModal').modal('hide');
on onSave() method
Demo https://stackblitz.com/edit/angular-model-bootstrap-close?file=src/app/app.component.ts
This works for me:
select date_format(date(starttime),'%Y-%m-%d') from data
where date(starttime) >= date '2012-11-02';
Note the format string '%Y-%m-%d' and the format of the input date.
I the following error message when faced this same problem:
The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'.
Solved when I used the same property name, it worked.
(...)
join enderecoST in db.PessoaEnderecos on
new
{
CD_PESSOA = nf.CD_PESSOA_ST,
CD_ENDERECO_PESSOA = nf.CD_ENDERECO_PESSOA_ST
} equals
new
{
enderecoST.CD_PESSOA,
enderecoST.CD_ENDERECO_PESSOA
} into eST
(...)
Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:
git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit
If you want to still have it in your local repository and only remove it from the remote, then you can use:
git push origin +HEAD^:<name of your branch, most likely 'master'>
NSString's method is lowercaseString
(0 arguments), not lowercaseString:
(1 argument).
I ran into this same issue. Someone had logged onto my computer and used their TFS credentials. I'm running VS2012, Windows 7, and the network admins have Credential Manager disabled.
Run this command from a command window with the same user your running visual studio as.
rundll32.exe keymgr.dll,KRShowKeyMgr
You'll see a popup with all your stored credentials. Remove the one for your TFS server.
Note: You will need to restart visual studio because it caches the tfs credentials.
This will definitely work. Orange outline won't show up anymore.. Common for all tags:
*:focus {
outline: none;
}
Specific to some tag, ex: input tag
input:focus{
outline:none;
}
Others have mentioned the architecture differences (little - big endian).
I read the problem that since the memory for the variables is shared, then by writing to one, the others change and, depending on their type, the value could be meaningless.
eg. union{ float f; int i; } x;
Writing to x.i would be meaningless if you then read from x.f - unless that is what you intended in order to look at the sign, exponent or mantissa components of the float.
I think there is also an issue of alignment: If some variables must be word aligned then you might not get the expected result.
eg. union{ char c[4]; int i; } x;
If, hypothetically, on some machine a char had to be word aligned then c[0] and c[1] would share storage with i but not c[2] and c[3].
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
I came across this thread because I was looking to build an absolute URI for a success page. request.build_absolute_uri()
gave me a URI for my current view but to get the URI for my success view I used the following....
request.build_absolute_uri(reverse('success_view_name'))
If you are using <ng-content>
with *ngIf
you are bound to fall into this loop.
Only way out I found was to change *ngIf
to display:none
functionality
I came across this question and inspired by other contributors. I need to append some content to a file once per line. Here is what I did.
class Doh {
def ln = System.getProperty('line.separator')
File file //assume it's initialized
void append(String content) {
file << "$content$ln"
}
}
Pretty neat I think :)
Building on the answers above using the indeterminate state, I've come up with a little bit that handles individual checkboxes and makes them tri-state.
MVC razor uses 2 inputs per checkbox anyway (the checkbox and a hidden with the same name to always force a value in the submit). MVC uses things like "true" as the checkbox value and "false" as the hidden of the same name; makes it amenable to boolean use in api calls. This snippet uses an third hidden to persist the last request values across submits.
Checkboxes initialized with the below will start indeterminate. Checking once turns on the checkbox. Checking twice turns off the checkbox (returning the hidden value of the same name). Checking a third time returns it to indeterminate (and clears out the hidden so a submit will produce a blank).
The page also populates another hidden (e.g. triBox2Orig) with whatever value was on the query string to start, so the 3 states can be initialized and persisted between submits.
$(document).ready(function () {
var initCheckbox = function (chkBox)
{
var hidden = $('[name="' + $(chkBox).prop("name") + '"][type="hidden"]');
var hiddenOrig = $('[name="' + $(chkBox).prop("name") + 'Orig"][type="hidden"]').prop("value");
hidden.prop("origValue", hidden.prop("value"));
if (!chkBox.prop("checked") && !hiddenOrig) chkBox.prop("indeterminate", true);
if (chkBox.prop("indeterminate")) hidden.prop("value", null);
chkBox.change(checkBoxToggleFun);
}
var checkBoxToggleFun = function ()
{
var isChecked = $(this).prop('checked');
var hidden = $('[name="' + $(this).prop("name") + '"][type="hidden"]');
var thirdState = isChecked && hidden.prop("value") === hidden.prop("origValue");
if (thirdState) { // on 3rd click of a checkbox, set it back to indeterminate
$(this).prop("indeterminate", true);
$(this).prop('checked', false);
}
hidden.prop("value", thirdState ? null : hidden.prop("origValue"));
};
var chkBox = $('#triBox1');
initCheckbox(chkBox);
chkBox = $('#triBox2');
initCheckbox(chkBox);
});
This area can have a huge impact on performance and security of the db. Get this wrong, and you could end up in a world of pain.
Because there is always an exception to the rule :)
In the client side handle the click event of the button, use the ClientID property to get he id of the button:
$(document).ready(function() {
$("#<%=myButton.ClientID %>,#<%=muSecondButton.ClientID%>").click(
function() {
$.get("/myPage.aspx",{id:$(this).attr('id')},function(data) {
// do something with the data
return false;
}
});
});
In your page on the server:
protected void Page_Load(object sender,EventArgs e) {
// check if it is an ajax request
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
if (Request.QueryString["id"]==myButton.ClientID) {
// call the click event handler of the myButton here
Response.End();
}
if (Request.QueryString["id"]==mySecondButton.ClientID) {
// call the click event handler of the mySecondButton here
Response.End();
}
}
}
append strings with add function
str1 = "Hello"
str2 = " World"
str3 = str.__add__(str2)
print(str3)
Output
Hello World
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
If you're running with jQuery you can use the datepicker UI library's parseDate function to convert your string to a date:
var d = $.datepicker.parseDate("DD, MM dd, yy", "Sunday, February 28, 2010");
and then follow it up with the formatDate method to get it to the string format you want
var datestrInNewFormat = $.datepicker.formatDate( "mm/dd/yy", d);
If you're not running with jQuery of course its probably not the best plan given you'd need jQuery core as well as the datepicker UI module... best to go with the suggestion from Segfault above to use date.js.
HTH
I would have put this in a comment on the accepted answer, since that's where it belongs, but I can't. So, just in case anyone gets unreliable results, this could be why.
Be careful of the accepted answer, it fails if the time_point is before the epoch.
This line of code:
std::size_t fractional_seconds = ms.count() % 1000;
will yield unexpected values if ms.count() is negative (since size_t is not meant to hold negative values).
When using this approach you have to make sure that none of your values contains something that would be illegal XML – user1151923
I always use the XML method. Make sure you use VALID XML. I have two functions to convert between valid XML and Text. (I tend to strip out the carriage returns as I don't usually need them.
CREATE FUNCTION dbo.udf_ConvertTextToXML (@Text varchar(MAX))
RETURNS varchar(MAX)
AS
BEGIN
SET @Text = REPLACE(@Text,CHAR(10),'')
SET @Text = REPLACE(@Text,CHAR(13),'')
SET @Text = REPLACE(@Text,'<','<')
SET @Text = REPLACE(@Text,'&','&')
SET @Text = REPLACE(@Text,'>','>')
SET @Text = REPLACE(@Text,'''',''')
SET @Text = REPLACE(@Text,'"','"')
RETURN @Text
END
CREATE FUNCTION dbo.udf_ConvertTextFromXML (@Text VARCHAR(MAX))
RETURNS VARCHAR(max)
AS
BEGIN
SET @Text = REPLACE(@Text,'<','<')
SET @Text = REPLACE(@Text,'&','&')
SET @Text = REPLACE(@Text,'>','>')
SET @Text = REPLACE(@Text,''','''')
SET @Text = REPLACE(@Text,'"','"')
RETURN @Text
END
There are both zip and unzip executables (as well as a boat load of other useful applications) in the UnxUtils package available on SourceForge (http://sourceforge.net/projects/unxutils). Copy them to a location in your PATH, such as 'c:\windows', and you will be able to include them in your scripts.
This is not the perfect solution (or the one you asked for) but a decent work-a-round.
Why don't you consider www.cameraftp.com? it supports image upload and online viewer
Below code snippet might help.
import UIKit
extension UIImage {
func cropImage(toRect rect: CGRect) -> UIImage? {
if let imageRef = self.cgImage?.cropping(to: rect) {
return UIImage(cgImage: imageRef)
}
return nil
}
}
There is a JDK dropdown in "job name" -> Configure in Jenkins web ui. It will list all JDKs available in Jenkins configuration.
Since it is your files in your app bundle, I think you can use pathForResource:ofType:
to get the full pathname of your file.
Here is an example:
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"your_file_name"
ofType:@"the_file_extension"];
Haven't tried it myself, but I think
has a lot of potential...
coming from php and classic asp, it's the first java web framework that sounds promising to me....
Edit by original question asker - 2011-06-09
Just wanted to provide an update.
I went with Play and it was exactly what I asked for. It requires very little configuration, and just works out of the box. It is unusual in that it eschews some common Java best-practices in favor of keeping things as simple as possible.
In particular, it makes heavy use of static methods, and even does some introspection on the names of variables passed to methods, something not supported by the Java reflection API.
Play's attitude is that its first goal is being a useful web framework, and sticking to common Java best-practices and idioms is secondary to that. This approach makes sense to me, but Java purists may not like it, and would be better-off with Apache Wicket.
In summary, if you want to build a web-app with convenience and simplicity comparable to a framework like Ruby on Rails, but in Java and with the benefit of Java's tooling (eg. Eclipse), then Play Framework is a great choice.
const
guarantees that a program does not change an object’s value. However, const
does not guarantee which type of initialization the object undergoes.
Consider:
const int mx = numeric_limits<int>::max(); // OK: runtime initialization
The function max()
merely returns a literal value. However, because the initializer is a function call, mx
undergoes runtime initialization. Therefore, you cannot use it as a constant expression:
int arr[mx]; // error: “constant expression required”
constexpr
is a new C++11 keyword that rids you of the need to create macros and hardcoded literals. It also guarantees, under certain conditions, that objects undergo static initialization. It controls the evaluation time of an expression. By enforcing compile-time evaluation of its expression, constexpr
lets you define true constant expressions that are crucial for time-critical applications, system programming, templates, and generally speaking, in any code that relies on compile-time constants.
A constant-expression function is a function declared constexpr
. Its body must be non-virtual and consist of a single return statement only, apart from typedefs and static asserts. Its arguments and return value must have literal types. It can be used with non-constant-expression arguments, but when that is done the result is not a constant expression.
A constant-expression function is meant to replace macros and hardcoded literals without sacrificing performance or type safety.
constexpr int max() { return INT_MAX; } // OK
constexpr long long_max() { return 2147483647; } // OK
constexpr bool get_val()
{
bool res = false;
return res;
} // error: body is not just a return statement
constexpr int square(int x)
{ return x * x; } // OK: compile-time evaluation only if x is a constant expression
const int res = square(5); // OK: compile-time evaluation of square(5)
int y = getval();
int n = square(y); // OK: runtime evaluation of square(y)
A constant-expression object is an object declared constexpr
. It must be initialized with a constant expression or an rvalue constructed by a constant-expression constructor with constant-expression arguments.
A constant-expression object behaves as if it was declared const
, except that it requires initialization before use and its initializer must be a constant expression. Consequently, a constant-expression object can always be used as part of another constant expression.
struct S
{
constexpr int two(); // constant-expression function
private:
static constexpr int sz; // constant-expression object
};
constexpr int S::sz = 256;
enum DataPacket
{
Small = S::two(), // error: S::two() called before it was defined
Big = 1024
};
constexpr int S::two() { return sz*2; }
constexpr S s;
int arr[s.two()]; // OK: s.two() called after its definition
A constant-expression constructor is a constructor declared constexpr
. It can have a member initialization list but its body must be empty, apart from typedefs and static asserts. Its arguments must have literal types.
A constant-expression constructor allows the compiler to initialize the object at compile-time, provided that the constructor’s arguments are all constant expressions.
struct complex
{
// constant-expression constructor
constexpr complex(double r, double i) : re(r), im(i) { } // OK: empty body
// constant-expression functions
constexpr double real() { return re; }
constexpr double imag() { return im; }
private:
double re;
double im;
};
constexpr complex COMP(0.0, 1.0); // creates a literal complex
double x = 1.0;
constexpr complex cx1(x, 0); // error: x is not a constant expression
const complex cx2(x, 1); // OK: runtime initialization
constexpr double xx = COMP.real(); // OK: compile-time initialization
constexpr double imaglval = COMP.imag(); // OK: compile-time initialization
complex cx3(2, 4.6); // OK: runtime initialization
Tips from the book Effective Modern C++ by Scott Meyers about constexpr
:
constexpr
objects are const and are initialized with values known during compilation;constexpr
functions produce compile-time results when called with arguments whose values are known during compilation;constexpr
objects and functions may be used in a wider range of contexts than non-constexpr
objects and functions;constexpr
is part of an object’s or function’s interface.Source: Using constexpr to Improve Security, Performance and Encapsulation in C++.
I just learned something new thanks to Artiso. I gave each module a name in the properties box. These names were also what I declared in the module. When I tried to call my second module, I kept getting an error: Compile error: Expected variable or procedure, not module
After reading Artiso's comment above about not having the same names, I renamed my second module, called it from the first, and problem solved. Interesting stuff! Thanks for the info Artiso!
In case my experience is unclear:
Module Name: AllFSGroupsCY Public Sub AllFSGroupsCY()
Module Name: AllFSGroupsPY Public Sub AllFSGroupsPY()
From AllFSGroupsCY()
Public Sub FSGroupsCY()
AllFSGroupsPY 'will error each time until the properties name is changed
End Sub
Do a cross-domain AJAX call
Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do
then jQuery will add ?callback={some_random_dynamically_generated_method}.
This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Check the following for more information
You have to use UPDATE instead of INSERT:
For Example:
UPDATE table1 SET col_a='k1', col_b='foo' WHERE key_col='1';
UPDATE table1 SET col_a='k2', col_b='bar' WHERE key_col='2';
myUtilDate.toInstant() // Convert from legacy class to modern. `Instant` is a point on the timeline in UTC.
.atZone( // Adjust from UTC to a particular time zone to determine date. Renders a `ZonedDateTime` object.
ZoneId.of( "America/Montreal" ) // Better to specify desired/expected zone explicitly than rely implicitly on the JVM’s current default time zone.
) // Returns a `ZonedDateTime` object.
.getMonthValue() // Extract a month number. Returns a `int` number.
java.time
DetailsThe Answer by Ortomala Lokni for using java.time is correct. And you should be using java.time as it is a gigantic improvement over the old java.util.Date/.Calendar classes. See the Oracle Tutorial on java.time.
I'll add some code showing how to use java.time without regard to java.util.Date, for when you are starting out with fresh code.
Using java.time in a nutshell… An Instant
is a moment on the timeline in UTC. Apply a time zone (ZoneId
) to get a ZonedDateTime
.
The Month
class is a sophisticated enum to represent a month in general. That enum has handy methods such as getting a localized name. And rest assured that the month number in java.time is a sane one, 1-12, not the zero-based nonsense (0-11) found in java.util.Date/.Calendar.
To get the current date-time, time zone is crucial. At any moment the date is not the same around the world. Therefore the month is not the same around the world if near the ending/beginning of the month.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or 'ZoneOffset.UTC'.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Month month = now.getMonth();
int monthNumber = month.getValue(); // Answer to the Question.
String monthName = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
As Obama says "Yes We Can". Here is the link to it. developers.google.com/#jquery
You need to use
ajax.googleapis.com/ajax/libs/jqueryui/[VERSION NO]/jquery-ui.min.js
ajax.googleapis.com/ajax/libs/jqueryui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css
jQuery CDN
code.jquery.com/ui/[VERSION NO]/jquery-ui.min.js
code.jquery.com/ui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css
Microsoft
ajax.aspnetcdn.com/ajax/jquery.ui/[VERSION NO]/jquery-ui.min.js
ajax.aspnetcdn.com/ajax/jquery.ui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css
Find theme names here http://jqueryui.com/themeroller/ in gallery subtab
.
But i would not recommend you hosting from cdn for the following reasons
http://zoompf.com/blog/2010/01/should-you-use-javascript-library-cdns
Mono Develop is what you want, if you have used visual studio you should find it simple enough to get started.
If I recall correctly you should be able to install with sudo apt-get install monodevelop
1)Go to configure build path . 2)Remove unbound JRE library . 3)Add library --> JRE System library .
Then project compile and done ..
Suffered from exact issue. Problem was because of NameValueSectionHandler in .config file. You should use AppSettingsSection instead:
<configuration>
<configSections>
<section name="DEV" type="System.Configuration.AppSettingsSection" />
<section name="TEST" type="System.Configuration.AppSettingsSection" />
</configSections>
<TEST>
<add key="key" value="value1" />
</TEST>
<DEV>
<add key="key" value="value2" />
</DEV>
</configuration>
then in C# code:
AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST");
btw NameValueSectionHandler is not supported any more in 2.0.
The database is a MySQL database, not a phpMyAdmin database. phpMyAdmin is only PHP code that connects to the DB.
mysql_connect('localhost', 'username', 'password') or die (mysql_error());
mysql_select_database('db_name') or die (mysql_error());
// now you are connected
Yes, it is possible to merge .NET executables with libraries. There are multiple tools available to get the job done:
In addition this can be combined with the Mono Linker, which does remove unused code and therefor makes the resulting assembly smaller.
Another possibility is to use .NETZ, which does not only allow compressing of an assembly, but also can pack the dlls straight into the exe. The difference to the above mentioned solutions is that .NETZ does not merge them, they stay separate assemblies but are packed into one package.
.NETZ is a open source tool that compresses and packs the Microsoft .NET Framework executable (EXE, DLL) files in order to make them smaller.
Since Python 3.5, subprocess.run() is recommended over subprocess.check_output():
>>> subprocess.run(['cat','/tmp/text.txt'], stdout=subprocess.PIPE).stdout
b'First line\nSecond line\n'
Since Python 3.7, instead of the above, you can use capture_output=true
parameter to capture stdout and stderr:
>>> subprocess.run(['cat','/tmp/text.txt'], capture_output=True).stdout
b'First line\nSecond line\n'
Also, you may want to use universal_newlines=True
or its equivalent since Python 3.7 text=True
to work with text instead of binary:
>>> stdout = subprocess.run(['cat', '/tmp/text.txt'], capture_output=True, text=True).stdout
>>> print(stdout)
First line
Second line
See subprocess.run() documentation for more information.
You can change from the property of every item.
%run YourNotebookfile.ipynb is working fine;
if you want to import a specific module then just add the import command after the ipynb i.e YourNotebookfile.ipynb having def Add()
then you can just use it
%run YourNotebookfile.ipynb import Add
You are not the first one to think about a "revision number" in Git, but 'wc
' is quite dangerous, since commit can be erased or squashed, and the history revisited.
The "revision number" was especially important for Subversion since it was needed in case of merge (SVN1.5 and 1.6 have improved on that front).
You could end up with a pre-commit hook which would include a revision number in the comment, with an algorithm not involving looking up the all history of a branch to determine the correct number.
Bazaar actually came up with such an algorithm , and it may be a good starting point for what you want to do.
(As Bombe's answer points out, Git has actually an algorithm of its own, based on the latest tag, plus the number of commits, plus a bit of an SHA-1 key). You should see (and upvote) his answer if it works for you.
To illustrate Aaron's idea, you can also append the Git commit hash into an application’s "info" file you are distributing with your application.
That way, the about box would look like:
The applicative number is part of the commit, but the 'application’s "info" file' is generated during the packaging process, effectively linking an applicative build number to a technical revision id.
awk '{a=match($0, $3); print substr($0,a)}'
First you find the position of the start of the third column. With substr you will print the whole line ($0) starting at the position(in this case a) to the end of the line.
Simple printf() function from O'Reilly's Python Cookbook.
import sys
def printf(format, *args):
sys.stdout.write(format % args)
Example output:
i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14
The REAL REAL answer is: For API 21 and higher:
No java code needed.
You can set android:nestedScrollingEnabled="false"
in xml:
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="true"
android:nestedScrollingEnabled="false"
tools:listitem="@layout/adapter_favorite_place">
Do you really need to "build" it from javascript or can you simply return the built HTML from PHP and insert it into the DOM?
Another way of monitoring a child-process is to create a worker thread that will :
This is the correct way to make a pure call. No CSS.
<div style='background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAFCAYAAABW1IzHAAAAHklEQVQokWNgGPaAkZHxPyMj439sYrSQo51PBgsAALa0ECF30JSdAAAAAElFTkSuQmCC)repeat-x center;'></div>
Native way to get the mimetype:
For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()
Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.
While mime_content_type
is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).
If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.
function getMimeType($filename)
{
$mimetype = false;
if(function_exists('finfo_open')) {
// open with FileInfo
} elseif(function_exists('getimagesize')) {
// open with GD
} elseif(function_exists('exif_imagetype')) {
// open with EXIF
} elseif(function_exists('mime_content_type')) {
$mimetype = mime_content_type($filename);
}
return $mimetype;
}
Besides being easier to read (for many people), list comprehensions win the speed race, too:
$ python2.6 -m timeit '[x.lower() for x in ["A","B","C"]]'
1000000 loops, best of 3: 1.03 usec per loop
$ python2.6 -m timeit '[x.upper() for x in ["a","b","c"]]'
1000000 loops, best of 3: 1.04 usec per loop
$ python2.6 -m timeit 'map(str.lower,["A","B","C"])'
1000000 loops, best of 3: 1.44 usec per loop
$ python2.6 -m timeit 'map(str.upper,["a","b","c"])'
1000000 loops, best of 3: 1.44 usec per loop
$ python2.6 -m timeit 'map(lambda x:x.lower(),["A","B","C"])'
1000000 loops, best of 3: 1.87 usec per loop
$ python2.6 -m timeit 'map(lambda x:x.upper(),["a","b","c"])'
1000000 loops, best of 3: 1.87 usec per loop
In C shell - The ampersand is after the greater-than symbol
make >& filename
Assuming you're using a std::ofstream
to write to file, the following snippet will write a std::string
to file in human readable form:
std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
When this error occurred to me was because Pods folder was in iCloud and had no local copy on my computer. Go to your project's folder in Finder and check if there is iCloud's symbol in any of the folders inside it!
Well, your syntax isn't really Python to begin with.
Iterations in Python are over he contents of containers (well, technically it's over iterators), with a syntax for item in container
. In this case, the container is the cars
list, but you want to skip the first and last elements, so that means cars[1:-1]
(python lists are zero-based, negative numbers count from the end, and :
is slicing syntax.
So you want
for c in cars[1:-1]:
do something with c
android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
applicationId ""
minSdkVersion 14
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.android.support:recyclerview-v7:23.0.0'
compile 'com.android.support:appcompat-v7:23.0.1'
}
Adding only android-support-v7-appcompat.jar
to library dependencies is not enough, you have also to import in your project the module that you can find in your SDK at the path \android-sdk\extras\android\support\v7\appcompat
and after that add module dependencies configuring the project structure in this way
otherwise are included only the class files of support library and the app is not able to load the other resources causing the error.
In addition as reVerse suggested replace this
public CustomActionBarDrawerToggle(Activity mActivity,
DrawerLayout mDrawerLayout) {
super(mActivity, mDrawerLayout,new Toolbar(MyActivity.this) ,
R.string.ns_menu_open, R.string.ns_menu_close);
}
with
public CustomActionBarDrawerToggle(Activity mActivity,
DrawerLayout mDrawerLayout) {
super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
}
The selected answer posted here solved one problem, but another is that you'll have to change the app pool to use .Net 2.0.
"SharePoint 2010 uses .NET Framework 3.5, not 4.0. The SharePoint 2010 app pools should be configured as .NET Framework 2.0 using the Integrated Pipeline Mode."
SELECT
[User], Activity,
STUFF(
(SELECT DISTINCT ',' + PageURL
FROM TableName
WHERE [User] = a.[User] AND Activity = a.Activity
FOR XML PATH (''))
, 1, 1, '') AS URLList
FROM TableName AS a
GROUP BY [User], Activity