Was facing this issue, Solved by adding package-info in my package
and the following code in it:
@XmlSchema(
namespace = "http://www.w3schools.com/xml/",
elementFormDefault = XmlNsForm.QUALIFIED,
xmlns = {
@XmlNs(prefix="", namespaceURI="http://www.w3schools.com/xml/")
}
)
package com.gateway.ws.outbound.bean;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
I recommend you just use the requests module.
It is much easier than the built in http clients: http://docs.python-requests.org/en/latest/index.html
Sample usage:
r = requests.get('http://www.thepage.com', proxies={"http":"http://myproxy:3129"})
thedata = r.content
I needed to pass both: a file and an integer. I did it this way:
needed to pass a file to upload: did it as per Sumit's answer.
Request type : POST
Body -> form-data
under the heading KEY, entered the name of the variable ('file' in my backend code).
in the backend:
file = request.files['file']
Next to 'file', there's a drop-down box which allows you to choose between 'File' or 'Text'. Chose 'File' and under the heading VALUE, 'Select files' appeared. Clicked on this which opened a window to select the file.
2. needed to pass an integer:
went to:
Params
entered variable name (e.g.: id) under KEY and its value (e.g.: 1) under VALUE
in the backend:
id = request.args.get('id')
Worked!
There are working combinations of OS, JDK and Eclipse bitness. In my case, I was using a 64-bit JDK with a 32-bit Eclipse on a 64-bit OS. After downgrading the JDK to 32-bit, Eclipse started working.
Use one of the following combinations.
For anyone interested in brevity, here are some "one-liners" that do not require plugins/dependencies that aren't part of a standard Node.js installation:
Public IPv4 and IPv6 address of eth0 as an array:
var ips = require('os').networkInterfaces().eth0.map(function(interface) {
return interface.address;
});
First public IP address of eth0 (usually IPv4) as a string:
var ip = require('os').networkInterfaces().eth0[0].address;
I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:
inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
int curRow = r * sectors;
int nextRow = (r+1) * sectors;
indices.push_back(curRow + s);
indices.push_back(nextRow + s);
indices.push_back(nextRow + (s+1));
indices.push_back(curRow + s);
indices.push_back(nextRow + (s+1));
indices.push_back(curRow + (s+1));
}
void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
float radius, unsigned int rings, unsigned int sectors)
{
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
for(int r = 0; r < rings; ++r) {
for(int s = 0; s < sectors; ++s) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
texcoords.push_back(vec2(s*S, r*R));
vertices.push_back(vec3(x,y,z) * radius);
push_indices(indices, sectors, r, s);
}
}
}
This is strange behavior and although I am unable to say why this is occurring, I can recommend some options.
First, an observation. If you include the image as Content in VS and copy it to the output directory, your code works. If the image is marked as None in VS and you copy it over, it doesn't work.
Solution 1: FileStream
The BitmapImage object accepts a UriSource or StreamSource as a parameter. Let's use StreamSource instead.
FileStream stream = new FileStream("picture.png", FileMode.Open, FileAccess.Read);
Image i = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.StreamSource = stream;
src.EndInit();
i.Source = src;
i.Stretch = Stretch.Uniform;
panel.Children.Add(i);
The problem: stream stays open. If you close it at the end of this method, the image will not show up. This means that the file stays write-locked on the system.
Solution 2: MemoryStream
This is basically solution 1 but you read the file into a memory stream and pass that memory stream as the argument.
MemoryStream ms = new MemoryStream();
FileStream stream = new FileStream("picture.png", FileMode.Open, FileAccess.Read);
ms.SetLength(stream.Length);
stream.Read(ms.GetBuffer(), 0, (int)stream.Length);
ms.Flush();
stream.Close();
Image i = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.StreamSource = ms;
src.EndInit();
i.Source = src;
i.Stretch = Stretch.Uniform;
panel.Children.Add(i);
Now you are able to modify the file on the system, if that is something you require.
try to add android:gravity="center"
into TextView
You can use :enabled pseudo-class, but notice IE<9
does not support it:
button:hover:enabled{
/*your styles*/
}
button:active:enabled{
/*your styles*/
}
Do you already have database entries in the table UserProfile
? If so, when you add new columns the DB doesn't know what to set it to because it can't be NULL
. Therefore it asks you what you want to set those fields in the column new_fields
to. I had to delete all the rows from this table to solve the problem.
(I know this was answered some time ago, but I just ran into this problem and this was my solution. Hopefully it will help anyone new that sees this)
This will redirect the stderr (which is descriptor 2) to the file descriptor 1 which is the the stdout.
2>&1
Now when perform this you are redirecting the stdout to the file sample.s
myprogram > sample.s
Combining the two commands will result in redirecting both stderr and stdout to sample.s
myprogram > sample.s 2>&1
Redirect to /dev/null
if you want to completely silent your application.
myprogram >/dev/null 2>&1
Practically speaking, if the keys were of type NaN, the browser will not change the order.
The following script will output "One", "Two", "Three":
var foo={"3":"Three", "1":"One", "2":"Two"};
for(bar in foo) {
alert(foo[bar]);
}
Whereas the following script will output "Three", "One", "Two":
var foo={"@3":"Three", "@1":"One", "@2":"Two"};
for(bar in foo) {
alert(foo[bar]);
}
Another option is to use a list comprehension:
df['First Season'] = [1 if year > 1990 else year for year in df['First Season']]
Well I think the forloop you've provided in the question is about as good as it gets, but I want to point out that unused variables that have to be assigned can be assigned to the variable named _
, a convention for "discarding" the value assigned. Though the _
reference will hold the value you gave it, code linters and other developers will understand you aren't using that reference. So here's an example:
for _ in range(2):
print('Hello')
Nobody actualy brought it so, the way it was made to work is animation-play-state set to paused.
Yes.
In essence, as long as nothing is output, you can do whatever you want (kill a session, remove user cookies, calculate Pi to 'n' digits, etc.) prior to issuing a location header.
The future is here! The proposals are closer to completion, no more ActiveX or flash or java. Now we can use:
You could use the Drag/Drop to get the file into the browser, or a simple upload control. Once the user has selected a file, you can read it w/ Javascript: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Container sizes
@container-large-desktop
(1140px + @grid-gutter-width) -> (970px + @grid-gutter-width)
in section Container sizes, change 1140
to 970
I hope its help you.
thank you for your correct. link for customize bootstrap: https://getbootstrap.com/docs/3.4/customize/
Can you load the GUIDs into a scratch table then do a
... WHERE var IN SELECT guid FROM #scratchtable
Python 2 will automatically set the type based on the size of the value. A guide of max values can be found below.
The Max value of the default Int in Python 2 is 65535, anything above that will be a long
For example:
>> print type(65535)
<type 'int'>
>>> print type(65536*65536)
<type 'long'>
In Python 3 the long datatype has been removed and all integer values are handled by the Int class. The default size of Int will depend on your CPU architecture.
For example:
The min/max values of each type can be found below:
If the size of your Int exceeds the limits mentioned above, python will automatically change it's type and allocate more memory to handle this increase in min/max values. Where in Python 2, it would convert into 'long', it now just converts into the next size of Int.
Example: If you are using a 32 bit operating system, your max value of an Int will be 2147483647 by default. If a value of 2147483648 or more is assigned, the type will be changed to Int64.
There are different ways to check the size of the int and it's memory allocation.
Note: In Python 3, using the built-in type() method will always return <class 'int'>
no matter what size Int you are using.
Use string instead of char
like
char c[10];
scanf ("%s", c);
I belive it works nice.
Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.
And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.
I'm using PreviewKeyDown
private void _calendar_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e){
switch (e.KeyCode){
case Keys.Down:
case Keys.Right:
//action
break;
case Keys.Up:
case Keys.Left:
//action
break;
}
}
I think this is better.
open: function(event, ui) {
$(this).closest('.ui-dialog').find('.ui-dialog-titlebar-close').hide();
}
This might helps you, closing a wpf window using mvvm with minimal code behind: http://jkshay.com/closing-a-wpf-window-using-mvvm-and-minimal-code-behind/
Messing around & found this CSS seems to contain the SVG in Chrome browser up to the point where the container is larger than the image:
div.inserted-svg-logo svg { max-width:100%; }
Also seems to be working in FF + IE 11.
I know you asked for GET and POST but I will provide CRUD since others may need this just in case: (this was tested in Python 3.7)
#!/usr/bin/env python3
import http.client
import json
print("\n GET example")
conn = http.client.HTTPSConnection("httpbin.org")
conn.request("GET", "/get")
response = conn.getresponse()
data = response.read().decode('utf-8')
print(response.status, response.reason)
print(data)
print("\n POST example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body = {'text': 'testing post'}
json_data = json.dumps(post_body)
conn.request('POST', '/post', json_data, headers)
response = conn.getresponse()
print(response.read().decode())
print(response.status, response.reason)
print("\n PUT example ")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing put'}
json_data = json.dumps(post_body)
conn.request('PUT', '/put', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)
print("\n delete example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing delete'}
json_data = json.dumps(post_body)
conn.request('DELETE', '/delete', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)
You have mentioned "user" twice in your FROM clause. You must provide a table alias to at least one mention so each mention of user. can be pinned to one or the other instance:
FROM article INNER JOIN section
ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user **AS user1** ON article.author\_id = **user1**.id
LEFT JOIN user **AS user2** ON article.modified\_by = **user2**.id
WHERE article.id = '1'
(You may need something different - I guessed which user is which, but the SQL engine won't guess.)
Also, maybe you only needed one "user". Who knows?
In Spring every request will go through the DispatcherServlet. To avoid Static file request through DispatcherServlet(Front contoller) we configure MVC Static content.
Spring 3.1. introduced the ResourceHandlerRegistry to configure ResourceHttpRequestHandlers for serving static resources from the classpath, the WAR, or the file system. We can configure the ResourceHandlerRegistry programmatically inside our web context configuration class.
- we have added the
/js/**
pattern to the ResourceHandler, lets include thefoo.js
resource located in thewebapp/js/
directory- we have added the
/resources/static/**
pattern to the ResourceHandler, lets include thefoo.html
resource located in thewebapp/resources/
directory
@Configuration
@EnableWebMvc
public class StaticResourceConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
registry.addResourceHandler("/resources/static/**")
.addResourceLocations("/resources/");
registry
.addResourceHandler("/js/**")
.addResourceLocations("/js/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new GzipResourceResolver())
.addResolver(new PathResourceResolver());
}
}
XML Configuration
<mvc:annotation-driven />
<mvc:resources mapping="/staticFiles/path/**" location="/staticFilesFolder/js/"
cache-period="60"/>
Spring Boot MVC Static Content if the file is located in the WAR’s webapp/resources folder.
spring.mvc.static-path-pattern=/resources/static/**
You could always use array methods:
var slides = getElementsByClassName("slide");
Array.prototype.forEach.call(slides, function(slide, index) {
Distribute(slides.item(index));
});
What worked for me was the following command:
python -m pip install --upgrade pip
No.
Having said that, there's nothing to stop you doing it. But you'll get inconsistent behaviour with the various browsers. Don't do it. 1 ID per element.
If you want multiple assignations to an element use classes (separated by a space).
Here, Apple Documentation has explained the difference between weak and strong property using various examples :
Here, In this blog author has collected all the properties in same place. It will help to compare properties characteristics :
http://rdcworld-iphone.blogspot.in/2012/12/variable-property-attributes-or.html
I believe I wasted like 1 day on researching it and this what I have come out with.
You need to add the Impersonating user to the Debug folder of your Solution as the Framework will try to access the DLL from this location and place it in Temporary Asp.Net Folder.
So basically follow these 2 steps
Give permission to Temporary Asp.Net Folder under C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
and make sure the user you are adding here is the same you are using while Impersonating.
Add the Impersonating user to the Debug folder of your Solution YourSolutionPath .. \bin\Debug
This should work
There appears to be a bug with appendTo using a frameset ID appending to a FORM in Chrome. Swapped out the attribute type directly with div and it works.
A worked, completed and simple example:
package io.github.baijifeilong.excel;
import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
/**
* Created by [email protected] at 2019/12/6 11:41
*/
public class ExcelBoldTextDemo {
@SneakyThrows
public static void main(String[] args) {
new XSSFWorkbook() {{
XSSFRow row = createSheet().createRow(0);
row.setRowStyle(createCellStyle());
row.getRowStyle().getFont().setBold(true);
row.createCell(0).setCellValue("Alpha");
row.createCell(1).setCellValue("Beta");
row.createCell(2).setCellValue("Gamma");
}}.write(new FileOutputStream("demo.xlsx"));
}
}
You can also cast a random value:
using System;
enum Test {
Value1,
Value2,
Value3
}
class Program {
public static void Main (string[] args) {
var max = Enum.GetValues(typeof(Test)).Length;
var value = (Test)new Random().Next(0, max - 1);
Console.WriteLine(value);
}
}
But you should use a better randomizer like the one in this library of mine.
In my case, I was defining a bean and autowiring it in the constructor of the same class file.
@SpringBootApplication
public class MyApplication {
private MyBean myBean;
public MyApplication(MyBean myBean) {
this.myBean = myBean;
}
@Bean
public MyBean myBean() {
return new MyBean();
}
}
My solution was to move the bean definition to another class file.
@Configuration
public CustomConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
You need to hook to console exit event and not your process.
http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx
The list.append
function does not return any value(but None
), it just adds the value to the list you are using to call that method.
In the first loop round you will assign None
(because the no-return of append
) to a
, then in the second round it will try to call a.append
, as a is None
it will raise the Exception you are seeing
You just need to change it to:
a=[]
for i in range(5):
a.append(i)
print(a)
# [0, 1, 2, 3, 4]
list.append
is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).
If you would like to create a new list based in one list without destroying or mutating it you can do something like this:
a=['a', 'b', 'c']
result = a + ['d']
print result
# ['a', 'b', 'c', 'd']
print a
# ['a', 'b', 'c']
As a corollary only, you can mimic the append
method by doing the following:
a=['a', 'b', 'c']
a = a + ['d']
print a
# ['a', 'b', 'c', 'd']
jQuery will encode and decode for you.
function htmlDecode(value) {_x000D_
return $("<textarea/>").html(value).text();_x000D_
}_x000D_
_x000D_
function htmlEncode(value) {_x000D_
return $('<textarea/>').text(value).html();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function() {_x000D_
$("#encoded")_x000D_
.text(htmlEncode("<img src onerror='alert(0)'>"));_x000D_
$("#decoded")_x000D_
.text(htmlDecode("<img src onerror='alert(0)'>"));_x000D_
});_x000D_
</script>_x000D_
_x000D_
<span>htmlEncode() result:</span><br/>_x000D_
<div id="encoded"></div>_x000D_
<br/>_x000D_
<span>htmlDecode() result:</span><br/>_x000D_
<div id="decoded"></div>
_x000D_
Have you tried using basicHttpBinding instead of wsHttpBinding? If do not need any authentication and the Ws-* implementations are not required, you'd probably be better off with plain old basicHttpBinding. WsHttpBinding implements WS-Security for message security and authentication.
You can get the favicon showing up in Django the same way you can do in any other framework: just use pure HTML.
Add the following code to the header of your HTML template.
Better, to your base HTML template if the favicon is the same across your application.
<link rel="shortcut icon" href="{% static 'favicon/favicon.png' %}"/>
The previous code assumes:
You can find useful information about file format support and how to use favicons in this article of Wikipedia https://en.wikipedia.org/wiki/Favicon.
I can recommend use .png
for universal browser compatibility.
EDIT:
As posted in one comment,
"Don't forget to add {% load staticfiles %}
in top of your template file!"
If you want to remove the file from the remote repo, first remove it from your project with --cache option and then push it:
git rm --cache /path/to/file
git commit -am "Remove file"
git push
(This works even if the file was added to the remote repo some commits ago) Remember to add to .gitignore the file extensions that you don't want to push.
For files encoding...
public class FRomUtf8ToIso {
static File input = new File("C:/Users/admin/Desktop/pippo.txt");
static File output = new File("C:/Users/admin/Desktop/ciccio.txt");
public static void main(String[] args) throws IOException {
BufferedReader br = null;
FileWriter fileWriter = new FileWriter(output);
try {
String sCurrentLine;
br = new BufferedReader(new FileReader( input ));
int i= 0;
while ((sCurrentLine = br.readLine()) != null) {
byte[] isoB = encode( sCurrentLine.getBytes() );
fileWriter.write(new String(isoB, Charset.forName("ISO-8859-15") ) );
fileWriter.write("\n");
System.out.println( i++ );
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
static byte[] encode(byte[] arr){
Charset utf8charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-15");
ByteBuffer inputBuffer = ByteBuffer.wrap( arr );
// decode UTF-8
CharBuffer data = utf8charset.decode(inputBuffer);
// encode ISO-8559-1
ByteBuffer outputBuffer = iso88591charset.encode(data);
byte[] outputData = outputBuffer.array();
return outputData;
}
}
Are you trying to test if two objects are the equal? ie: their properties are equal?
If this is the case, you'll probably have noticed this situation:
var a = { foo : "bar" };
var b = { foo : "bar" };
alert (a == b ? "Equal" : "Not equal");
// "Not equal"
you might have to do something like this:
function objectEquals(obj1, obj2) {
for (var i in obj1) {
if (obj1.hasOwnProperty(i)) {
if (!obj2.hasOwnProperty(i)) return false;
if (obj1[i] != obj2[i]) return false;
}
}
for (var i in obj2) {
if (obj2.hasOwnProperty(i)) {
if (!obj1.hasOwnProperty(i)) return false;
if (obj1[i] != obj2[i]) return false;
}
}
return true;
}
Obviously that function could do with quite a bit of optimisation, and the ability to do deep checking (to handle nested objects: var a = { foo : { fu : "bar" } }
) but you get the idea.
As FOR pointed out, you might have to adapt this for your own purposes, eg: different classes may have different definitions of "equal". If you're just working with plain objects, the above may suffice, otherwise a custom MyClass.equals()
function may be the way to go.
None of the solutions regarding packet size or timeouts made any difference for me. I needed to disable ssl
mysql -u -p -hmyhost.com --disable-ssl db < file.sql
https://dev.mysql.com/doc/refman/5.7/en/encrypted-connections.html
That worked for me,
Right Click on project -> "Run as Maven Test". This will automatically download the missing plugins and than Right Click on project ->"Update Maven project" it removes the error.
You could use the nth-child
pseudo-selector. For example:
table.align-right-3rd-column td:nth-child(3)
{
text-align: right;
}
Then in your table do:
<table class="align-right-3rd-column">
<tr>
<td></td><td></td><td></td>
...
</tr>
</table>
Edit:
Unfortunately, this only works in Firefox 3.5. However, if your table only has 3 columns, you could use the sibling selector, which has much better browser support. Here's what the style sheet would look like:
table.align-right-3rd-column td + td + td
{
text-align: right;
}
This will match any column preceded by two other columns.
new Date().toLocaleDateString()
= "9/13/2015"
You don't need to set innerHTML, just by writing
<p>
<script> document.write(new Date().toLocaleDateString()); </script>
</p>
will work.
P.S.
new Date().toDateString()
= "Sun Sep 13 2015"
Try this to prevent the backspace button in Internet Explorer which by default acts as "Back":
<script language="JavaScript">
$(document).ready(function() {
$(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false;
if (event.keyCode === 8 ) {
var d = event.srcElement || event.target;
if ((d.tagName.toUpperCase() === 'INPUT' &&
(
d.type.toUpperCase() === 'TEXT' ||
d.type.toUpperCase() === 'PASSWORD' ||
d.type.toUpperCase() === 'FILE' ||
d.type.toUpperCase() === 'EMAIL' ||
d.type.toUpperCase() === 'SEARCH' ||
d.type.toUpperCase() === 'DATE' )
) ||
d.tagName.toUpperCase() === 'TEXTAREA') {
doPrevent = d.readOnly || d.disabled;
}
else {
doPrevent = true;
}
}
if (doPrevent) {
event.preventDefault();
}
try {
document.addEventListener('keydown', function (e) {
if ((e.keyCode === 13)) {
//alert('Enter keydown');
e.stopPropagation();
e.preventDefault();
}
}, true);
}
catch (err) {
}
});
});
</script>
JPA's behaviour is correct (meaning as per the specification): objects aren't deleted simply because you've removed them from a OneToMany collection. There are vendor-specific extensions that do that but native JPA doesn't cater for it.
In part this is because JPA doesn't actually know if it should delete something removed from the collection. In object modeling terms, this is the difference between composition and "aggregation*.
In composition, the child entity has no existence without the parent. A classic example is between House and Room. Delete the House and the Rooms go too.
Aggregation is a looser kind of association and is typified by Course and Student. Delete the Course and the Student still exists (probably in other Courses).
So you need to either use vendor-specific extensions to force this behaviour (if available) or explicitly delete the child AND remove it from the parent's collection.
I'm aware of:
If you want to see how much space each folder ocuppes:
du -sh *
s
– summarizeh
– human readable*
– list of foldersDon't be afraid of using raw HTML.
<input type="text" value="<%= Html.Encode(Model.SomeDate.ToShortDateString()) %>" />
The javaw.exe command is identical to java.exe, except that with javaw.exe there is no associated console window
There are several ways that you can transform data from multiple rows into columns.
PIVOT
In SQL Server you can use the PIVOT
function to transform the data from rows to columns:
select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
select value, columnname
from yourtable
) d
pivot
(
max(value)
for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;
See Demo.
columnnames
If you have an unknown number of columnnames
that you want to transpose, then you can use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName)
from yourtable
group by ColumnName, id
order by id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
select value, ColumnName
from yourtable
) x
pivot
(
max(value)
for ColumnName in (' + @cols + N')
) p '
exec sp_executesql @query;
See Demo.
If you do not want to use the PIVOT
function, then you can use an aggregate function with a CASE
expression:
select
max(case when columnname = 'FirstName' then value end) Firstname,
max(case when columnname = 'Amount' then value end) Amount,
max(case when columnname = 'PostalCode' then value end) PostalCode,
max(case when columnname = 'LastName' then value end) LastName,
max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable
See Demo.
This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:
select fn.value as FirstName,
a.value as Amount,
pc.value as PostalCode,
ln.value as LastName,
an.value as AccountNumber
from yourtable fn
left join yourtable a
on fn.somecol = a.somecol
and a.columnname = 'Amount'
left join yourtable pc
on fn.somecol = pc.somecol
and pc.columnname = 'PostalCode'
left join yourtable ln
on fn.somecol = ln.somecol
and ln.columnname = 'LastName'
left join yourtable an
on fn.somecol = an.somecol
and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'
I like to add this method, if you are using an edit form, you can use this code to save the changes in your update(Request $request, $id)
function:
$post = Post::find($id);
$post->fill($request->input())->save();
keep in mind that you have to name your inputs with the same column name. The fill()
function will do all the work for you :)
Here is Beena's answer in ES6 Sans the JQuery dependency.. Thank's Beena!
let resetFormObject = (elementID)=> {
document.getElementById(elementID).getElementsByTagName('input').forEach((input)=>{
switch(input.type) {
case 'password':
case 'text':
case 'textarea':
case 'file':
case 'select-one':
case 'select-multiple':
case 'date':
case 'number':
case 'tel':
case 'email':
input.value = '';
break;
case 'checkbox':
case 'radio':
input.checked = false;
break;
}
});
}
dumps
takes an object and produces a string:
>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'
load
would take a file-like object, read the data from that object, and use that string to create an object:
with open('file.json') as fh:
a = json.load(fh)
Note that dump
and load
convert between files and objects, while dumps
and loads
convert between strings and objects. You can think of the s
-less functions as wrappers around the s
functions:
def dump(obj, fh):
fh.write(dumps(obj))
def load(fh):
return loads(fh.read())
Also note the calendar.timegm() function as described by this blog entry:
import calendar
calendar.timegm(utc_timetuple)
The output should agree with the solution of vaab.
Try this:
var i = 3;
$('#my_table > tbody > tr:eq(' + i + ')').after(html);
or this:
var i = 3;
$('#my_table > tbody > tr').eq( i ).after(html);
or this:
var i = 4;
$('#my_table > tbody > tr:nth-child(' + i + ')').after(html);
All of these will place the row in the same position. nth-child
uses a 1 based index.
If you have a path for that file in the web server, you can get the real path in the server's file system using ServletContext.getRealPath(). Note that it is not guaranteed to work in every container (as a container is not required to unpack the WAR file and store the content in the file system - most do though). And I guess it won't work with files in /WEB-INF, as they don't have a virtual path.
The alternative would be to use ServletContext.getResource() which returns a URI. This URI may be a 'file:' URL, but there's no guarantee for that.
Decoding is redundant
You only had this "error" in the first place, because of a misunderstanding of what's happening.
You get the b
because you encoded to utf-8
and now it's a bytes object.
>> type("text".encode("utf-8"))
>> <class 'bytes'>
Fixes:
If you have access to Excel, look in the "Statistical Functions" section of the Function Reference within Help. For straight-line best-fit, you need SLOPE and INTERCEPT and the equations are right there.
Oh, hang on, they're also defined online here: http://office.microsoft.com/en-us/excel/HP052092641033.aspx for SLOPE, and there's a link to INTERCEPT. OF course, that assumes MS don't move the page, in which case try Googling for something like "SLOPE INTERCEPT EQUATION Excel site:microsoft.com" - the link given turned out third just now.
I think this is just what you'er looking for:
ls | xargs -I {} mv {} Unix_{}
Yes, it is simple yet elegant and powerful, and also one-liner. You can get more detailed intro from me on the page:Rename Files and Directories (Add Prefix)
Unfortunately historical ticker data that is free is hard to come by. Now that opentick is dead, I dont know of any other provider.
In a previous lifetime I worked for a hedgefund that had an automated trading system, and we used historical data profusely.
We used TickData for our source. Their prices were reasonable, and the data had sub second resolution.
I know that this is an old question, but it was the first answer on a Google search, so it seems relevant. I recently had this same problem. The solution in my case was to just use the Public Suffix List:
https://publicsuffix.org/learn/
The suggested language specific libraries listed should all allow for easy validation of not just domain format, but also top level domain validity.
I think you just need COUNT(DISTINCT post_id) FROM votes
.
See "4.2.7. Aggregate Expressions" section in http://www.postgresql.org/docs/current/static/sql-expressions.html.
EDIT: Corrected my careless mistake per Erwin's comment.
imprime en linea los datos con un espaciado determinado, así tendrás columnas de datos de la misma variable y será más claro
Print all data in line, so you have rows with the data you need, i just solve the same problem like this, just make sur you had asignad a constant data size and spacement between, I made this
Serial.print("cuenta q2: ");
Serial.print( cuenta_pulsos_encoder_1,3);
Serial.print("\t");
Serial.print(q2_real,4);
Serial.print("\t");
Serial.print("cuenta q3: ");
Serial.print( cuenta_pulsos_encoder_2,3);
Serial.print("\t");
Serial.print(q3_real,4);
Serial.print("\t");
Serial.print("cuenta q4: ");
Serial.print( cuenta_pulsos_encoder_3,3);
Serial.print("\t");
Serial.println(q4_real,4);
My issue was resolved by replacing the'SID' in URL with 'service name' and correct host.
I struggled to understand the proxy settings for websockets for https therefore let me put clarity here what i realized.
First you need to enable proxy
and proxy_wstunnel
apache modules and the apache configuration file will look like this.
<IfModule mod_ssl.c>
<VirtualHost _default_:443>
ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/your_project_public_folder
SSLEngine on
SSLCertificateFile /etc/ssl/certs/path_to_your_ssl_certificate
SSLCertificateKeyFile /etc/ssl/private/path_to_your_ssl_key
<Directory /var/www/your_project_public_folder>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
php_flag display_errors On
</Directory>
ProxyRequests Off
ProxyPass /wss/ ws://example.com:port_no
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</IfModule>
in your frontend application use the url "wss://example.com/wss/"
this is very important mostly if you are stuck with websockets you might be making mistake in the front end url. You probably putting url wrongly like below.
wss://example.com:8080/wss/ -> port no should not be mentioned
ws://example.com/wss/ -> url should start with wss only.
wss://example.com/wss -> url should end with / -> most important
also interesting part is the last /wss/
is same as proxypass
value if you writing proxypass /ws/
then in the front end you should write /ws/
in the end of url.
If you are coming from Microsoft Excel, the following functions will be similar to LEFT()
, RIGHT()
, and MID()
functions.
# This counts from the left and then extract n characters
str_left <- function(string, n) {
substr(string, 1, n)
}
# This counts from the right and then extract n characters
str_right <- function(string, n) {
substr(string, nchar(string) - (n - 1), nchar(string))
}
# This extract characters from the middle
str_mid <- function(string, from = 2, to = 5){
substr(string, from, to)
}
Examples:
x <- "some text in a string"
str_left(x, 4)
[1] "some"
str_right(x, 6)
[1] "string"
str_mid(x, 6, 9)
[1] "text"
That's the job that GNU's automake/autoconf are designed to solve. You might want to investigate them.
Alternatively you can set environment variables on your different platforms and make you Makefile conditional against them.
I found the easiest way to do this, especially if you're adding your table view inside of tab bar is to first add a view and then add the table view inside that view. This gives you the top margin guides you're looking for.
JB hit the nail on the head. The only thing I can add is that Java 8 doesn't do pure parallel processing, it does paraquential. Yes I wrote the article and I've been doing F/J for thirty years so I do understand the issue.
In the page load event you set your label
lbl_username.text = "some text";
decodeURIComponent()
is fine, but you never want ot use encodeURIComponent()
directly. This fails to escape reserved characters like *
, !
, '
, (
, and )
. Check out RFC3986, where this is defined, for more info on that. The Mozilla Developer Network documentation gives both a good explanation and a solution. Explanation...
To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
Solution...
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
In case you're not sure, check out a good, working demo at JSBin.com. Compare this with a bad, working demo at JSBin.com using encodeURIComponent()
directly.
Good code results:
thing%2athing%20thing%21
Bad code results from encodeURIComponent()
:
thing*thing%20thing!
Using a <br/>
for making a new row it's a bad solution from the start.
Make your container #div1 to have a width equal to 3 child-divs.
<br/>
in my opinion should not be used in other places than paragraphs.
import re
def rm_suffix(url = 'abcdc.com', suffix='\.com'):
return(re.sub(suffix+'$', '', url))
I want to repeat this answer as the most expressive way to do it. Of course, the following would take less CPU time:
def rm_dotcom(url = 'abcdc.com'):
return(url[:-4] if url.endswith('.com') else url)
However, if CPU is the bottle neck why write in Python?
When is CPU a bottle neck anyway? In drivers, maybe.
The advantages of using regular expression is code reusability. What if you next want to remove '.me', which only has three characters?
Same code would do the trick:
>>> rm_sub('abcdc.me','.me')
'abcdc'
If you handle "adding tag" via JScript:
<form ...>
<button onclick="...">any text you want</button>
</form>
Or above if handle via page reload
Yet again, I am going to offer one more solution :) I was using Humphrey's code, so this is based off of that.
However, I ran into issues with the field being a ModelChoiceField
. Everything would work on the first request. However, if the formset tried to add a new item and failed validation, something was going wrong with the "existing" forms where the SELECTED
option was being reset to the default ---------
.
Anyway, I couldn't figure out how to fix that. So instead, (and I think this is actually cleaner in the form), I made the fields HiddenInputField()
. This just means you have to do a little more work in the template.
So the fix for me was to simplify the Form:
class ItemForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ItemForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.id:
self.fields['sku'].widget=HiddenInput()
And then in the template, you'll need to do some manual looping of the formset.
So, in this case you would do something like this in the template:
<div>
{{ form.instance.sku }} <!-- This prints the value -->
{{ form }} <!-- Prints form normally, and makes the hidden input -->
</div>
This worked a little better for me and with less form manipulation.
Here's a custom hook that I use which I believe is more intuitive than using usePrevious
.
import { useRef, useEffect } from 'react'
// useTransition :: Array a => (a -> Void, a) -> Void
// |_______| |
// | |
// callback deps
//
// The useTransition hook is similar to the useEffect hook. It requires
// a callback function and an array of dependencies. Unlike the useEffect
// hook, the callback function is only called when the dependencies change.
// Hence, it's not called when the component mounts because there is no change
// in the dependencies. The callback function is supplied the previous array of
// dependencies which it can use to perform transition-based effects.
const useTransition = (callback, deps) => {
const func = useRef(null)
useEffect(() => {
func.current = callback
}, [callback])
const args = useRef(null)
useEffect(() => {
if (args.current !== null) func.current(...args.current)
args.current = deps
}, deps)
}
You'd use useTransition
as follows.
useTransition((prevRate, prevSendAmount, prevReceiveAmount) => {
if (sendAmount !== prevSendAmount || rate !== prevRate && sendAmount > 0) {
const newReceiveAmount = sendAmount * rate
// do something
} else {
const newSendAmount = receiveAmount / rate
// do something
}
}, [rate, sendAmount, receiveAmount])
Hope that helps.
For completeness:
Along the lines of Chase's answer, I usually use as.data.frame
to coerce the matrix to a data.frame:
m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))
EDIT: speed test data.frame
vs. as.data.frame
system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
8.005 0.108 8.165
system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
3.759 0.048 3.802
Yes, it appears to be faster (by about 2 times).
The top answers here mention using T to open a file in a new tab silently, or Ctrl+WW to hop back to nerd-tree window after file is opened normally.
IF WORKING WITH BUFFERS: use go to open a file in a new buffer, silently, meaning your focus will remain on nerd-tree.
Use this to open multiple files fast :)
Expression you are looking for may be:
...
return any( isinstance(e, list) for e in my_list )
Testing:
>>> my_list = [1,2]
>>> any( isinstance(e, list) for e in my_list )
False
>>> my_list = [1,2, [3,4,5]]
>>> any( isinstance(e, list) for e in my_list )
True
>>>
Based on the other answer by @Mechanical Snail, except without the use of python, which I found to be wildly overkill. Add this to your ~/.gitconfig
:
[github]
user = "your-name-here"
[alias]
hub-new-repo = "!REPO=$(basename $PWD) GHUSER=$(git config --get github.user); curl -u $GHUSER https://api.github.com/user/repos -d {\\\"name\\\":\\\"$REPO\\\"} --fail; git remote add origin [email protected]:$GHUSER/$REPO.git; git push origin master"
implementation Without a Controller.
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>_x000D_
<body>_x000D_
_x000D_
<script>_x000D_
var app = angular.module("myShoppingList", []); _x000D_
</script>_x000D_
_x000D_
<div ng-app="myShoppingList" ng-init="products = ['Milk','Bread','Cheese']">_x000D_
<ul>_x000D_
<li ng-repeat="x in products track by $index">{{x}}_x000D_
<span ng-click="products.splice($index,1)">×</span>_x000D_
</li>_x000D_
</ul>_x000D_
<input ng-model="addItem">_x000D_
<button ng-click="products.push(addItem)">Add</button>_x000D_
</div>_x000D_
_x000D_
<p>Click the little x to remove an item from the shopping list.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
The splice() method adds/removes items to/from an array.
array.splice(index, howmanyitem(s), item_1, ....., item_n)
index: Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array.
howmanyitem(s): Optional. The number of items to be removed. If set to 0, no items will be removed.
item_1, ..., item_n: Optional. The new item(s) to be added to the array
Two complement is found out by adding one to 1'st complement of the given number.
Lets say we have to find out twos complement of 10101
then find its ones complement, that is, 01010
add 1
to this result, that is, 01010+1=01011
, which is the final answer.
Here are a variety of ways to do this in base R
including an alternative aggregate
approach. The examples below return means per month, which I think is what you requested. Although, the same approach could be used to return means per person:
Using ave
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
Rate1.mean <- with(my.data, ave(Rate1, Month, FUN = function(x) mean(x, na.rm = TRUE)))
Rate2.mean <- with(my.data, ave(Rate2, Month, FUN = function(x) mean(x, na.rm = TRUE)))
my.data <- data.frame(my.data, Rate1.mean, Rate2.mean)
my.data
Using by
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
by.month <- as.data.frame(do.call("rbind", by(my.data, my.data$Month, FUN = function(x) colMeans(x[,3:4]))))
colnames(by.month) <- c('Rate1.mean', 'Rate2.mean')
by.month <- cbind(Month = rownames(by.month), by.month)
my.data <- merge(my.data, by.month, by = 'Month')
my.data
Using lapply
and split
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
ly.mean <- lapply(split(my.data, my.data$Month), function(x) c(Mean = colMeans(x[,3:4])))
ly.mean <- as.data.frame(do.call("rbind", ly.mean))
ly.mean <- cbind(Month = rownames(ly.mean), ly.mean)
my.data <- merge(my.data, ly.mean, by = 'Month')
my.data
Using sapply
and split
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.data
sy.mean <- t(sapply(split(my.data, my.data$Month), function(x) colMeans(x[,3:4])))
colnames(sy.mean) <- c('Rate1.mean', 'Rate2.mean')
sy.mean <- data.frame(Month = rownames(sy.mean), sy.mean, stringsAsFactors = FALSE)
my.data <- merge(my.data, sy.mean, by = 'Month')
my.data
Using aggregate
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.summary <- with(my.data, aggregate(list(Rate1, Rate2), by = list(Month),
FUN = function(x) { mon.mean = mean(x, na.rm = TRUE) } ))
my.summary <- do.call(data.frame, my.summary)
colnames(my.summary) <- c('Month', 'Rate1.mean', 'Rate2.mean')
my.summary
my.data <- merge(my.data, my.summary, by = 'Month')
my.data
EDIT: June 28, 2020
Here I use aggregate
to obtain the column means
of an entire matrix
by group where group is defined in an external vector
:
my.group <- c(1,2,1,2,2,3,1,2,3,3)
my.data <- matrix(c( 1, 2, 3, 4, 5,
10, 20, 30, 40, 50,
2, 4, 6, 8, 10,
20, 30, 40, 50, 60,
20, 18, 16, 14, 12,
1000, 1100, 1200, 1300, 1400,
2, 3, 4, 3, 2,
50, 40, 30, 20, 10,
1001, 2001, 3001, 4001, 5001,
1000, 2000, 3000, 4000, 5000), nrow = 10, ncol = 5, byrow = TRUE)
my.data
my.summary <- aggregate(list(my.data), by = list(my.group), FUN = function(x) { my.mean = mean(x, na.rm = TRUE) } )
my.summary
# Group.1 X1 X2 X3 X4 X5
#1 1 1.666667 3.000 4.333333 5.000 5.666667
#2 2 25.000000 27.000 29.000000 31.000 33.000000
#3 3 1000.333333 1700.333 2400.333333 3100.333 3800.333333
It is also important to encode the rest of the text in order to protect from possible script injection attacks
function insertTextWithLineBreaks(text, targetElement) {
var textWithNormalizedLineBreaks = text.replace('\r\n', '\n');
var textParts = textWithNormalizedLineBreaks.split('\n');
for (var i = 0; i < textParts.length; i++) {
targetElement.appendChild(document.createTextNode(textParts[i]));
if (i < textParts.length - 1) {
targetElement.appendChild(document.createElement('br'));
}
}
}
A recursive method to check if a Class<?>
is a sub class of another Class<?>
...
Improved version of @To Kra's answer:
protected boolean isSubclassOf(Class<?> clazz, Class<?> superClass) {
if (superClass.equals(Object.class)) {
// Every class is an Object.
return true;
}
if (clazz.equals(superClass)) {
return true;
} else {
clazz = clazz.getSuperclass();
// every class is Object, but superClass is below Object
if (clazz.equals(Object.class)) {
// we've reached the top of the hierarchy, but superClass couldn't be found.
return false;
}
// try the next level up the hierarchy.
return isSubclassOf(clazz, superClass);
}
}
What others have forgotten is Ctrl+Shift+L for easy text search. It searches everywhere and it is fast and efficient. This might be a Sprint tool suit which is an extension of eclipse (and it might be available in newer versions)
I just ran into the same kind of error using RSelenium::rsDriver()
's default chromever = "latest"
setting which resulted in the failed attempt to combine chromedriver 75.0.3770.8
with latest google-chrome-stable 74.0.3729.157
:
session not created: This version of ChromeDriver only supports Chrome version 75
Since this obviously seems to be a recurring and pretty annoying issue, I have come up with the following workaround to always use the latest compatible ChromeDriver version:
rD <- RSelenium::rsDriver(browser = "chrome",
chromever =
system2(command = "google-chrome-stable",
args = "--version",
stdout = TRUE,
stderr = TRUE) %>%
stringr::str_extract(pattern = "(?<=Chrome )\\d+\\.\\d+\\.\\d+\\.") %>%
magrittr::extract(!is.na(.)) %>%
stringr::str_replace_all(pattern = "\\.",
replacement = "\\\\.") %>%
paste0("^", .) %>%
stringr::str_subset(string =
binman::list_versions(appname = "chromedriver") %>%
dplyr::last()) %>%
as.numeric_version() %>%
max() %>%
as.character())
The above code is only tested under Linux and makes use of some tidyverse packages (install them beforehand or rewrite it in base R). For other operating systems you might have to adapt it a bit, particularly replace command = "google-chrome-stable"
with the system-specific command to launch Google Chrome:
On macOS it should be enough to replace command = "google-chrome-stable"
with command = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
.
On Windows a plattform-specific bug prevents us from calling the Google Chrome binary directly to get its version number. Instead do the following:
rD <- RSelenium::rsDriver(browser = "chrome",
chromever =
system2(command = "wmic",
args = 'datafile where name="C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe" get Version /value',
stdout = TRUE,
stderr = TRUE) %>%
stringr::str_extract(pattern = "(?<=Version=)\\d+\\.\\d+\\.\\d+\\.") %>%
magrittr::extract(!is.na(.)) %>%
stringr::str_replace_all(pattern = "\\.",
replacement = "\\\\.") %>%
paste0("^", .) %>%
stringr::str_subset(string =
binman::list_versions(appname = "chromedriver") %>%
dplyr::last())
as.numeric_version() %>%
max() %>%
as.character())
Basically, the code just ensures the latest ChromeDriver version matching the major-minor-patch version number of the system's stable Google Chrome browser is passed as chromever
argument. This procedure should adhere to the official ChromeDriver versioning scheme. Quote:
- ChromeDriver uses the same version number scheme as Chrome (...)
- Each version of ChromeDriver supports Chrome with matching major, minor, and build version numbers. For example, ChromeDriver 73.0.3683.20 supports all Chrome versions that start with 73.0.3683.
Use a list instead and replace your foreach
loop with a for
loop:
@model IList<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(x => x[i].IP)
@Html.CheckBoxFor(x => x[i].Checked)
</td>
<td>
@Html.DisplayFor(x => x[i].IP)
</td>
</tr>
}
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
Alternatively you could use an editor template:
@model IEnumerable<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml
which will automatically be rendered for each element of the collection:
@model BlockedIPViewModel
<tr>
<td>
@Html.HiddenFor(x => x.IP)
@Html.CheckBoxFor(x => x.Checked)
</td>
<td>
@Html.DisplayFor(x => x.IP)
</td>
</tr>
The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article
.
Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
def __eq__(self,other):
return self.value == other.value
node1 = Node(1)
node2 = Node(1)
print(f'node1 id:{id(node1)}')
print(f'node2 id:{id(node2)}')
print(node1 == node2)
>>> node1 id:4396696848
>>> node2 id:4396698000
>>> True
Try using mocha's --grep
option:
-g, --grep <pattern> only run tests matching <pattern>
You can use any valid JavaScript regex as <pattern>
. For instance, if we have test/mytest.js
:
it('logs a', function(done) {
console.log('a');
done();
});
it('logs b', function(done) {
console.log('b');
done();
});
Then:
$ mocha -g 'logs a'
To run a single test. Note that this greps across the names of all describe(name, fn)
and it(name, fn)
invocations.
Consider using nested describe()
calls for namespacing in order to make it easy to locate and select particular sets.
$header3 = @("Field_1","Field_2","Field_3","Field_4","Field_5")
Import-Csv $fileName -Header $header3 -Delimiter "`t" | select -skip 3 | Foreach-Object {
$record = $indexName
foreach ($property in $_.PSObject.Properties){
#doSomething $property.Name, $property.Value
if($property.Name -like '*TextWrittenAsNumber*'){
$record = $record + "," + '"' + $property.Value + '"'
}
else{
$record = $record + "," + $property.Value
}
}
$array.add($record) | out-null
#write-host $record
}
Java-Projects does not have ONE path! Java-Projects has multiple pathes even so one Class can have multiple locations in different classpath's in one "Project".
So if you have a calculator.jar located in your JRE/lib and one calculator.jar with the same classes on a CD: if you execute the calculator.jar the classes from the CD, the java-vm will take the classes from the JRE/lib!
This problem often comes to programmers who like to load resources deployed inside of the Project. In this case,
System.getResource("/likebutton.png")
is taken for example.
I've spoken to Tab Atkins (author of the flexbox spec) about this, and this is what we came up with:
HTML:
<div class="content">
<div class="box">
<div class="column">Column 1</div>
<div class="column">Column 2</div>
<div class="column">Column 3</div>
</div>
</div>
CSS:
.content {
flex: 1;
display: flex;
overflow: auto;
}
.box {
display: flex;
min-height: min-content; /* needs vendor prefixes */
}
Here are the pens:
The reason this works is because align-items: stretch
doesn't shrink its items if they have an intrinsic height, which is accomplished here by min-content
.
First of all, if you open catalina.bat with text editor, you see that: "Do not set the variables in this script....." So never change it in that script, instead you can do below steps:
Then set 2 variables in that bat file such as:
set CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
set JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"
Lastly run that at cmd that: "catalina.bat jpda start"
In IDE, create remote debug configuration and set host to related server ip and port to 8000.
I think that's better to use flex boxes (compatibility) than the absolute position. Here's example from me in pure css.
.container{_x000D_
background-color:green;_x000D_
height:500px;_x000D_
_x000D_
/*FLEX BOX */_x000D_
display: -ms-flexbox;_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-direction: column;_x000D_
-ms-flex-direction: column;_x000D_
flex-direction: column;_x000D_
-webkit-flex-wrap: nowrap;_x000D_
-ms-flex-wrap: nowrap;_x000D_
flex-wrap: nowrap;_x000D_
-webkit-justify-content: flex-start;_x000D_
-ms-flex-pack: start;_x000D_
justify-content: flex-start;_x000D_
-webkit-align-content: stretch;_x000D_
-ms-flex-line-pack: stretch;_x000D_
align-content: stretch;_x000D_
-webkit-align-items: flex-start;_x000D_
-ms-flex-align: start;_x000D_
align-items: flex-start;_x000D_
}_x000D_
_x000D_
.elem1{_x000D_
background-color:red;_x000D_
padding:20px;_x000D_
_x000D_
/*FLEX BOX CHILD */_x000D_
-webkit-order: 0;_x000D_
-ms-flex-order: 0;_x000D_
order: 0;_x000D_
-webkit-flex: 0 1 auto;_x000D_
-ms-flex: 0 1 auto;_x000D_
flex: 0 1 auto;_x000D_
-webkit-align-self: flex-end;_x000D_
-ms-flex-item-align: end;_x000D_
align-self: flex-end;_x000D_
_x000D_
}
_x000D_
<div class="container">_x000D_
TOP OF CONTAINER _x000D_
<div class="elem1">_x000D_
Nam pretium turpis et arcu. Sed a libero. Sed mollis, eros et ultrices tempus, mauris ipsum aliquam libero, non adipiscing dolor urna a orci._x000D_
_x000D_
Mauris sollicitudin fermentum libero. Pellentesque libero tortor, tincidunt et, tincidunt eget, semper nec, quam. Quisque id mi._x000D_
_x000D_
Donec venenatis vulputate lorem. Maecenas ullamcorper, dui et placerat feugiat, eros pede varius nisi, condimentum viverra felis nunc et lorem. Curabitur vestibulum aliquam leo._x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
I reproduced your issue on my Windows 8.1 system :
I got the same message you did. Thinking that it might be the environment variable, I did the following :
It came up successfully !
You didn't mention the version you're using, but if you're using rc5 or rc6, that "old" style of form has been deprecated. Take a look at this for guidance on the "new" forms techniques: https://angular.io/docs/ts/latest/guide/forms.html
Well I would like to help you by posting a sample program and its output
Program:
t = input("")
x = [None]*t
y = [[None]*t]*t
for i in range(1, t+1):
x[i-1] = i;
for j in range(1, t+1):
y[i-1][j-1] = j;
print x
print y
Output :-
2
[1, 2]
[[1, 2], [1, 2]]
I hope this clears some very basic concept of yours regarding their declaration.
To initialize them with some other specific values, like initializing them with 0
.. you can declare them as:
x = [0]*10
Hope it helps..!! ;)
Open the start menu and type cmd
into the search box
Hold Ctrl + Shift
and press Enter
This runs the Command Prompt in Administrator mode.
Now type regsvr32 MyComobject.dll
if you are developing QGIS plugins then simply
self.dlg.cbo_load_net.currentIndex()
I know, it's a tad bit too late to answer, but all you need to do is, force all forms dirty. Take a look at the following snippet:
angular.forEach($scope.myForm.$error.required, function(field) {
field.$setDirty();
});
and then you can check if your form is valid using:
if($scope.myForm.$valid) {
//Do something
}
and finally, I guess, you would want to change your route if everything looks good:
$location.path('/somePath');
Edit: form won't register itself on the scope until submit event is trigger. Just use ng-submit directive to call a function, and wrap the above in that function, and it should work.
Download MSBuild with the link from @Nicodemeus answer was OK, yet the installation was broken until I've added these keys into a register:
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\12.0]
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
Here are steps:
It should work.
On Ubuntu after installing lxc-docker you need to add your user to the docker user group:
sudo usermod -a -G docker myusername
This is because of the socket file permissions:
srw-rw---- 1 root docker 0 Mar 20 07:43 /var/run/docker.sock
DO NOT RUN usermod WITHOUT "-a" as suggested in one of the other comments or it will wipe your additional groups setting and will just leave the "docker" group
This is what will happen:
? ~ id pawel
uid=1000(pawel) gid=1000(pawel) groups=1000(pawel),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),108(lpadmin),124(sambashare),998(docker)
? ~ usermod -G docker pawel
? ~ id pawel
uid=1000(pawel) gid=1000(pawel) groups=1000(pawel),998(docker)
Add to your panel's style code something like this:
<asp:Panel ID="myPanel" runat="Server" CssClass="myPanelCSS" style="overflow-y:auto; overflow-x:hidden"></asp:Panel>
Use WebRequest. From Scott Hanselman:
public static string HttpPost(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Proxy = new System.Net.WebProxy(ProxyString, true);
//Add these, as we're doing a POST
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//We need to count how many bytes we're sending.
//Post'ed Faked Forms should be name=value&
byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream ();
os.Write (bytes, 0, bytes.Length); //Push it out there
os.Close ();
System.Net.WebResponse resp = req.GetResponse();
if (resp== null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
You can also use LocalBroadcast
for this purpose. Here is a quick guide
Create a broadcast receiver:
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("speedExceeded"));
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Double currentSpeed = intent.getDoubleExtra("currentSpeed", 20);
Double currentLatitude = intent.getDoubleExtra("latitude", 0);
Double currentLongitude = intent.getDoubleExtra("longitude", 0);
// ... react to local broadcast message
}
This is how you can trigger it
Intent intent = new Intent("speedExceeded");
intent.putExtra("currentSpeed", currentSpeed);
intent.putExtra("latitude", latitude);
intent.putExtra("longitude", longitude);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
unRegister receiver in onPause:
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
If you're displaying a user-readable file name, you do not want to use lastPathComponent
. Instead, pass the full path to NSFileManager's displayNameAtPath:
method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.
When you are storing a DataFrame
object into a csv file using the to_csv
method, you probably wont be needing to store the preceding indices of each row of the DataFrame
object.
You can avoid that by passing a False
boolean value to index
parameter.
Somewhat like:
df.to_csv(file_name, encoding='utf-8', index=False)
So if your DataFrame object is something like:
Color Number
0 red 22
1 blue 10
The csv file will store:
Color,Number
red,22
blue,10
instead of (the case when the default value True
was passed)
,Color,Number
0,red,22
1,blue,10
Here is a little something I cooked up today. Seems to work for me. Basically you override the Add method in your base namespace to do a check and then call the base's Add method in order to actually add it. Hope this works for you
using System;
using System.Collections.Generic;
using System.Collections;
namespace Main
{
internal partial class Dictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
{
internal new virtual void Add(TKey key, TValue value)
{
if (!base.ContainsKey(key))
{
base.Add(key, value);
}
}
}
internal partial class List<T> : System.Collections.Generic.List<T>
{
internal new virtual void Add(T item)
{
if (!base.Contains(item))
{
base.Add(item);
}
}
}
public class Program
{
public static void Main()
{
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1,"b");
dic.Add(1,"a");
dic.Add(2,"c");
dic.Add(1, "b");
dic.Add(1, "a");
dic.Add(2, "c");
string val = "";
dic.TryGetValue(1, out val);
Console.WriteLine(val);
Console.WriteLine(dic.Count.ToString());
List<string> lst = new List<string>();
lst.Add("b");
lst.Add("a");
lst.Add("c");
lst.Add("b");
lst.Add("a");
lst.Add("c");
Console.WriteLine(lst[2]);
Console.WriteLine(lst.Count.ToString());
}
}
}
As described here, this is another approach that takes care of symlinks too:
/**
* Copy a file, or recursively copy a folder and its contents
* @author Aidan Lister <[email protected]>
* @version 1.0.1
* @link http://aidanlister.com/2004/04/recursively-copying-directories-in-php/
* @param string $source Source path
* @param string $dest Destination path
* @param int $permissions New folder creation permissions
* @return bool Returns true on success, false on failure
*/
function xcopy($source, $dest, $permissions = 0755)
{
$sourceHash = hashDirectory($source);
// Check for symlinks
if (is_link($source)) {
return symlink(readlink($source), $dest);
}
// Simple copy for a file
if (is_file($source)) {
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest, $permissions);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
if($sourceHash != hashDirectory($source."/".$entry)){
xcopy("$source/$entry", "$dest/$entry", $permissions);
}
}
// Clean up
$dir->close();
return true;
}
// In case of coping a directory inside itself, there is a need to hash check the directory otherwise and infinite loop of coping is generated
function hashDirectory($directory){
if (! is_dir($directory)){ return false; }
$files = array();
$dir = dir($directory);
while (false !== ($file = $dir->read())){
if ($file != '.' and $file != '..') {
if (is_dir($directory . '/' . $file)) { $files[] = hashDirectory($directory . '/' . $file); }
else { $files[] = md5_file($directory . '/' . $file); }
}
}
$dir->close();
return md5(implode('', $files));
}
Another common solution is adding "Other.." option to the drop down and when selected show text box that is otherwise hidden. Then when submitting the form, assign hidden field value with either the drop down or textbox value and in the server side code check the hidden value.
Example: http://jsfiddle.net/c258Q/
HTML code:
Please select: <form onsubmit="FormSubmit(this);">
<input type="hidden" name="fruit" />
<select name="fruit_ddl" onchange="DropDownChanged(this);">
<option value="apple">Apple</option>
<option value="orange">Apricot </option>
<option value="melon">Peach</option>
<option value="">Other..</option>
</select> <input type="text" name="fruit_txt" style="display: none;" />
<button type="submit">Submit</button>
</form>
JavaScript:
function DropDownChanged(oDDL) {
var oTextbox = oDDL.form.elements["fruit_txt"];
if (oTextbox) {
oTextbox.style.display = (oDDL.value == "") ? "" : "none";
if (oDDL.value == "")
oTextbox.focus();
}
}
function FormSubmit(oForm) {
var oHidden = oForm.elements["fruit"];
var oDDL = oForm.elements["fruit_ddl"];
var oTextbox = oForm.elements["fruit_txt"];
if (oHidden && oDDL && oTextbox)
oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;
}
And in the server side, read the value of "fruit" from the Request.
Try this.
First create a RoutedCommand object:
RoutedCommand newCmd = new RoutedCommand();
newCmd.InputGestures.Add(new KeyGesture(Key.N, ModifierKeys.Control));
CommandBindings.Add(new CommandBinding(newCmd, btnNew_Click));
Steps to comment / uncommented
Press alt + f11/ Developer tab visual basic editor view tab - toolbar - edit - comments.
If you want to remove all the data from all your tables, you might want to try the command python manage.py flush
. This will delete all of the data in your tables, but the tables themselves will still exist.
See more here: https://docs.djangoproject.com/en/1.8/ref/django-admin/
While you can't add a wildcard like that, you could add the full list of sites that you need, at least for testing, that works well enough for me, in your hosts file, you just add:
127.0.0.1 site1.local
127.0.0.1 site2.local
127.0.0.1 site3.local
...
Just using Data Binding syntax. For example,
<Button x:Name="btn"
Content="Click"
Command="{Binding ClickCmd}"
CommandParameter="{Binding ElementName=btn,Path=Content}" />
Not only can we use Data Binding to get some data from View Models, but also pass data back to View Models. In CommandParameter, must use ElementName to declare binding source explicitly.
You want:
DECLARE @times int
SELECT @times = COUNT(DidWin)
FROM thetable
WHERE DidWin = 1 AND Playername='Me'
You also don't need the 'as' clause.
After a long time looking for a way to get git log
output the date in the format YYYY-MM-DD
in a way that would work in less
, I came up with the following format:
%ad%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08
along with the switch --date=iso
.
This will print the date in ISO format (a long one), and then print 14 times the backspace character (0x08), which, in my terminal, effectively removes everything after the YYYY-MM-DD part. For example:
git log --date=iso --pretty=format:'%ad%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%aN %s'
This gives something like:
2013-05-24 bruno This is the message of the latest commit.
2013-05-22 bruno This is an older commit.
...
What I did was create an alias named l
with some tweaks on the format above. It shows the commit graph to the left, then the commit's hash, followed by the date, the shortnames, the refnames and the subject. The alias is as follows (in ~/.gitconfig):
[alias]
l = log --date-order --date=iso --graph --full-history --all --pretty=format:'%x08%x09%C(red)%h %C(cyan)%ad%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08 %C(bold blue)%aN%C(reset)%C(bold yellow)%d %C(reset)%s'
One item that seems to have been missed is star transformations. Index Intersection operators resolve the predicate by calculating the set of rows hit by each of the predicates before any I/O is done on the fact table. On a star schema you would index each individual dimension key and the query optimiser can resolve which rows to select by the index intersection computation. The indexes on individual columns give the best flexibility for this.
So, I know this is an old topic, but I'll first say it isn't possible. The closest thing currently is locking the mouse to a single position, and tracking change in its x and y. This concept has been adopted by - it looks like - Chrome and Firefox. It's managed by what's called Mouse Lock, and hitting escape will break it. From my brief read-up, I think the idea is that it locks the mouse to one location, and reports motion events similar to click-and-drag events.
Here's the release documentation:
FireFox: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
Chrome: http://www.chromium.org/developers/design-documents/mouse-lock
And here's a pretty neat demonstration: http://media.tojicode.com/q3bsp/
In Java its Webelement.getText() . Not sure about python.
You are setting self.name
to the string "get_thing"
, not the function get_thing
.
If you want self.name
to be a function, then you should set it to one:
setattr(self, 'name', self.get_thing)
However, that's completely unnecessary for your other code, because you could just call it directly:
value_returned = self.get_thing()
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "name_you_want");
input.setAttribute("value", "value_you_want");
//append to form element that you want .
document.getElementById("chells").appendChild(input);
Maybe you can try this: though please note - This pulls the column count, not the row count
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int count = reader.VisibleFieldCount;
Console.WriteLine(count);
}
}
As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.
ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)
As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().
This will match yyyy-mm-dd
and also yyyy-m-d
:
^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$
If you're looking for an exact match for yyyy-mm-dd
then try this
^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$
or use this one if you need to find a date inside a string like The date is 2017-11-30
\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*
We can give a default value for the timestamp to avoid this problem.
This post gives a detailed workaround: http://gusiev.com/2009/04/update-and-create-timestamps-with-mysql/
create table test_table( id integer not null auto_increment primary key, stamp_created timestamp default '0000-00-00 00:00:00', stamp_updated timestamp default now() on update now() );
Note that it is necessary to enter nulls into both columns during "insert":
mysql> insert into test_table(stamp_created, stamp_updated) values(null, null); Query OK, 1 row affected (0.06 sec) mysql> select * from t5; +----+---------------------+---------------------+ | id | stamp_created | stamp_updated | +----+---------------------+---------------------+ | 2 | 2009-04-30 09:44:35 | 2009-04-30 09:44:35 | +----+---------------------+---------------------+ 2 rows in set (0.00 sec) mysql> update test_table set id = 3 where id = 2; Query OK, 1 row affected (0.05 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from test_table; +----+---------------------+---------------------+ | id | stamp_created | stamp_updated | +----+---------------------+---------------------+ | 3 | 2009-04-30 09:44:35 | 2009-04-30 09:46:59 | +----+---------------------+---------------------+ 2 rows in set (0.00 sec)
I agree with Levik as the parent container is set to 100% if you have sidebars and want them to fill the space to meet up with the footer you cannot set them to 100% because they will be 100 percent of the parent height as well which means that the footer ends up getting pushed down when using the clear function.
Think of it this way if your header is say 50px height and your footer is 50px height and the content is just autofitted to the remaining space say 100px for example and the page container is 100% of this value its height will be 200px. Then when you set the sidebar height to 100% it is then 200px even though it is supposed to fit snug in between the header and footer. Instead it ends up being 50px + 200px + 50px so the page is now 300px because the sidebars are set to the same height as the page container. There will be a big white space in the contents of the page.
I am using internet Explorer 9 and this is what I am getting as the effect when using this 100% method. I havent tried it in other browsers and I assume that it may work in some of the other options. but it will not be universal.
try this:
SELECT
COUNT(program_name) AS [Count],program_type AS [Type]
FROM (SELECT DISTINCT program_name,program_type
FROM cm_production
WHERE push_number=@push_number
) dt
GROUP BY program_type
You can also try this way
<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>
jquery
$('.select_continent').click(function () {
alert($(this).data('value'));
});
Good luck !!!!
I found the easiest way to locate it, you can use
which python
it will show something like this:
/usr/bin/python
This is not an error. This is a warning. The difference is pretty huge. This particular warning basically means that the <Context>
element in Tomcat's server.xml
contains an unknown attribute source
and that Tomcat doesn't know what to do with this attribute and therefore will ignore it.
Eclipse WTP adds a custom attribute source
to the project related <Context>
element in the server.xml
of Tomcat which identifies the source of the context (the actual project in the workspace which is deployed to the particular server). This way Eclipse can correlate the deployed webapplication with an project in the workspace. Since Tomcat version 6.0.16, any unspecified XML tags and attributes in the server.xml
will produce a warning during Tomcat's startup, even though there is no DTD nor XSD for server.xml
.
Just ignore it. Your web project is fine. It should run fine. This issue is completely unrelated to JSF.
When you try to use or manipulate variables in one line beware of their content! E.g. a variable like the following
PATH=C:\Program Files (x86)\somewhere;"C:\Company\Cool Tool";%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;
may lead to a lot of unhand-able trouble if you use it as %PATH%
%PATH%
to handle the parentheses problem%USERPROFILE%
contain?As far as I know, there's a good library called localeplanet
for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery)
Here's the website of library: http://www.localeplanet.com/
Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/
The common part of all those articles/libraries is that they use a i18n
class and a get
method (in some ways also defining an smaller function name like _
) for retrieving/converting the key
to the value
. In my explaining the key
means that string you want to translate and the value
means translated string.
Then, you just need a JSON document to store key
's and value
's.
For example:
var _ = document.webL10n.get;
alert(_('test'));
And here the JSON:
{ test: "blah blah" }
I believe using current popular libraries solutions is a good approach.
public static string GetIPAddress(string hostname)
{
IPHostEntry host;
host = Dns.GetHostEntry(hostname);
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
//System.Diagnostics.Debug.WriteLine("LocalIPadress: " + ip);
return ip.ToString();
}
}
return string.Empty;
}
Use below statement to switch to different databases residing inside your postgreSQL RDMS
\c databaseName
The short answer is primitives are data types, while references are pointers, which do not hold their values but point to their values and are used on/with objects.
Primatives:
boolean
character
byte
short
integer
long
float
double
Lots of good references that explain these basic concepts. http://www.javaforstudents.co.uk/Types
This is the best way i've found so far:
from os.path import dirname, join, isdir, abspath, basename
from glob import glob
pwd = dirname(__file__)
for x in glob(join(pwd, '*.py')):
if not x.startswith('__'):
__import__(basename(x)[:-3], globals(), locals())
Try this if you unbind the onclick event by ID Then use:
$('#youLinkID').attr('onclick','').unbind('click');
Try this if you unbind the onclick event by Class Then use:
$('.className').attr('onclick','').unbind('click');
To create all intermediate-level destination directories you could use os.makedirs()
before copying:
import os
import shutil
srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'
assert not os.path.isabs(srcfile)
dstdir = os.path.join(dstroot, os.path.dirname(srcfile))
os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)
With unsigned numbers of type unsigned int
or larger, in the absence of type conversions, a-b
is defined as yielding the unsigned number which, when added to b
, will yield a
. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).
Note that unsigned numbers smaller than unsigned int
may get promoted to type int
before the subtraction, the behavior of a-b
will depend upon the size of int
.
In case anyone needed the above in swift :
SWIFT 3.0 and above :
this will capitalize your string, make the first letter capital :
viewNoteDateMonth.text = yourString.capitalized
this will uppercase your string, make all the string upper case :
viewNoteDateMonth.text = yourString.uppercased()
I had the same problem, but when I was surfing on the internet I understood that $http return back by default a promise, then I could use it with "then" after return the "data". look at the code:
app.service('myService', function($http) {
this.getData = function(){
var myResponseData = $http.get('test.json').then(function (response) {
console.log(response);.
return response.data;
});
return myResponseData;
}
});
app.controller('MainCtrl', function( myService, $scope) {
// Call the getData and set the response "data" in your scope.
myService.getData.then(function(myReponseData) {
$scope.data = myReponseData;
});
});
check if a user exists or not. If not insert
$exist = DB::table('User')->where(['username'=>$username,'password'=>$password])->get();
if(count($exist) >0) {
echo "User already exist";;
}
else {
$data=array('username'=>$username,'password'=>$password);
DB::table('User')->insert($data);
}
Laravel 5.4
Here is another idea that allow you to affect other elements without considering any specific selector and by only using the :hover
state of the main element.
For this, I will rely on the use of custom properties (CSS variables). As we can read in the specification:
Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules ...
The idea is to define custom properties within the main element and use them to style child elements and since these properties are inherited we simply need to change them within the main element on hover.
Here is an example:
#container {_x000D_
width: 200px;_x000D_
height: 30px;_x000D_
border: 1px solid var(--c);_x000D_
--c:red;_x000D_
}_x000D_
#container:hover {_x000D_
--c:blue;_x000D_
}_x000D_
#container > div {_x000D_
width: 30px;_x000D_
height: 100%;_x000D_
background-color: var(--c);_x000D_
}
_x000D_
<div id="container">_x000D_
<div>_x000D_
</div>_x000D_
</div>
_x000D_
Why this can be better than using specific selector combined with hover?
I can provide at least 2 reasons that make this method a good one to consider:
border
, linear-gradient
, background-color
, box-shadow
etc. This will avoid us reseting all these properties on hover.Here is a more complex example:
.container {_x000D_
--c:red;_x000D_
width:400px;_x000D_
display:flex;_x000D_
border:1px solid var(--c);_x000D_
justify-content:space-between;_x000D_
padding:5px;_x000D_
background:linear-gradient(var(--c),var(--c)) 0 50%/100% 3px no-repeat;_x000D_
}_x000D_
.box {_x000D_
width:30%;_x000D_
background:var(--c);_x000D_
box-shadow:0px 0px 5px var(--c);_x000D_
position:relative;_x000D_
}_x000D_
.box:before {_x000D_
content:"A";_x000D_
display:block;_x000D_
width:15px;_x000D_
margin:0 auto;_x000D_
height:100%;_x000D_
color:var(--c);_x000D_
background:#fff;_x000D_
}_x000D_
_x000D_
/*Hover*/_x000D_
.container:hover {_x000D_
--c:blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box"></div>_x000D_
<div class="box"></div>_x000D_
</div>
_x000D_
As we can see above, we only need one CSS declaration in order to change many properties of different elements.
How about pushing loops to their end limits
for(var a=0; a<data_a.length; a++){
for(var b=0; b<data_b.length; b++){
for(var c=0; c<data_c.length; c++){
for(var d=0; d<data_d.length; d++){
a = data_a.length;
b = data_b.length;
c = data_b.length;
d = data_d.length;
}
}
}
}
cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )
I do not why, but this works for me . rather than use '%s'
.
In PyCharm the parameters are added in the Script Parameters
as you did but, they are enclosed in double quotes ""
and without specifying the Interpreter flags like -s
. Those flags are specified in the Interpreter options
box.
Script Parameters box contents:
"file1.txt" "file2.txt"
Interpeter flags:
-s
Or, visually:
Then, with a simple test file to evaluate:
if __name__ == "__main__":
import sys
print(sys.argv)
We get the parameters we provided (with sys.argv[0]
holding the script name of course):
['/Path/to/current/folder/test.py', 'file1.txt', 'file2.txt']
Beware that when the mounted
event is fired on a component, not all Vue components are replaced yet, so the DOM may not be final yet.
To really simulate the DOM onload
event, i.e. to fire after the DOM is ready but before the page is drawn, use vm.$nextTick from inside mounted
:
mounted: function () {
this.$nextTick(function () {
// Will be executed when the DOM is ready
})
}
Based on quick inspection of google web, this would be CSS path to links in page list
ol[id="rso"] h3[class="r"] a
So you should do something like
String path = "ol[id='rso'] h3[class='r'] a";
driver.findElements(By.cssSelector(path)).get(2).click();
However you could also use xpath
which is not really recommended as a best practice and also JQuery locators but I am not sure if you can use them aynywhere else except inArquillian Graphene
I just need to initialize all the array elements to Boolean false.
Either use boolean[]
instead so that all values defaults to false
:
boolean[] array = new boolean[size];
Or use Arrays#fill()
to fill the entire array with Boolean.FALSE
:
Boolean[] array = new Boolean[size];
Arrays.fill(array, Boolean.FALSE);
Also note that the array index is zero based. The freq[Global.iParameter[2]] = false;
line as you've there would cause ArrayIndexOutOfBoundsException
. To learn more about arrays in Java, consult this basic Oracle tutorial.
Save it as a CSV file and import it as a flat source file.
I needed a solution to select the previous sibling tr. I came up with this solution using React and Styled-components. This is not my exact solution (This is from memory, hours later). I know there is a flaw in the setHighlighterRow function.
OnMouseOver a row will set the row index to state, and rerender the previous row with a new background color
class ReactClass extends Component {
constructor() {
this.state = {
highlightRowIndex: null
}
}
setHighlightedRow = (index) => {
const highlightRowIndex = index === null ? null : index - 1;
this.setState({highlightRowIndex});
}
render() {
return (
<Table>
<Tbody>
{arr.map((row, index) => {
const isHighlighted = index === this.state.highlightRowIndex
return {
<Trow
isHighlighted={isHighlighted}
onMouseOver={() => this.setHighlightedRow(index)}
onMouseOut={() => this.setHighlightedRow(null)}
>
...
</Trow>
}
})}
</Tbody>
</Table>
)
}
}
const Trow = styled.tr`
& td {
background-color: ${p => p.isHighlighted ? 'red' : 'white'};
}
&:hover {
background-color: red;
}
`;
It was weird that no one suggested KVM.
It is gonna provide you almost native performance and it is built-in Linux. Go and check it out.
you will feel like u are using mac only and then install Xcode there u may even choose to directly boot into the OSX GUI instead of Linux one on startup
Without jQuery:
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
}
};
reader.readAsText(file);
};
HTML:
<input type="file" name="file" id="file">
Remember to put your javascript code after the file field is rendered.
If we have a dropdown with a title of "Data Classification":
<select title="Data Classification">
<option value="Top Secret">Top Secret</option>
<option value="Secret">Secret</option>
<option value="Confidential">Confidential</option>
</select>
We can get it into a variable:
var dataClsField = $('select[title="Data Classification"]');
Then put into another variable the value we want the dropdown to have:
var myValue = "Top Secret"; // this would have been "2" in your example
Then we can use the field we put into dataClsField
, do a find for myValue
and make it selected using .prop()
:
dataClsField.find('option[value="'+ myValue +'"]').prop('selected', 'selected');
Or, you could just use .val()
, but your selector of .
can only be used if it matches a class on the dropdown, and you should use quotes on the value inside the parenthesis, or just use the variable we set earlier:
dataClsField.val(myValue);
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).Just wanted to add that you can do this to apply dos2unix fix for all files under a directory, as it saved me heaps of time when we had to 'fix' a bunch of our scripts.
find . -type f -exec dos2unix.exe {} \;
I'd do it as a comment to Roman's answer, but I don't have access to commenting yet.
You can add one li
element where you want to add divider
<ul>
<li> your content </li>
<li class="divider-vertical-second-menu"></li>
<li> NExt content </li>
<li class="divider-vertical-second-menu"></li>
<li> last item </li>
</ul>
In CSS you can Add following code.
.divider-vertical-second-menu{
height: 40px;
width: 1px;
margin: 0 5px;
overflow: hidden;
background-color: #DDD;
border-right: 2px solid #FFF;
}
This will increase you speed of execution as it will not load any image. just test it out.. :)
Use the ssh2
functions. Anything you'd do via an exec() call can be done directly using these functions, saving you a lot of connections and shell invocations.
I know this is very late, but is useful for newbies. We can atuload url helper and it will be available throughout the application. For this in application\config\autoload.php modify as follows -
$autoload['helper'] = array('url');
Function pointers are a great way to do this, e.g.
result = switchFunction(someStringKey); //result is an optional return value
...this calls a function that you have set by string key (one function per case):
setSwitchFunction("foo", fooFunc);
setSwitchFunction("bar", barFunc);
Use a pre-existing hashmap/table/dictionary implementation such as khash, return that pointer to a function inside of switchFunction()
, and execute it (or just return it from switchFunction()
and execute it yourself). If the map implementation doesn't store that, just use a uint64_t
instead that you cast accordingly to a pointer.
Please find the simple solution to convete Date & Time Format in Go Lang. Please find the example below.
Package Link: https://github.com/vigneshuvi/GoDateFormat.
Please find the plackholders:https://medium.com/@Martynas/formatting-date-and-time-in-golang-5816112bf098
package main
// Import Package
import (
"fmt"
"time"
"github.com/vigneshuvi/GoDateFormat"
)
func main() {
fmt.Println("Go Date Format(Today - 'yyyy-MM-dd HH:mm:ss Z'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MM-dd HH:mm:ss Z")))
fmt.Println("Go Date Format(Today - 'yyyy-MMM-dd'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MMM-dd")))
fmt.Println("Go Time Format(NOW - 'HH:MM:SS'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS")))
fmt.Println("Go Time Format(NOW - 'HH:MM:SS tt'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS tt")))
}
func GetToday(format string) (todayString string){
today := time.Now()
todayString = today.Format(format);
return
}
While I currently lean toward RDL because it seems more flexible and easier to manage, RDLC has an advantage in that it seems to simplify your licensing. Because RDLC doesn’t need a Reporting Services instance, you won't need a Reporting Services License to use it.
I’m not sure if this still applies with the newer versions of SQL Server, but at one time if you chose to put the SQL Server Database and Reporting Services instances on two separate machines, you were required to have two separate SQL Server licenses:
http://social.msdn.microsoft.com/forums/en-US/sqlgetstarted/thread/82dd5acd-9427-4f64-aea6-511f09aac406/
You can Bing for other similar blogs and posts regarding Reporting Services licensing.
Ninject is great. It seems really fast, but I haven't done any comparisons. I know Nate, the author, did some comparisons between Ninject and other DI frameworks and is looking for more ways to improve the speed of Ninject.
I've heard lots of people I respect say good things about StructureMap and CastleWindsor. Those, in my mind, are the big three to look at right now.
You need to loop through and parse/convert the elements in your array, like this:
var result_string = 'a,b,c,d|1,2,3,4',
result = result_string.split("|"),
alpha = result[0],
count = result[1],
count_array = count.split(",");
for(var i=0; i<count_array.length;i++) count_array[i] = +count_array[i];
//now count_array contains numbers
You can test it out here. If the +
, is throwing, think of it as:
for(var i=0; i<count_array.length;i++) count_array[i] = parseInt(count_array[i], 10);
var value = "" + 5 + 6;
alert(value);
Try this
<div class="home-component"
[style.width.px]="width"
[style.height.px]="height">Some stuff in this div</div>
[Updated]: To set in % use
[style.height.%]="height">Some stuff in this div</div>
I simply added security.ignored=/**
in the application.properties
,and that did the charm.
Combination of two previous answers:
var selected = [];
$('#checkboxes input:checked').each(function() {
selected.push($(this).attr('name'));
});
Maybe you can change your buildToolsVersion num.
this is my problem:
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'D:\ProgramTools\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1
my build.gradle:
android {
compileSdkVersion 23
buildToolsVersion "24.0.0"
defaultConfig {
applicationId "com.pioneers.recyclerviewitemanimation"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
I just change buildToolsVersion to buildToolsVersion "23.0.2" and the problem was solved.
Please Note: The original poster was not specifically asking about PHP. All the php centric answers make large assumptions not relevant to the actual question.
The default error log as opposed to the scripts error logs usually has the (more) specific error. often it will be permissions denied or even an interpreter that can't be found.
This means the fault almost always lies with your script. e.g you uploaded a perl script but didnt give it execute permissions? or perhaps it was corrupted in a linux environment if you write the script in windows and then upload it to the server without the line endings being converted you will get this error.
in perl if you forget
print "content-type: text/html\r\n\r\n";
you will get this error
There are many reasons for it. so please first check your error log and then provide some more information.
The default error log is often in /var/log/httpd/error_log
or /var/log/apache2/error.log
.
The reason you look at the default error logs (as indicated above) is because errors don't always get posted into the custom error log as defined in the virtual host.
Assumes linux and not necessarily perl
typescript needs to know that our var a
is going to ether be Number || String
export type StringOrNumber = number | string;
export function toString (v: StringOrNumber) {
return `${v}`;
}
export function toNumber (v: StringOrNumber) {
return Number(v);
}
export function toggle (v: StringOrNumber) {
return typeof v === "number" ? `${v}` : Number(v);
}
I faced this exception for a long time and was not able to pinpoint the problem. The exception says line 1 column 9. The mistake I did is to get the first line of the file which flume is processing.
Apache flume process the content of the file in patches. So, when flume throws this exception and says line 1, it means the first line in the current patch.
If your flume agent is configured to use batch size = 100, and (for example) the file contains 400 lines, this means the exception is thrown in one of the following lines 1, 101, 201,301.
How to discover the line which causes the problem?
You have three ways to do that.
1- pull the source code and run the agent in debug mode. If you are an average developer like me and do not know how to make this, check the other two options.
2- Try to split the file based on the batch size and run the flume agent again. If you split the file into 4 files, and the invalid json exists between lines 301 and 400, the flume agent will process the first 3 files and stop at the fourth file. Take the fourth file and again split it into more smaller files. continue the process until you reach a file with only one line and flume fails while processing it.
3- Reduce the batch size of the flume agent to only one and compare the number of processed events in the output of the sink you are using. For example, in my case I am using Solr sink. The file contains 400 lines. The flume agent is configured with batch size=100. When I run the flume agent, it fails at some point and throw that exception. At this point check how many documents are ingested in Solr. If the invalid json exists at line 346, the number of documents indexed into Solr will be 345, so the next line is the line which causes the problem.
In my case I followed the third option and fortunately I pinpoint the line which causes the problem.
This is a long answer but it actually does not solve the exception. How I overcome this exception?
I have no idea why Jackson library complain while parsing a json string contains escaped characters \n \r \t
. I think (but I am not sure) the Jackson parser is by default escaping these characters which cases the json string to be split into two lines (in case of \n
) and then it deals each line as a separate json string.
In my case we used a customized interceptor to remove these characters before being processed by the flume agent. This is the way we solved this problem.
If you want to do anything else during the iteration, it may be nice to get both the index (which guarantees you being able to reference it, for example if you have a list of dicts) and the actual list item contents.
inlist = [{'field1':10, 'field2':20}, {'field1':30, 'field2':15}]
for idx, i in enumerate(inlist):
do some stuff with i['field1']
if somecondition:
xlist.append(idx)
for i in reversed(xlist): del inlist[i]
enumerate
gives you access to the item and the index at once. reversed
is so that the indices that you're going to later delete don't change on you.
The Python way to map
printf("Enter two numbers here: ");
scanf("%d %d", &var1, &var2)
would be
var1, var2 = raw_input("Enter two numbers here: ").split()
Note that we don't have to explicitly specify split(' ')
because split()
uses any whitespace characters as delimiter as default. That means if we simply called split()
then the user could have separated the numbers using tabs, if he really wanted, and also spaces.,
Python has dynamic typing so there is no need to specify %d
. However, if you ran the above then var1
and var2
would be both Strings. You can convert them to int
using another line
var1, var2 = [int(var1), int(var2)]
Or you could use list comprehension
var1, var2 = [int(x) for x in [var1, var2]]
To sum it up, you could have done the whole thing with this one-liner:
# Python 3
var1, var2 = [int(x) for x in input("Enter two numbers here: ").split()]
# Python 2
var1, var2 = [int(x) for x in raw_input("Enter two numbers here: ").split()]
The reason the code will not work without void
is because the System.out.println(String string)
method returns nothing and just prints the supplied arguments to the standard out terminal, which is the computer monitor in most cases. When a method returns "nothing" you have to specify that by putting the void
keyword in its signature.
You can see the documentation of the System.out.println here:
http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#println%28java.lang.String%29
To press the issue further, println is a classic example of a method which is performing computation as a "side effect."
I think, that in this case using PYTHONPATH is a better thing, mostly because it doesn't introduce (questionable) unneccessary code.
After all, if you think of it, your user doesn't need that sys.path
thing, because your package will get installed into site-packages, because you will be using a packaging system.
If the user chooses to run from a "local copy", as you call it, then I've observed, that the usual practice is to state, that the package needs to be added to PYTHONPATH manually, if used outside the site-packages.
func NKPlaceholderImage(image:UIImage?, imageView:UIImageView?,imgUrl:String,compate:@escaping (UIImage?) -> Void){
if image != nil && imageView != nil {
imageView!.image = image!
}
var urlcatch = imgUrl.replacingOccurrences(of: "/", with: "#")
let documentpath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
urlcatch = documentpath + "/" + "\(urlcatch)"
let image = UIImage(contentsOfFile:urlcatch)
if image != nil && imageView != nil
{
imageView!.image = image!
compate(image)
}else{
if let url = URL(string: imgUrl){
DispatchQueue.global(qos: .background).async {
() -> Void in
let imgdata = NSData(contentsOf: url)
DispatchQueue.main.async {
() -> Void in
imgdata?.write(toFile: urlcatch, atomically: true)
let image = UIImage(contentsOfFile:urlcatch)
compate(image)
if image != nil {
if imageView != nil {
imageView!.image = image!
}
}
}
}
}
}
}
Use Like this :
// Here imgPicture = your imageView
// UIImage(named: "placeholder") is Display image brfore download and load actual image.
NKPlaceholderImage(image: UIImage(named: "placeholder"), imageView: imgPicture, imgUrl: "Put Here your server image Url Sting") { (image) in }
If your CPU is spiking to 100% and staying there, it's quite likely that you either have a deadlock scenario or an infinite loop. A profiler seems like a good choice for finding an infinite loop. Deadlocks are much more difficult to track down, however.
Arrays must have zero based integer indexes in JavaScript. So:
var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);
Or maybe you want to use objects (which are associative arrays):
var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
which is equivalent to:
var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.
If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1)
next to it and copy the formula down. This assumes you have your values in range A1:A100
and the de-duplicated values are in column B.
put this line in parent construct : $this->load->database();
function __construct() {
parent::__construct();
$this->load->library('lib_name');
$model=array('model_name');
$this->load->model($model);
$this->load->database();
}
this way.. it should work..
import datetime
day = int(input("day[1,2,3,..31]: "))
month = int(input("Month[1,2,3,...12]: "))
year = int(input("year[0~2020]: "))
start_date = datetime.date(year, month, day)
day = int(input("day[1,2,3,..31]: "))
month = int(input("Month[1,2,3,...12]: "))
year = int(input("year[0~2020]: "))
end_date = datetime.date(year, month, day)
time_difference = end_date - start_date
age = time_difference.days
print("Total days: " + str(age))
On CentOS Linux, Python3.6, I edited this file (make a backup copy first)
/usr/lib/python3.6/site-packages/certifi/cacert.pem
to the end of the file, I added my public certificate from my .pem file. you should be able to obtain the .pem file from your ssl certificate provider.
If its in a landscape then you will be needing more width and less height! That's just what all websites have.
Lets go with a basic first then the rest!
The basic CSS:
By CSS you can do this,
#body {
width: 100%;
height: 100%;
}
Here you are using a div with id
body, as:
<body>
<div id="body>
all the text would go here!
</div>
</body>
Then you can have a web page with 100%
height and width.
What if he tries to resize the window?
The issues pops up, what if he tries to resize the window? Then all the elements inside #body
would try to mess up the UI. For that you can write this:
#body {
height: 100%;
width: 100%;
}
And just add min-height
max-height
min-width
and max-width
.
This way, the page element would stay at the place they were at the page load.
Using JavaScript:
Using JavaScript, you can control the UI, use jQuery as:
$('#body').css('min-height', '100%');
And all other remaining CSS properties, and JS will take care of the User Interface when the user is trying to resize the window.
How to not add scroll to the web page:
If you are not trying to add a scroll, then you can use this JS
$('#body').css('min-height', screen.height); // or anyother like window.height
This way, the document will get a new height whenever the user would load the page.
Second option is better, because when users would have different screen resolutions they would want a CSS or Style sheet created for their own screen. Not for others!
Tip: So try using JS to find current Screen size and edit the page! :)
Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.
...assuming that bgbody.png actually exists :)
Is your CSS in a stylesheet file or in a <style>
block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.
Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.
Here's a little plug if you mostly want to
select
elementoptions
, proper zindex, etc)ul
, li
generated markupsThen jquery.yaselect.js could be a better fit. Simply:
$('select').yaselect();
And the final markup is:
<div class="yaselect-wrap">
<div class="yaselect-current"><!-- current selection --></div>
</div>
<select class="yaselect-select" size="5">
<!-- your option tags -->
</select>
Check it out on github.com
I was getting this error for a different reason than those listed here, and could not find the solution easily, so I figured I would post here.
Hopefully this is helpful to someone.
My issue was with referencing files in the program. It was not able to find the file listed, because when I was coding it I had the file I wanted to reference in the top level directory and just called
"my_file.png"
when I was calling the files.
pyinstaller did not like this, because even when I was running it from the same folder, it was expecting a full path:
"C:\Files\my_file.png"
Once I changed all of my paths, to the full version of their path, it fixed this issue.
If you are copying to GitHub, you may use the GitHub Importer to do that for you. The original repo can even be from other version control systems.
In my case it helped just to close Xcode, repaired the permissions with the Disk Utility. Only after a reboot it worked like a charm.
Found a similar way to fix this issue (at least it did for me).
First check where the CLI php.ini
is located:
php -i | grep "php.ini"
In my case I ended up with : Configuration File (php.ini) Path => /etc
Then cd ..
all the way back and cd
into /etc
, do ls
in my case php.ini didn't show up, only a php.ini.default
Now, copy the php.ini.default file named as php.ini:
sudo cp php.ini.default php.ini
In order to edit, change the permissions of the file:
sudo chmod ug+w php.ini
sudo chgrp staff php.ini
Open directory and edit the php.ini file:
open .
Tip: If you are not able to edit the php.ini due to some permissions issue then copy 'php.ini.default' and paste it on your desktop and rename it to 'php.ini' then open it and edit it following step 7. Then move (copy+paste) it in /etc folder. Issue will be resolved.
Search for [Date] and make sure the following line is in the correct format:
date.timezone = "Europe/Amsterdam"
I hope this could help you out.