If you have Excel 2007 or later use COUNTIFS
with an "S" on the end, i.e.
=COUNTIFS(B2:B292,">10",B2:B292,"<10000")
You may need to change commas , to semi-colons ;
In earlier versions of excel use SUMPRODUCT
like this
=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))
Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=
I would do it this way:
(function($) {
jQuery.fn.doSomething = function() {
return this.each(function() {
var $this = $(this);
$this.click(function(event) {
event.preventDefault();
// Your function goes here
});
});
};
})(jQuery);
Then on document ready you can do stuff like this:
$(document).ready(function() {
$('#div1').doSomething();
$('#div2').doSomething();
});
Service
extends ContextWrapper
which extends Context
. Hence the Service
is a Context
.
Use 'this'
keyword in the service.
Pretty sure pk_OrderID is the PK of AC_Shipping_Addresses
And you are trying to insert a duplicate via the _Order.OrderNumber
Do a
select * from AC_Shipping_Addresses where pk_OrderID = 165863;
or select count(*) ....
Pretty sure you will get a row returned.
What it is telling you is you are already using pk_OrderID = 165863 and cannot have another row with that value.
if you want to not insert if there is a row
insert into table (pk, value)
select 11 as pk, 'val' as value
where not exists (select 1 from table where pk = 11)
You can use the default traceroute
command for this purpose, then there will be nothing to install.
traceroute -T -p 9100 <IP address/hostname>
The -T
argument is required so that the TCP protocol is used instead of UDP.
In the rare case when traceroute
isn't available, you can also use ncat
.
nc -Czvw 5 <IP address/hostname> 9100
If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)
Check this out, it should get you started,
http://www.codeproject.com/KB/office/package.aspx
And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.
Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;
if ( sheet != null )
{
Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
if ( range != null )
{
int nRows = usedRange.Rows.Count;
int nCols = usedRange.Columns.Count;
foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
{
string value = row.Cells[0].FormattedValue as string;
}
}
}
You can also do
Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;
if ( sheets != null )
{
foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
{
// Do Stuff
}
}
And if you need to insert rows/columns
// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );
Instead of hiding view, create the width constrain and change it to 0 in code when you want to hide the UIView.
It may be the simplest way to do so. Also, it will preserve the view and you don't need to recreate it if you want to show it again (ideal to use inside table cells). To change the constant value you need to create a constant reference outlet (the same way as you do outlets for the view).
From 4.1.2 Heap Sizing:
"For a 32-bit process model, the maximum virtual address size of the process is typically 4 GB, though some operating systems limit this to 2 GB or 3 GB. The maximum heap size is typically -Xmx3800m (1600m) for 2 GB limits), though the actual limitation is application dependent. For 64-bit process models, the maximum is essentially unlimited."
Found a pretty good answer here: Java maximum memory on Windows XP.
Use a JSON parser, like JSON.NET
string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();
for some reason, my.demo.service has the same level as src/ in eclise project explorer view. After I move my.demo.service under src/, it is fine. Seems I should not create new package in "Project Explorer" view in Eclipse...
But thank you for your response:)
Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException
this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original).
Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.
public static void main(String[] args) throws IOException {
String destFolderPath = "D:/TestFile/abc";
String fileName = "pqr.xlsx";
String sourceFilePath= "D:/TestFile/xyz.xlsx";
File f = new File(destFolderPath);
if(f.mkdir()){
System.out.println("Directory created!!!!");
}
else {
System.out.println("Directory Exists!!!!");
}
f= new File(destFolderPath,fileName);
if(f.createNewFile()) {
System.out.println("File Created!!!!");
} else {
System.out.println("File exists!!!!");
}
Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
System.out.println("Copy done!!!!!!!!!!!!!!");
}
In order to do a complete refresh, where the grid will be re-rendered alongwith new read request, you can do the following:
Grid.setOptions({
property: true/false
});
Where property can be any property e.g. sortable
A couple of things:
new
as a variable name, it's a reserved word.input
elements, you can just use the value
property directly, you don't have to go through getAttribute
. The attribute is "reflected" as a property.name
.So:
var inputs, input, newValue, i;
inputs = document.getElementsByTagName('input');
for (i=0; i<inputs.length; i++) {
input = inputs[i];
if (input.name == "ans") {
newValue = input.value;
alert(newValue);
}
}
The accepted answer (use MockitoJUnitRunner
and @InjectMocks
) is great. But if you want something a little more lightweight (no special JUnit runner), and less "magical" (more transparent) especially for occasional use, you could just set the private fields directly using introspection.
If you use Spring, you already have a utility class for this : org.springframework.test.util.ReflectionTestUtils
The use is quite straightforward :
ReflectionTestUtils.setField(myLauncher, "myService", myService);
The first argument is your target bean, the second is the name of the (usually private) field, and the last is the value to inject.
If you don't use Spring, it is quite trivial to implement such a utility method. Here is the code I used before I found this Spring class :
public static void setPrivateField(Object target, String fieldName, Object value){
try{
Field privateField = target.getClass().getDeclaredField(fieldName);
privateField.setAccessible(true);
privateField.set(target, value);
}catch(Exception e){
throw new RuntimeException(e);
}
}
What makes the code ugly is the special-handling for the first case. Most of the lines in this small snippet are devoted, not to doing the code's routine job, but to handling that special case. And that's what alternatives like gimel's solve, by moving the special handling outside the loop. There is one special case (well, you could see both start and end as special cases - but only one of them needs to be treated specially), so handling it inside the loop is unnecessarily complicated.
Look at the following commands (especially the commented block).
DROP TABLE foo;
DROP TABLE bar;
CREATE TABLE foo (a int, b text);
CREATE TABLE bar (a serial, b text);
INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i;
INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;
-- blocks of commands to turn foo into bar
CREATE SEQUENCE foo_a_seq;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
ALTER TABLE foo ALTER COLUMN a SET NOT NULL;
ALTER SEQUENCE foo_a_seq OWNED BY foo.a; -- 8.2 or later
SELECT MAX(a) FROM foo;
SELECT setval('foo_a_seq', 5); -- replace 5 by SELECT MAX result
INSERT INTO foo (b) VALUES('teste');
INSERT INTO bar (b) VALUES('teste');
SELECT * FROM foo;
SELECT * FROM bar;
Another solution using java.util.Base64 with Spring Boot
Encryptor Class
package com.jmendoza.springboot.crypto.cipher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
@Component
public class Encryptor {
@Value("${security.encryptor.key}")
private byte[] key;
@Value("${security.encryptor.algorithm}")
private String algorithm;
public String encrypt(String plainText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return new String(Base64.getEncoder().encode(cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8))));
}
public String decrypt(String cipherText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(cipherText)));
}
}
EncryptorController Class
package com.jmendoza.springboot.crypto.controller;
import com.jmendoza.springboot.crypto.cipher.Encryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/cipher")
public class EncryptorController {
@Autowired
Encryptor encryptor;
@GetMapping(value = "encrypt/{value}")
public String encrypt(@PathVariable("value") final String value) throws Exception {
return encryptor.encrypt(value);
}
@GetMapping(value = "decrypt/{value}")
public String decrypt(@PathVariable("value") final String value) throws Exception {
return encryptor.decrypt(value);
}
}
application.properties
server.port=8082
security.encryptor.algorithm=AES
security.encryptor.key=M8jFt46dfJMaiJA0
Example
http://localhost:8082/cipher/encrypt/jmendoza
2h41HH8Shzc4BRU3hVDOXA==
http://localhost:8082/cipher/decrypt/2h41HH8Shzc4BRU3hVDOXA==
jmendoza
Postgres hasn't implemented an equivalent to INSERT OR REPLACE
. From the ON CONFLICT
docs (emphasis mine):
It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.
Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE
applies more generally, since it lets you set new values based on preexisting data. For example:
INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;
Since Symfony 3.3,
You can use %kernel.project_dir%/web/
instead of %kernel.root_dir%/../web/
Check this answer: Set CORS header in Tomcat
Note that you need Tomcat 7.0.41 or higher.
To know where the current instance of Tomcat is located try this:
System.out.println(System.getProperty("catalina.base"));
You'll see the path in the console view.
Then look for /conf/web.xml on that folder, open it and add the lines of the above link.
For Windows (7), the same folder is located at,
%APPDATA%\Subversion\auth
Type in the above in the Run(Win key + R) dialog box and hit Enter,
To check the existing username open the below file as a text file,
%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx
you can use more than one useEffect
for example if my variable is data1 i can use all of this in my component
useEffect( () => console.log("mount"), [] );
useEffect( () => console.log("will update data1"), [ data1 ] );
useEffect( () => console.log("will update any") );
useEffect( () => () => console.log("will update data1 or unmount"), [ data1 ] );
useEffect( () => () => console.log("unmount"), [] );
PageMethod an easier and faster approach for Asp.Net AJAX We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.
PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.
In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:
<body>
<form id="form1" runat="server">
<div>
<fieldset style="width: 200px;">
<asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</fieldset>
<div>
</div>
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" />
</div>
</form>
</body>
</html>
To setup page method, first you have to drag a script manager on your page.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
Also notice that I have changed EnablePageMethods="true"
.
This will tell ScriptManager that I am going to call PageMethods from client side.
Now next step is to create a Server Side function.
Here is the function which I created, this function validates user's input:
[WebMethod]
public static string RegisterUser(string email, string password)
{
string result = "Congratulations!!! your account has been created.";
if (email.Length == 0)//Zero length check
{
result = "Email Address cannot be blank";
}
else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
{
result = "Not a valid email address";
}
else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
{
result = "Not a valid email address";
}
else if (password.Length == 0)
{
result = "Password cannot be blank";
}
else if (password.Length < 5)
{
result = "Password cannot be less than 5 chars";
}
return result;
}
To tell script manager that this method is accessible through javascript we need to ensure two things:
First: This method should be 'public static'.
Second: There should be a [WebMethod] tag above method as written in above code.
Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:
<script type="text/javascript">
function Signup() {
var email = document.getElementById('<%=txtEmail.ClientID %>').value;
var password = document.getElementById('<%=txtPassword.ClientID %>').value;
PageMethods.RegisterUser(email, password, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
}
</script>
To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods.
My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).
Now every thing seems ready, and now I have added OnClientClick="Signup();return false;"
on my Signup button. So here complete code of my aspx page :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<fieldset style="width: 200px;">
<asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</fieldset>
<div>
</div>
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
</div>
</form>
</body>
</html>
<script type="text/javascript">
function Signup() {
var email = document.getElementById('<%=txtEmail.ClientID %>').value;
var password = document.getElementById('<%=txtPassword.ClientID %>').value;
PageMethods.RegisterUser(email, password, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
}
</script>
My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:
-----------test2-------test3
What happened is the machine actually printed this:
test-------test2-------test3\r-------
That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).
Using Document Body:
<body ononline="onlineConditions()" onoffline="offlineConditions()">(...)</body>
Using Javascript Event:
window.addEventListener('load', function() {
function updateOnlineStatus() {
var condition = navigator.onLine ? "online" : "offline";
if( condition == 'online' ){
console.log( 'condition: online')
}else{
console.log( 'condition: offline')
}
}
window.addEventListener('online', updateOnlineStatus );
window.addEventListener('offline', updateOnlineStatus );
});
Reference:
Document-Body: ononline Event
Javascript-Event: Online and offline events
Additional Thoughts:
To ship around the "network connection is not the same as internet connection" Problem from the above methods: You can check the internet connection once with ajax on the application start and configure an online/offline mode. Create a reconnect button for the user to go online. And add on each failed ajax request a function that kick the user back into the offline mode.
You can use DataFrame.any
with parameter axis=1
for check at least one True
in row by DataFrame.isna
with boolean indexing
:
df1 = df[df.isna().any(axis=1)]
d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
df = pd.DataFrame(d).set_index('filename')
print (df)
alpha1 alpha2 gamma1 gamma2 chi2min
filename
M66_MI_NSRh35d32kpoints.dat 0.8016 0.9283 1.000000 0.074804 3.985599e+01
F71_sMI_DMRI51d.dat 0.0000 0.0000 NaN 0.000000 1.000000e+25
F62_sMI_St22d7.dat 1.7210 3.8330 0.237480 0.150000 1.091832e+01
F41_Car_HOC498d.dat 1.1670 2.8090 0.364190 0.300000 7.966335e+00
F78_MI_547d.dat 1.8970 5.4590 0.095319 NaN 2.593468e+01
Explanation:
print (df.isna())
alpha1 alpha2 gamma1 gamma2 chi2min
filename
M66_MI_NSRh35d32kpoints.dat False False False False False
F71_sMI_DMRI51d.dat False False True False False
F62_sMI_St22d7.dat False False False False False
F41_Car_HOC498d.dat False False False False False
F78_MI_547d.dat False False False True False
print (df.isna().any(axis=1))
filename
M66_MI_NSRh35d32kpoints.dat False
F71_sMI_DMRI51d.dat True
F62_sMI_St22d7.dat False
F41_Car_HOC498d.dat False
F78_MI_547d.dat True
dtype: bool
df1 = df[df.isna().any(axis=1)]
print (df1)
alpha1 alpha2 gamma1 gamma2 chi2min
filename
F71_sMI_DMRI51d.dat 0.000 0.000 NaN 0.0 1.000000e+25
F78_MI_547d.dat 1.897 5.459 0.095319 NaN 2.593468e+01
The other answers assume that your compiler is C++11 compliant. That is fine if it is. But what if you are using an older compiler?
I picked up the following hack somewhere on the net. It works well enough for me:
#if defined __UINT32_MAX__ or UINT32_MAX
#include <inttypes.h>
#else
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned long uint32_t;
typedef unsigned long long uint64_t;
#endif
It is not portable, of course. But it might work for your compiler.
If the tables are already created using the scripts, then there is another way to copy the data is by using BCP command to copy all the data from your source server to your destination server
To export the table data into a text file on source server:
bcp <database name>.<schema name>.<table name> OUT C:\FILE.TXT -c -t -T -S <server_name[ \instance_name]> -U <username> -P <Password>
To import the table data from a text file on target server:
bcp <database name>.<schema name>.<table name> IN C:\FILE.TXT -c -t -T -S <server_name[ \instance_name]> -U <username> -P <Password>
Another way is to use the powers of /usr/bin/env
:
docker run ubuntu env DEBUG=1 path/to/script.sh
You have many options. Collating some of the answers above and the accepted answer from this post you can do:
1. df[-df["column"].isin(["value"])]
2. df[~df["column"].isin(["value"])]
3. df[df["column"].isin(["value"]) == False]
4. df[np.logical_not(df["column"].isin(["value"]))]
Note: for option 4 for you'll need to import numpy as np
Update: You can also use the .query
method for this too. This allows for method chaining:
5. df.query("column not in @values")
.
where values
is a list of the values that you don't want to include.
What you are looking for is this:
SHOW VARIABLES;
You can modify it further like any query:
SHOW VARIABLES LIKE '%max%';
#!/bin/bash
# loop*figures.bash
for i in 1 2 3 4 5 # First loop.
do
for j in $(seq 1 $i)
do
echo -n "*"
done
echo
done
echo
# outputs
# *
# **
# ***
# ****
# *****
for i in 5 4 3 2 1 # First loop.
do
for j in $(seq -$i -1)
do
echo -n "*"
done
echo
done
# outputs
# *****
# ****
# ***
# **
# *
for i in 1 2 3 4 5 # First loop.
do
for k in $(seq -5 -$i)
do
echo -n ' '
done
for j in $(seq 1 $i)
do
echo -n "* "
done
echo
done
echo
# outputs
# *
# * *
# * * *
# * * * *
# * * * * *
for i in 1 2 3 4 5 # First loop.
do
for j in $(seq -5 -$i)
do
echo -n "* "
done
echo
for k in $(seq 1 $i)
do
echo -n ' '
done
done
echo
# outputs
# * * * * *
# * * * *
# * * *
# * *
# *
exit 0
public class DynamicLinkedList
{
private class Node
{
private object element;
private Node next;
public object Element
{
get { return this.element; }
set { this.element = value; }
}
public Node Next
{
get { return this.next; }
set { this.next = value; }
}
public Node(object element, Node prevNode)
{
this.element = element;
prevNode.next = this;
}
public Node(object element)
{
this.element = element;
next = null;
}
}
private Node head;
private Node tail;
private int count;
public DynamicLinkedList()
{
this.head = null;
this.tail = null;
this.count = 0;
}
public void AddAtLastPosition(object element)
{
if (head == null)
{
head = new Node(element);
tail = head;
}
else
{
Node newNode = new Node(element, tail);
tail = newNode;
}
count++;
}
public object GetLastElement()
{
object lastElement = null;
Node currentNode = head;
while (currentNode != null)
{
lastElement = currentNode.Element;
currentNode = currentNode.Next;
}
return lastElement;
}
}
Testing with:
static void Main(string[] args)
{
DynamicLinkedList list = new DynamicLinkedList();
list.AddAtLastPosition(1);
list.AddAtLastPosition(2);
list.AddAtLastPosition(3);
list.AddAtLastPosition(4);
list.AddAtLastPosition(5);
object lastElement = list.GetLastElement();
Console.WriteLine(lastElement);
}
string name;
char *c_string;
getline(cin, name);
c_string = new char[name.length()];
for (int index = 0; index < name.length(); index++){
c_string[index] = name[index];
}
c_string[name.length()] = '\0';//add the null terminator at the end of
// the char array
I know this is not the predefined method but thought it may be useful to someone nevertheless.
div {_x000D_
height:50px;_x000D_
}_x000D_
.short-div {_x000D_
height:25px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="container">_x000D_
<h1>Responsive Bootstrap</h1>_x000D_
<div class="row">_x000D_
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5" style="background-color:red;">Span 5</div>_x000D_
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="background-color:blue">Span 3</div>_x000D_
<div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="padding:0px">_x000D_
<div class="short-div" style="background-color:green">Span 2</div>_x000D_
<div class="short-div" style="background-color:purple">Span 2</div>_x000D_
</div>_x000D_
<div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="background-color:yellow">Span 2</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="container-fluid">_x000D_
<div class="row-fluid">_x000D_
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">_x000D_
<div class="short-div" style="background-color:#999">Span 6</div>_x000D_
<div class="short-div">Span 6</div>_x000D_
</div>_x000D_
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="background-color:#ccc">Span 6</div>_x000D_
</div>_x000D_
</div>
_x000D_
This question is tagged python-2.x
so it didn't seem right to tamper with the original question, or the accepted answer. However, Python 2 is now unsupported, and this question still has good google juice for "python csv urllib", so here's an updated Python 3 solution.
It's now necessary to decode urlopen
's response (in bytes) into a valid local encoding, so the accepted answer has to be modified slightly:
import csv, urllib.request
url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib.request.urlopen(url)
lines = [l.decode('utf-8') for l in response.readlines()]
cr = csv.reader(lines)
for row in cr:
print(row)
Note the extra line beginning with lines =
, the fact that urlopen
is now in the urllib.request
module, and print
of course requires parentheses.
It's hardly advertised, but yes, csv.reader
can read from a list of strings.
And since someone else mentioned pandas, here's a one-liner to display the CSV in a console-friendly output:
python3 -c 'import pandas
df = pandas.read_csv("http://winterolympicsmedals.com/medals.csv")
print(df.to_string())'
(Yes, it's three lines, but you can copy-paste it as one command. ;)
I found another situation in which this problem may arise (despite following the steps listed by other users above) and that's when the username of the user you're logged in as has an '_' on it. The path it will try to use to find the temp directory is whatever is set in %TEMP%. I managed to work around it by:
Installed successfully that way.
I suppose, that the problem was in usage of *.htm extension in RequestMapping (foobar.htm). Try to change it to footer.json or something else.
The link to the correct answer: https://stackoverflow.com/a/21236862/537246
P.S.
It is in manner of Spring to do something by default, concerning, that developers know whole API of Spring from A to Z. And then just "406 not acceptable" without any details, and Tomcat's logs are empty!
Andrey's answer (the highest voted at the time of writing) is slightly incorrect. I would have added this as comment but I am not reputable enough.
In Andrey's answer:
char[] chars = {'c', 'h', 'a', 'r', 's'}
byte[] bytes = Charset.forName("UTF-8").encode(CharBuffer.wrap(chars)).array();
the call to array() may not return the desired value, for example:
char[] c = "aaaaaaaaaa".toCharArray();
System.out.println(Arrays.toString(Charset.forName("UTF-8").encode(CharBuffer.wrap(c)).array()));
output:
[97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0]
As can be seen a zero byte has been added. To avoid this use the following:
char[] c = "aaaaaaaaaa".toCharArray();
ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c));
byte[] b = new byte[bb.remaining()];
bb.get(b);
System.out.println(Arrays.toString(b));
output:
[97, 97, 97, 97, 97, 97, 97, 97, 97, 97]
As the answer also alluded to using passwords it might be worth blanking out the array that backs the ByteBuffer (accessed via the array() function):
ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c));
byte[] b = new byte[bb.remaining()];
bb.get(b);
blankOutByteArray(bb.array());
System.out.println(Arrays.toString(b));
just add static keyword at the starting of the function return type.. and then you can access the member function of the class without object:) for ex:
static void Name_pairs::read_names()
{
cout << "Enter name: ";
cin >> name;
names.push_back(name);
cout << endl;
}
I'm using Version 4.0.2.15 with Build 15.21
For me I needed this:
UPDATE table_name SET column_name = REPLACE(column_name,"search str","replace str");
Putting t.column_name
in the first argument of replace
did not work.
Add the following aliases. I think these should be made available in PowerShell by default:
function not-exist { -not (Test-Path $args) }
Set-Alias !exist not-exist -Option "Constant, AllScope"
Set-Alias exist Test-Path -Option "Constant, AllScope"
With that, the conditional statements will change to:
if (exist $path) { ... }
and
if (not-exist $path) { ... }
if (!exist $path) { ... }
Microsoft is releasing the "Microsoft Edge WebView2" WPF control that will get us a great, free option for embedding Chromium across Windows 10, Windows 8.1, or Windows 7. It is available via Nuget as the package Microsoft.Web.WebView2
.
Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.
The answer is yes, if you write return statement the controls goes back to to the caller method immediately. With an exception of finally block, which gets executed after the return statement.
and finally can also override the value you have returned, if you return inside of finally block. LINK: Try-catch-finally-return clarification
Return Statement definition as per:
Java Docs:
a return statement can be used to branch out of a control flow block and exit the method
MSDN Documentation:
The return statement terminates the execution of a function and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call.
Wikipedia:
A return statement causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called, known as its return address. The return address is saved, usually on the process's call stack, as part of the operation of making the subroutine call. Return statements in many languages allow a function to specify a return value to be passed back to the code that called the function.
You need to declare @font-face
like this in your stylesheet
@font-face {
font-family: 'Awesome-Font';
font-style: normal;
font-weight: 400;
src: local('Awesome-Font'), local('Awesome-Font-Regular'), url(path/Awesome-Font.woff) format('woff');
}
Now if you want to apply this font to a paragraph simply use it like this..
p {
font-family: 'Awesome-Font', Arial;
}
What I believe you're looking for is a way to work with arrays as object values:
var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into
var data = {
sampleTime: '1450632410296',
data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
sampleTime: '1450632410296',
data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);
This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify
:
JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'
You might have forgotten to auto increment the id field.
Have a look at CGI in Wikipedia. CGI is a protocol between the web server and a external program or a script that handles the input and generates output that is sent to the browser.
CGI is a simply a way for web server and a program to communicate, nothing more, nothing less. Here the server manages the network connection and HTTP protocol and the program handles input and generates output that is sent to the browser. CGI script can be basically any program that can be executed by the webserver and follows the CGI protocol. Thus a CGI program can be implemented, for example, in C. However that is extremely rare, since C is not very well suited for the task.
/cgi-bin/*.cgi
is a simply a path where people commonly put their CGI script. Web server are commonly configured by default to fetch CGI scripts from that path.
a CGI script can be implemented also in PHP, but all PHP programs are not CGI scripts. If webserver has embedded PHP interpreter (e.g. mod_php in Apache), then the CGI phase is skipped by more efficient direct protocol between the web server and the interpreter.
Whether you have implemented a CGI script or not depends on how your script is being executed by the web server.
Run ps aux | grep nodejs
, find the PID of the process you're looking for, then run kill
starting with SIGTERM (kill -15 25239
). If that doesn't work then use SIGKILL instead, replacing -15
with -9
.
You use attach
without detach
- every time you do it new call to attach masks objects attached before (they contain the same names). Either use detach
or do not use attach
at all.
Nice discussion and tips are here.
It is standard matplotlib.pyplot:
...
import matplotlib.pyplot as plt
plt.ylim(10, 40)
Or simpler, as mwaskom comments below:
ax.set(ylim=(10, 40))
select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual
git reset --hard HEAD
git fetch --all
git reset --hard origin/your_branch
How about the ole goto statement (i know, i know, but it works just fine here ;)
DECLARE
v_attr char(88);
CURSOR SELECT_USERS IS
SELECT id FROM USER_TABLE
WHERE USERTYPE = 'X';
BEGIN
FOR user_rec IN SELECT_USERS LOOP
BEGIN
SELECT attr INTO v_attr
FROM ATTRIBUTE_TABLE
WHERE user_id = user_rec.id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- user does not have attribute, continue loop to next record.
goto end_loop;
END;
<<end_loop>>
null;
END LOOP;
END;
Just put end_loop at very end of loop of course. The null can be substituted with a commit maybe or a counter increment maybe, up to you.
Remove the course_enrollment_settings.base_price
immediately after CASE
:
SELECT
CASE
WHEN course_enrollment_settings.base_price = 0 THEN 1
...
END
CASE
has two different forms, as detailed in the manual. Here, you want the second form since you're using search conditions.
In order to send data from child component create property decorated with output() in child component and in the parent listen to the created event. Emit this event with new values in the payload when ever it needed.
@Output() public eventName:EventEmitter = new EventEmitter();
to emit this event:
this.eventName.emit(payloadDataObject);
You can create the toggler button with css only in a very easy way, there is no need to use any fonts in SVG or ... foramt.
Your Button:
<button
class="navbar-toggler collapsed"
data-target="#navbarsExampleDefault"
data-toggle="collapse">
<span class="line"></span>
<span class="line"></span>
<span class="line"></span>
</button>
Your Button Style:
.navbar-toggler{
width: 47px;
height: 34px;
background-color: #7eb444;
}
Your horizontal line Style:
.navbar-toggler .line{
width: 100%;
float: left;
height: 2px;
background-color: #fff;
margin-bottom: 5px;
}
Demo
.navbar-toggler{_x000D_
width: 47px;_x000D_
height: 34px;_x000D_
background-color: #7eb444;_x000D_
border:none;_x000D_
}_x000D_
.navbar-toggler .line{_x000D_
width: 100%;_x000D_
float: left;_x000D_
height: 2px;_x000D_
background-color: #fff;_x000D_
margin-bottom: 5px;_x000D_
}
_x000D_
<button class="navbar-toggler" data-target="#navbarsExampleDefault" data-toggle="collapse" aria-expanded="true" >_x000D_
<span class="line"></span> _x000D_
<span class="line"></span> _x000D_
<span class="line" style="margin-bottom: 0;"></span>_x000D_
</button>
_x000D_
Use Margin or Padding, applied to the scope within the container:
<StackPanel>
<StackPanel.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="0,10,0,0"/>
</Style>
</StackPanel.Resources>
<TextBox Text="Apple"/>
<TextBox Text="Banana"/>
<TextBox Text="Cherry"/>
</StackPanel>
EDIT: In case you would want to re-use the margin between two containers, you can convert the margin value to a resource in an outer scope, f.e.
<Window.Resources>
<Thickness x:Key="tbMargin">0,10,0,0</Thickness>
</Window.Resources>
and then refer to this value in the inner scope
<StackPanel.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="{StaticResource tbMargin}"/>
</Style>
</StackPanel.Resources>
EDIT: Updated for the latest version of nodemon!
I was struggling with the same thing for my development environment until I noticed that nodemon
's API allows us to change its default behaviour in order to execute a custom command. For example:
nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec 'ts-node' src/index.ts
Or even better: externalize nodemon's config to a nodemon.json
file with the following content, and then just run nodemon
, as Sandokan suggested:
{ "watch": ["src/**/*.ts"], "ignore": ["src/**/*.spec.ts"], "exec": "ts-node ./index.ts" }
By virtue of doing this, you'll be able to live-reload a ts-node
process without having to worry about the underlying implementation.
Cheers!
Updated for the most recent version of nodemon:
You can run this, for example:
nodemon --watch "src/**" --ext "ts,json" --ignore "src/**/*.spec.ts" --exec "ts-node src/index.ts"
Or create a nodemon.json
file with the following content:
{
"watch": ["src"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node ./src/index.ts" // or "npx ts-node src/index.ts"
}
and then run nodemon
with no arguments.
Try this:
$('.select').on('select2:selecting select2:unselecting', function(e) {
var value = e.params.args.data.id;
});
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
CloseableHttpClient
is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated.
The HttpClient
is an interface for this class and other classes.
You should then use the CloseableHttpClient
in your code, and create it using the HttpClientBuilder
. If you need to wrap the client to add specific behaviour you should use request and response interceptors instead of wrapping with the HttpClient
.
This answer was given in the context of httpclient-4.3.
Java Escape Sequences:
\u{0000-FFFF} /* Unicode [Basic Multilingual Plane only, see below] hex value
does not handle unicode values higher than 0xFFFF (65535),
the high surrogate has to be separate: \uD852\uDF62
Four hex characters only (no variable width) */
\b /* \u0008: backspace (BS) */
\t /* \u0009: horizontal tab (HT) */
\n /* \u000a: linefeed (LF) */
\f /* \u000c: form feed (FF) */
\r /* \u000d: carriage return (CR) */
\" /* \u0022: double quote (") */
\' /* \u0027: single quote (') */
\\ /* \u005c: backslash (\) */
\{0-377} /* \u0000 to \u00ff: from octal value
1 to 3 octal digits (variable width) */
The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F
/ 𓀿
and would have to be broken into "\uD80C\uDC3F"
(UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F"
.
if myProp is an object, it may not be changed in usual. so, watch will never be triggered. the reason of why myProp not be changed is that you just set some keys of myProp in most cases. the myProp itself is still the one. try to watch props of myProp, like "myProp.a",it should work.
I too got the same error and struggled a lot in fixing this issue. Spent quiet a bit time in searching Google and found the following solution and my issue got resolved.
the issue was due to, missing Struts2 Libraries in the deployment path. Most of the folks may put the libraries for compilation and tend to forget to attach required libraries for run-time. So I added the same libraries in the web deployment assembly, and the issue was OFF.
Input: 0 0.1 1000
=FIXED(E5,2)
Output: 0.00 0.10 1,000.00
=TEXT(E5,"0.00")
Output: 0.00 0.10 1000.00
Note: As you can see FIXED add a coma after a thousand, where TEXT does not.
If you have to do a curl in php, you should use urlencode()
from PHP but individually!
strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+")
If you do urlencode(strPOST)
, you will bring you another problem, you will have one Item1 and & will be change %xx value and be as one value, see down here the return!
Example 1
$strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+") will give Item1=Value1&Item2=%2B
Example 2
$strPOST = urlencode("Item1=" . $Value1 . "&Item2=+") will give Item1%3DValue1%26Item2%3D%2B
Example 1 is the good way to prepare string for POST in curl
Example 2 show that the receptor will not see the equal and the ampersand to distinguish both value!
I've been dealing with a very similar problem and have been able to achieve what I was looking for, even though I'm using SQL Server 2000. I know it is an old question, but think its valid to post here the solution since there should be others like me that use old versions and still need help.
Here's the trick: SQL Server won't accept passing a table to a UDF, nor you can pass a T-SQL query so the function creates a temp table or even calls a stored procedure to do that. So, instead, I've created a reserved table, which I called xtList. This will hold the list of values (1 column, as needed) to work with.
CREATE TABLE [dbo].[xtList](
[List] [varchar](1000) NULL
) ON [PRIMARY]
Then, a stored procedure to populate the list. This is not strictly necessary, but I think is very usefull and best practice.
-- =============================================
-- Author: Zark Khullah
-- Create date: 20/06/2014
-- =============================================
CREATE PROCEDURE [dbo].[xpCreateList]
@ListQuery varchar(2000)
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM xtList
INSERT INTO xtList
EXEC(@ListQuery)
END
Now, just deal with the list in any way you want, using the xtList. You can use in a procedure (for executing several T-SQL commands), scalar functions (for retrieving several strings) or multi-statement table-valued functions (retrieves the strings but like it was inside a table, 1 string per row). For any of that, you'll need cursors:
DECLARE @Item varchar(100)
DECLARE cList CURSOR DYNAMIC
FOR (SELECT * FROM xtList WHERE List is not NULL)
OPEN cList
FETCH FIRST FROM cList INTO @Item
WHILE @@FETCH_STATUS = 0 BEGIN
<< desired action with values >>
FETCH NEXT FROM cList INTO @Item
END
CLOSE cList
DEALLOCATE cList
The desired action would be as follows, depending on which type of object created:
Stored procedures
-- =============================================
-- Author: Zark Khullah
-- Create date: 20/06/2014
-- =============================================
CREATE PROCEDURE [dbo].[xpProcreateExec]
(
@Cmd varchar(8000),
@ReplaceWith varchar(1000)
)
AS
BEGIN
DECLARE @Query varchar(8000)
<< cursor start >>
SET @Query = REPLACE(@Cmd,@ReplaceWith,@Item)
EXEC(@Query)
<< cursor end >>
END
/* EXAMPLES
(List A,B,C)
Query = 'SELECT x FROM table'
with EXEC xpProcreateExec(Query,'x') turns into
SELECT A FROM table
SELECT B FROM table
SELECT C FROM table
Cmd = 'EXEC procedure ''arg''' --whatchout for wrong quotes, since it executes as dynamic SQL
with EXEC xpProcreateExec(Cmd,'arg') turns into
EXEC procedure 'A'
EXEC procedure 'B'
EXEC procedure 'C'
*/
Scalar functions
-- =============================================
-- Author: Zark Khullah
-- Create date: 20/06/2014
-- =============================================
CREATE FUNCTION [dbo].[xfProcreateStr]
(
@OriginalText varchar(8000),
@ReplaceWith varchar(1000)
)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @Result varchar(8000)
SET @Result = ''
<< cursor start >>
SET @Result = @Result + REPLACE(@OriginalText,@ReplaceWith,@Item) + char(13) + char(10)
<< cursor end >>
RETURN @Result
END
/* EXAMPLE
(List A,B,C)
Text = 'Access provided for user x'
with "SELECT dbo.xfProcreateStr(Text,'x')" turns into
'Access provided for user A
Access provided for user B
Access provided for user C'
*/
Multi-statement table-valued functions
-- =============================================
-- Author: Zark Khullah
-- Create date: 20/06/2014
-- =============================================
CREATE FUNCTION [dbo].[xfProcreateInRows]
(
@OriginalText varchar(8000),
@ReplaceWith varchar(1000)
)
RETURNS
@Texts TABLE
(
Text varchar(2000)
)
AS
BEGIN
<< cursor start >>
INSERT INTO @Texts VALUES(REPLACE(@OriginalText,@ReplaceWith,@Item))
<< cursor end >>
END
/* EXAMPLE
(List A,B,C)
Text = 'Access provided for user x'
with "SELECT * FROM dbo.xfProcreateInRow(Text,'x')" returns rows
'Access provided for user A'
'Access provided for user B'
'Access provided for user C'
*/
You should let the user do that if they want (and you can't stop them anyway).
Your problem is that you need to know that they have and then assume that they mean OK, not cancel. Replace confirm(x)
with myConfirm(x)
:
function myConfirm(message) {
var start = Number(new Date());
var result = confirm(message);
var end = Number(new Date());
return (end<(start+10)||result==true);
}
Download ChromeDriver from this direct link OR get the latest version from this page.
Paste the chromedriver.exe
file in your C:\Python27\Scripts
folder.
This should work now:
from selenium import webdriver
driver = webdriver.Chrome()
fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)
Put this code in the <head></head>
tags:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:
Delivery -> Package (One -> Many)
CREATE TABLE Delivery(
Id INT IDENTITY PRIMARY KEY,
NoteNumber NVARCHAR(255) NOT NULL
)
CREATE TABLE Package(
Id INT IDENTITY PRIMARY KEY,
Status INT NOT NULL DEFAULT 0,
Delivery_Id INT NOT NULL,
CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)
The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).
So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.
Simple Response: This worked for me with no Problem. It seems the key is to ensure that the View has focus before you getHeight etc. Do this by using the hasFocus() method, then using getHeight() method in that order. Just 3 lines of code required.
ImageButton myImageButton1 =(ImageButton)findViewById(R.id.imageButton1);
myImageButton1.hasFocus();
int myButtonHeight = myImageButton1.getHeight();
Log.d("Button Height: ", ""+myButtonHeight );//Not required
Hope it helps.
I have faced this error, Previous I had push in root directory, and now I have push another directory, so I could be remove this error and run below commands.
git add .
git commit -m "some comments"
git push --set-upstream origin master
node-crontab allows you to edit system cron jobs from node.js. Using this library will allow you to run programs even after your main process termintates. Disclaimer: I'm the developer.
Pretty old question but the most simple answer isn't yet posted.
Here it is :
1) In [workspace]\.metadata\.plugins\org.eclipse.e4.workbench
delete workbench.xmi
file.
In most cases it's enough - try to load Eclipse.
Still you have to re-configure your specific perspective settings (if any)
2) Now getting problems with building projects that worked perfectly? As of my experience following steps help:
- uncheck Projects->Build automatically
- switch to Java perspective (if not yet): Window -> Open perspective -> Java
- locate Problems view or open it: Window -> Show view -> Problems
- right-click on problem groups and select Delete. Be sure to delete Lint errors
- clean the workspace: Project -> Clean... with option Clean all projects
- check Projects->Build automatically
- if problems persist for some projects: right-click project, select Properties -> Android and make sure appropriate Project Build Target is chosen
3) It was always sufficient for me. But if you still get problems - try @george post recommendations
As many others have answered, No.
I use the following code on those unfortunate occasions when I need to use a base type as a derived type. Yes it is a violation of the Liskov Substitution Principle (LSP) and yes most of the time we favor composition over inheritance. Props to Markus Knappen Johansson whose original answer this is based upon.
This code in the base class:
public T As<T>()
{
var type = typeof(T);
var instance = Activator.CreateInstance(type);
if (type.BaseType != null)
{
var properties = type.BaseType.GetProperties();
foreach (var property in properties)
if (property.CanWrite)
property.SetValue(instance, property.GetValue(this, null), null);
}
return (T) instance;
}
Allows:
derivedObject = baseObect.As<derivedType>()
Since it uses reflection, it is "expensive". Use accordingly.
Backgrounds jobs are expensive to setup and are not reusable. PowerShell MVP Oisin Grehan has a good example of PowerShell multi-threading.
(10/25/2010 site is down, but accessible via the Web Archive).
I'e used adapted Oisin script for use in a data loading routine here:
http://rsdd.codeplex.com/SourceControl/changeset/view/a6cd657ea2be#Invoke-RSDDThreaded.ps1
I had the same problem and solved it by copying the MSVCR100.dll
file from sqldeveloper\jdk\jre\bin
to the sqldeveloper\sqldeveloper\bin
folder.
Credit goes to Erik Anderson from SQL Developer failed to start
Note that different versions of SQL Developer need different versions of MSVCR*.dll
. Various comments below have offered which versions worked for them.
Class definitions should be like :
export class Environment {
cId:string;
cName:string;
constructor( id: string, name: string ) {
this.cId = id;
this.cName = name;
}
getMyFields(){
return this.cId + " " + this.cName;
}
}
var environments = new Environment('a','b');
console.log(environments.getMyFields()); // will print a b
Source: https://www.typescriptlang.org/docs/handbook/classes.html
Are dictionaries ordered in Python 3.6+?
They are insertion ordered[1]. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict
if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior[1]).
As of Python 3.7, this is no longer an implementation detail and instead becomes a language feature. From a python-dev message by GvR:
Make it so. "Dict keeps insertion order" is the ruling. Thanks!
This simply means that you can depend on it. Other implementations of Python must also offer an insertion ordered dictionary if they wish to be a conforming implementation of Python 3.7.
How does the Python
3.6
dictionary implementation perform better[2] than the older one while preserving element order?
Essentially, by keeping two arrays.
The first array, dk_entries
, holds the entries (of type PyDictKeyEntry
) for the dictionary in the order that they were inserted. Preserving order is achieved by this being an append only array where new items are always inserted at the end (insertion order).
The second, dk_indices
, holds the indices for the dk_entries
array (that is, values that indicate the position of the corresponding entry in dk_entries
). This array acts as the hash table. When a key is hashed it leads to one of the indices stored in dk_indices
and the corresponding entry is fetched by indexing dk_entries
. Since only indices are kept, the type of this array depends on the overall size of the dictionary (ranging from type int8_t
(1
byte) to int32_t
/int64_t
(4
/8
bytes) on 32
/64
bit builds)
In the previous implementation, a sparse array of type PyDictKeyEntry
and size dk_size
had to be allocated; unfortunately, it also resulted in a lot of empty space since that array was not allowed to be more than 2/3 * dk_size
full for performance reasons. (and the empty space still had PyDictKeyEntry
size!).
This is not the case now since only the required entries are stored (those that have been inserted) and a sparse array of type intX_t
(X
depending on dict size) 2/3 * dk_size
s full is kept. The empty space changed from type PyDictKeyEntry
to intX_t
.
So, obviously, creating a sparse array of type PyDictKeyEntry
is much more memory demanding than a sparse array for storing int
s.
You can see the full conversation on Python-Dev regarding this feature if interested, it is a good read.
In the original proposal made by Raymond Hettinger, a visualization of the data structures used can be seen which captures the gist of the idea.
For example, the dictionary:
d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}
is currently stored as [keyhash, key, value]:
entries = [['--', '--', '--'], [-8522787127447073495, 'barry', 'green'], ['--', '--', '--'], ['--', '--', '--'], ['--', '--', '--'], [-9092791511155847987, 'timmy', 'red'], ['--', '--', '--'], [-6480567542315338377, 'guido', 'blue']]
Instead, the data should be organized as follows:
indices = [None, 1, None, None, None, 0, None, 2] entries = [[-9092791511155847987, 'timmy', 'red'], [-8522787127447073495, 'barry', 'green'], [-6480567542315338377, 'guido', 'blue']]
As you can visually now see, in the original proposal, a lot of space is essentially empty to reduce collisions and make look-ups faster. With the new approach, you reduce the memory required by moving the sparseness where it's really required, in the indices.
[1]: I say "insertion ordered" and not "ordered" since, with the existence of OrderedDict, "ordered" suggests further behavior that the dict
object doesn't provide. OrderedDicts are reversible, provide order sensitive methods and, mainly, provide an order-sensive equality tests (==
, !=
). dict
s currently don't offer any of those behaviors/methods.
[2]: The new dictionary implementations performs better memory wise by being designed more compactly; that's the main benefit here. Speed wise, the difference isn't so drastic, there's places where the new dict might introduce slight regressions (key-lookups, for example) while in others (iteration and resizing come to mind) a performance boost should be present.
Overall, the performance of the dictionary, especially in real-life situations, improves due to the compactness introduced.
You can use the groupby command, if you already have some labels for your data.
out_list = [group[1] for group in in_series.groupby(label_series.values)]
Here's a detailed example:
Let's say we want to partition a pd series using some labels into a list of chunks
For example, in_series
is:
2019-07-01 08:00:00 -0.10
2019-07-01 08:02:00 1.16
2019-07-01 08:04:00 0.69
2019-07-01 08:06:00 -0.81
2019-07-01 08:08:00 -0.64
Length: 5, dtype: float64
And its corresponding label_series
is:
2019-07-01 08:00:00 1
2019-07-01 08:02:00 1
2019-07-01 08:04:00 2
2019-07-01 08:06:00 2
2019-07-01 08:08:00 2
Length: 5, dtype: float64
Run
out_list = [group[1] for group in in_series.groupby(label_series.values)]
which returns out_list
a list
of two pd.Series
:
[2019-07-01 08:00:00 -0.10
2019-07-01 08:02:00 1.16
Length: 2, dtype: float64,
2019-07-01 08:04:00 0.69
2019-07-01 08:06:00 -0.81
2019-07-01 08:08:00 -0.64
Length: 3, dtype: float64]
Note that you can use some parameters from in_series
itself to group the series, e.g., in_series.index.day
Based on First answer here is the complete image selection options:
Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
|PNG|*.PNG;*.png
|JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
|Bitmap(.BMP,.bmp)|*.BMP;*.bmp
|GIF|*.GIF;*.gif
|TIF|*.tif;*.tiff
|ICO|*.ico;*.ICO";
Nick's answer works great and the default settings are nice, but you can more fully control the scrolling by completing all of the optional settings.
here is what it looks like in the API:
.animate( properties [, duration] [, easing] [, complete] )
so you could do something like this:
.animate(
{scrollTop:'300px'},
300,
swing,
function(){
alert(animation complete! - your custom code here!);
}
)
here is the jQuery .animate function api page: http://api.jquery.com/animate/
Since C++11 you could use std::put_time
from iomanip
header:
#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::cout << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << std::endl;
}
std::put_time
is a stream manipulator, therefore it could be used together with std::ostringstream
in order to convert the date to a string:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>
int main()
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::ostringstream oss;
oss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S");
auto str = oss.str();
std::cout << str << std::endl;
}
I was getting this issue on our TeamCity build server. I tried updating NuGet on the build server (via TC) but that didn't work. I finally resolved the problem by changing the "Update Mode" of the Nuget Installer build step from solution file to packages.config
.
This is what worked for me:
$.get({
method: 'GET',
url: 'api.php',
headers: {
'Content-Type': 'application/json',
},
// query parameters go under "data" as an Object
data: {
client: 'mikescafe'
}
});
will make a REST/AJAX call - > GET http://localhost:3000/api.php?client=mikescafe
Good Luck.
I'd recommend looking at consistent gets/logical reads as a better proxy for 'work' than run time. The run time can be skewed by what else is happening on the database server, how much stuff is in the cache etc.
But if you REALLY want SQL executing time, the V$SQL view has both CPU_TIME and ELAPSED_TIME.
Use the Request.UrlReferrer
property.
Underneath the scenes it is just checking the ServerVariables("HTTP_REFERER")
property.
Don't know about plugins but this shouldn't be too hard:
;(function($) {
$.fn.counter = function(options) {
// Set default values
var defaults = {
start: 0,
end: 10,
time: 10,
step: 1000,
callback: function() { }
}
var options = $.extend(defaults, options);
// The actual function that does the counting
var counterFunc = function(el, increment, end, step) {
var value = parseInt(el.html(), 10) + increment;
if(value >= end) {
el.html(Math.round(end));
options.callback();
} else {
el.html(Math.round(value));
setTimeout(counterFunc, step, el, increment, end, step);
}
}
// Set initial value
$(this).html(Math.round(options.start));
// Calculate the increment on each step
var increment = (options.end - options.start) / ((1000 / options.step) * options.time);
// Call the counter function in a closure to avoid conflicts
(function(e, i, o, s) {
setTimeout(counterFunc, s, e, i, o, s);
})($(this), increment, options.end, options.step);
}
})(jQuery);
Usage:
$('#foo').counter({
start: 1000,
end: 4500,
time: 8,
step: 500,
callback: function() {
alert("I'm done!");
}
});
Example:
I guess the usage is self-explanatory; in this example, the counter will start from 1000 and count up to 4500 in 8 seconds in 500ms intervals, and will call the callback function when the counting is done.
might fail working with link_directories, then add each static library like following:
target_link_libraries(foo /path_to_static_library/libbar.a)
You can regenerate your certificate and restart your iPhone.
This work for me, I hope this help you.
Making a request to
C:\wnmp\curl>curl.exe --trace-ascii -H 'project1.loc' -d "uuid=d99a49d846d5ae570
667a00825373a7b5ae8e8e2" http://project1.loc/Users/getSettings.xml
Resulted in the -H
log file containing:
== Info: Could not resolve host: 'project1.loc'; Host not found
== Info: Closing connection #0
== Info: About to connect() to project1.loc port 80 (#0)
== Info: Trying 127.0.0.1... == Info: connected
== Info: Connected to project1.loc (127.0.0.1) port 80 (#0)
=> Send header, 230 bytes (0xe6)
0000: POST /Users/getSettings.xml HTTP/1.1
0026: User-Agent: curl/7.19.5 (i586-pc-mingw32msvc) libcurl/7.19.5 Ope
0066: nSSL/1.0.0a zlib/1.2.3
007e: Host: project1.loc
0092: Accept: */*
009f: Content-Length: 45
00b3: Content-Type: application/x-www-form-urlencoded
00e4:
=> Send data, 45 bytes (0x2d)
0000: uuid=d99a49d846d5ae570667a00825373a7b5ae8e8e2
<= Recv header, 24 bytes (0x18)
0000: HTTP/1.1 403 Forbidden
<= Recv header, 22 bytes (0x16)
0000: Server: nginx/0.7.66
<= Recv header, 37 bytes (0x25)
0000: Date: Wed, 11 Aug 2010 15:37:06 GMT
<= Recv header, 25 bytes (0x19)
0000: Content-Type: text/html
<= Recv header, 28 bytes (0x1c)
0000: Transfer-Encoding: chunked
<= Recv header, 24 bytes (0x18)
0000: Connection: keep-alive
<= Recv header, 25 bytes (0x19)
0000: X-Powered-By: PHP/5.3.2
<= Recv header, 56 bytes (0x38)
0000: Set-Cookie: SESSION=m9j6caghb223uubiddolec2005; path=/
<= Recv header, 57 bytes (0x39)
0000: P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"
<= Recv header, 2 bytes (0x2)
0000:
<= Recv data, 118 bytes (0x76)
0000: 6b
0004: <html><head><title>HTTP/1.1 403 Forbidden</title></head><body><h
0044: 1>HTTP/1.1 403 Forbidden</h1></body></html>
0071: 0
0074:
== Info: Connection #0 to host project1.loc left intact
== Info: Closing connection #0
My hosts file looks like:
# Copyright (c) 1993-1999 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
127.0.0.1 localhost
...
...
127.0.0.1 project1.loc
No external libraries, works on both Python 2.7 and 3.x:
>>> list(set({"a":1, "b": 2}.values()))[0]
1
For aribtrary key just leave out .values()
>>> list(set({"a":1, "b": 2}))[0]
'a'
You won't be able to draw images directly from another server into a canvas and then use getImageData
. It's a security issue and the canvas will be considered "tainted".
Would it work for you to save a copy of the image to your server using PHP and then just load the new image? For example, you could send the URL to the PHP script and save it to your server, then return the new filename to your javascript like this:
<?php //The name of this file in this example is imgdata.php
$url=$_GET['url'];
// prevent hackers from uploading PHP scripts and pwning your system
if(!@is_array(getimagesize($url))){
echo "path/to/placeholderImage.png";
exit("wrong file type.");
}
$img = file_get_contents($url);
$fn = substr(strrchr($url, "/"), 1);
file_put_contents($fn,$img);
echo $fn;
?>
You'd use the PHP script with some ajax javascript like this:
xi=new XMLHttpRequest();
xi.open("GET","imgdata.php?url="+yourImageURL,true);
xi.send();
xi.onreadystatechange=function() {
if(xi.readyState==4 && xi.status==200) {
img=new Image;
img.onload=function(){
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
}
img.src=xi.responseText;
}
}
If you use getImageData
on the canvas after that, it will work fine.
Alternatively, if you don't want to save the whole image, you could pass x & y coordinates to your PHP script and calculate the pixel's rgba value on that side. I think there are good libraries for doing that kind of image processing in PHP.
If you want to use this approach, let me know if you need help implementing it.
edit-1: peeps pointed out that the php script is exposed and allows the internet to potentially use it maliciously. there are a million ways to handle this, one of the simplest being some sort of URL obfuscation... i reckon secure php practices deserves a separate google ;P
edit-2: by popular demand, I've added a check to ensure it is an image and not a php script (from: PHP check if file is an image).
He want an elegant and proper solution try this small regex pattern matcher.
This is specifically for India.(First digit can't be zero and and then can be any 9 digits)
return mobile.matches("[1-9][0-9]{9}");
Pattern Breakdown:-
[1-9]
matches first digit and checks if number(integer) lies between(inclusive) 1 to 9
[0-9]{9}
matches the same thing but {9}
tells the pattern that it has to check for upcoming all 9 digits.
Now the {9} part may vary for different countries so you may have array which tells the number of digits allowed in phone number. Some countries also have significance for zero ahead of number, so you may have exception for those and design a separate regex patterns for those countries phone numbers.
You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.
Use a return statement!
return;
or
if (condition) return;
You don't need to (and can't) specify any values, if your method returns void
.
just in case you are using a remote access and want to dump all database data, you can use:
pg_dump -a -h your_host -U your_user -W -Fc your_database > DATA.dump
it will create a dump with all database data and use
pg_restore -a -h your_host -U your_user -W -Fc your_database < DATA.dump
to insert the same data in your data base considering you have the same structure
It is Work for me:
language:{"infoEmpty": "No records available",}
This one shows how to print only selected element on the page with dpi/resolution
adjustments
HTML:
<html>
<body>
<header>This is the header</header>
<div id="content">
This is the element you only want to capture
</div>
<button id="print">Download Pdf</button>
<footer>This is the footer</footer>
</body>
</html>
CSS:
body {
background: beige;
}
header {
background: red;
}
footer {
background: blue;
}
#content {
background: yellow;
width: 70%;
height: 100px;
margin: 50px auto;
border: 1px solid orange;
padding: 20px;
}
JS:
$('#print').click(function() {
var w = document.getElementById("content").offsetWidth;
var h = document.getElementById("content").offsetHeight;
html2canvas(document.getElementById("content"), {
dpi: 300, // Set to 300 DPI
scale: 3, // Adjusts your resolution
onrendered: function(canvas) {
var img = canvas.toDataURL("image/jpeg", 1);
var doc = new jsPDF('L', 'px', [w, h]);
doc.addImage(img, 'JPEG', 0, 0, w, h);
doc.save('sample-file.pdf');
}
});
});
you can also quote string
''+document.location+''.substring(2,3);
On Linux, macOS and Unix to display the groups to which you belong, use:
id -Gn
which is equivalent to groups
utility which has been obsoleted on Unix (as per Unix manual).
On macOS and Unix, the command id -p
is suggested for normal interactive.
Explanation of the parameters:
-G
,--groups
- print all group IDs
-n
,--name
- print a name instead of a number, for-ugG
-p
- Make the output human-readable.
To put any element at the bottom of its container, just used this:
div {
position: absolute;
bottom: 0px;
}
dimen.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="weight">1</integer>
<dimen name="dialog_top_radius">21dp</dimen>
<dimen name="textview_dialog_head_min_height">50dp</dimen>
<dimen name="textview_dialog_drawable_padding">5dp</dimen>
<dimen name="button_dialog_layout_margin">3dp</dimen>
</resources>
styles.xml
<style name="TextView.Dialog">
<item name="android:paddingLeft">@dimen/dimen_size</item>
<item name="android:paddingRight">@dimen/dimen_size</item>
<item name="android:gravity">center_vertical</item>
<item name="android:textColor">@color/black</item>
</style>
<style name="TextView.Dialog.Head">
<item name="android:minHeight">@dimen/textview_dialog_head_min_height</item>
<item name="android:textColor">@color/white</item>
<item name="android:background">@drawable/dialog_title_style</item>
<item name="android:drawablePadding">@dimen/textview_dialog_drawable_padding</item>
</style>
<style name="TextView.Dialog.Text">
<item name="android:textAppearance">@style/Font.Medium.16</item>
</style>
<style name="Button" parent="Base.Widget.AppCompat.Button">
<item name="android:layout_height">@dimen/button_min_height</item>
<item name="android:layout_width">match_parent</item>
<item name="android:textColor">@color/white</item>
<item name="android:gravity">center</item>
<item name="android:textAppearance">@style/Font.Medium.20</item>
</style>
<style name="Button.Dialog">
<item name="android:layout_weight">@integer/weight</item>
<item name="android:layout_margin">@dimen/button_dialog_layout_margin</item>
</style>
<style name="Button.Dialog.Middle">
<item name="android:background">@drawable/button_primary_selector</item>
</style>
dialog_title_style.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="270"
android:endColor="@color/primaryDark"
android:startColor="@color/primaryDark" />
<corners
android:topLeftRadius="@dimen/dialog_top_radius"
android:topRightRadius="@dimen/dialog_top_radius" />
</shape>
dialog_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/backgroundDialog" />
<corners
android:topLeftRadius="@dimen/dialog_top_radius"
android:topRightRadius="@dimen/dialog_top_radius" />
<padding />
</shape>
dialog_one_button.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/dailog_background"
android:orientation="vertical">
<TextView
android:id="@+id/dialogOneButtonTitle"
style="@style/TextView.Dialog.Head"
android:text="Process Completed" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:orientation="vertical">
<TextView
android:id="@+id/dialogOneButtonText"
style="@style/TextView.Dialog.Text"
android:text="Return the main menu" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/dialogOneButtonOkButton"
style="@style/Button.Dialog.Middle"
android:text="Ok" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
OneButtonDialog.java
package com.example.sametoztoprak.concept.dialogs;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.example.sametoztoprak.concept.R;
import com.example.sametoztoprak.concept.models.DialogFields;
/**
* Created by sametoztoprak on 26/09/2017.
*/
public class OneButtonDialog extends Dialog implements View.OnClickListener {
private static OneButtonDialog oneButtonDialog;
private static DialogFields dialogFields;
private Button dialogOneButtonOkButton;
private TextView dialogOneButtonText;
private TextView dialogOneButtonTitle;
public OneButtonDialog(AppCompatActivity activity) {
super(activity);
}
public static OneButtonDialog getInstance(AppCompatActivity activity, DialogFields dialogFields) {
OneButtonDialog.dialogFields = dialogFields;
return oneButtonDialog = (oneButtonDialog == null) ? new OneButtonDialog(activity) : oneButtonDialog;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_one_button);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialogOneButtonTitle = (TextView) findViewById(R.id.dialogOneButtonTitle);
dialogOneButtonText = (TextView) findViewById(R.id.dialogOneButtonText);
dialogOneButtonOkButton = (Button) findViewById(R.id.dialogOneButtonOkButton);
dialogOneButtonOkButton.setOnClickListener(this);
}
@Override
protected void onStart() {
super.onStart();
dialogOneButtonTitle.setText(dialogFields.getTitle());
dialogOneButtonText.setText(dialogFields.getText());
dialogOneButtonOkButton.setText(dialogFields.getOneButton());
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.dialogOneButtonOkButton:
break;
default:
break;
}
dismiss();
}
}
There are a few ways depending on some data rules that you have not included, but here is one way using what you gave.
SELECT
t1.Field1,
t2.Field2
FROM Table1 t1
LEFT JOIN Table1 t2 ON t1.FK = t2.FK AND t2.Field1 IS NULL
Another way:
SELECT
t1.Field1,
(SELECT Field2 FROM Table2 t2 WHERE t2.FK = t1.FK AND Field1 IS NULL) AS Field2
FROM Table1 t1
Inspired by the insightful answers on this page, I created a mixed approach, which I consider the simplest and more flexible one. What do you think?
First, I define the usage in a variable, which allows me to reuse it in different contexts. The format is very simple, almost WYSIWYG, without the need to add any control characters. This seems reasonably portable to me (I ran it on MacOS and Ubuntu)
__usage="
Usage: $(basename $0) [OPTIONS]
Options:
-l, --level <n> Something something something level
-n, --nnnnn <levels> Something something something n
-h, --help Something something something help
-v, --version Something something something version
"
Then I can simply use it as
echo "$__usage"
or even better, when parsing parameters, I can just echo it there in a one-liner:
levelN=${2:?"--level: n is required!""${__usage}"}
You can stick optional whitespace characters \s*
in between every other character in your regex. Although granted, it will get a bit lengthy.
/cats/
-> /c\s*a\s*t\s*s/
Just use Apache Commons
Great explanation here:
https://www.cuelogic.com/blog/using-framelayout-for-designing-xml-layouts-in-android
LinearLayout arranges elements side by side either horizontally or vertically.
RelativeLayout helps you arrange your UI elements based on specific rules. You can specify rules like: align this to parent’s left edge, place this to the left/right of this elements etc.
AbsoluteLayout is for absolute positioning i.e. you can specify exact co-ordinates where the view should go.
FrameLayout allows placements of views along Z-axis. That means that you can stack your view elements one above the other.
Simply do this:
<div ng-style="{'background-color': '{{myColorVariable}}', height: '2rem'}"></div>
_x000D_
If this SQL is being used in any peoplesoft specific code (Application Engine, SQLEXEC, SQLfetch, etc..) you could use %Datein metaSQL. Peopletools automatically converts the date to a format which would be accepted by the database platform the application is running on.
In case this SQL is being used to perform a backend update from a query analyzer (like SQLDeveloper, SQLTools), the date format that is being used is wrong. Oracle expects the date format to be DD-MMM-YYYY, where MMM could be JAN, FEB, MAR, etc..
as an aside, i Couldnt import the .dll if it was already in the plugins folder. I put it in a temp folder on the C drive, and it worked perfectly.
In our case it was an empty AndroidManifest.xml.
While upgrading Eclispe we ran into the usual trouble, and AndroidManifest.xml must have been checked into SVN by the build script after being clobbered.
Found it by compiling from inside Eclipse, instead of from the command line.
Here's a comprehensive yet non-exhaustive list of examples of list
operations and whether or not they are thread safe.
Hoping to get an answer regarding the obj in a_list
language construct here.
Not with an iterator.
For org.json.JSONArray
, you can do:
for (int i = 0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
For javax.json.JsonArray
, you can do:
for (int i = 0; i < arr.size(); i++) {
arr.getJsonObject(i);
}
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
What are Radians and what problem does it solve?:
Radians and degrees are two separate units of measure that help people express and communicate precise changes in direction. Wikipedia has some great intuition with their infographics on how one Radian is defined relative to degrees:
https://en.wikipedia.org/wiki/Radian
Python examples using libraries calculating degrees from radians:
>>> import math
>>> math.degrees(0) #0 radians == 0 degrees
0.0
>>> math.degrees(math.pi/2) #pi/2 radians is 90 degrees
90.0
>>> math.degrees(math.pi) #pi radians is 180 degrees
180.0
>>> math.degrees(math.pi+(math.pi/2)) #pi+pi/2 radians is 270 degrees
270.0
>>> math.degrees(math.pi+math.pi) #2*pi radians is 360 degrees
360.0
Python examples using libraries calculating radians from degrees:
>>> import math
>>> math.radians(0) #0 degrees == 0 radians
0.0
>>> math.radians(90) #90 degrees is pi/2 radians
1.5707963267948966
>>> math.radians(180) #180 degrees is pi radians
3.141592653589793
>>> math.radians(270) #270 degrees is pi+(pi/2) radians
4.71238898038469
>>> math.radians(360) #360 degrees is 2*pi radians
6.283185307179586
Source: https://docs.python.org/3/library/math.html#angular-conversion
The mathematical notation:
If you roll your own degree/radian converter, you have to write your own code to handle edge cases.
Mistakes here are easy to make, and will hurt just like it hurt the developers of the 1999 mars orbiter who sunk $125m dollars crashing it into Mars because of non intuitive edge cases here.
Lets crash that orbiter and Roll our own Radians to Degrees:
Invalid radians as input return garbage output.
>>> 0 * 180.0 / math.pi #0 radians is 0 degrees
0.0
>>> (math.pi/2) * 180.0 / math.pi #pi/2 radians is 90 degrees
90.0
>>> (math.pi) * 180.0 / math.pi #pi radians is 180 degrees
180.0
>>> (math.pi+(math.pi/2)) * 180.0 / math.pi #pi+(pi/2) radians is 270 degrees
270.0
>>> (2 * math.pi) * 180.0 / math.pi #2*pi radians is 360 degrees
360.0
Degrees to radians:
>>> 0 * math.pi / 180.0 #0 degrees in radians
0.0
>>> 90 * math.pi / 180.0 #90 degrees in radians
1.5707963267948966
>>> 180 * math.pi / 180.0 #180 degrees in radians
3.141592653589793
>>> 270 * math.pi / 180.0 #270 degrees in radians
4.71238898038469
>>> 360 * math.pi / 180.0 #360 degrees in radians
6.283185307179586
Expressing multiple rotations with degrees and radians
Single rotation valid radian values are between 0 and 2*pi. Single rotation degree values are between 0 and 360. However if you want to express multiple rotations, valid radian and degree values are between 0 and infinity.
>>> import math
>>> math.radians(360) #one complete rotation
6.283185307179586
>>> math.radians(360+360) #two rotations
12.566370614359172
>>> math.degrees(12.566370614359172) #math.degrees and math.radians preserve the
720.0 #number of rotations
Collapsing multiple rotations:
You can collapse multiple degree/radian rotations into a single rotation by modding against the value of one rotation. For degrees you mod by 360, for radians you modulus by 2*pi.
>>> import math
>>> math.radians(720+90) #2 whole rotations plus 90 is 14.14 radians
14.137166941154069
>>> math.radians((720+90)%360) #14.1 radians brings you to
1.5707963267948966 #the end point as 1.57 radians.
>>> math.degrees((2*math.pi)+(math.pi/2)) #one rotation plus a quarter
450.0 #rotation is 450 degrees.
>>> math.degrees(((2*math.pi)+(math.pi/2))%(2*math.pi)) #one rotation plus a quarter
90.0 #rotation brings you to 90.
Protip
Khan academy has some excellent content to solidify intuition around trigonometry and angular mathematics: https://www.khanacademy.org/math/algebra2/trig-functions/intro-to-radians-alg2/v/introduction-to-radians
f
doesn't actually alter the value of x
(which is always the same reference to an instance of a list). Rather, it alters the contents of this list.
In both cases, a copy of a reference is passed to the function. Inside the function,
n
gets assigned a new value. Only the reference inside the function is modified, not the one outside it.x
does not get assigned a new value: neither the reference inside nor outside the function are modified. Instead, x
’s value is modified.Since both the x
inside the function and outside it refer to the same value, both see the modification. By contrast, the n
inside the function and outside it refer to different values after n
was reassigned inside the function.
One of the easiest ways to check if the area formed by the vertices of triangle (x1,y1),(x2,y2),(x3,y3) is positive or not.
Area can by calculated by the formula:
1/2 [x1(y2–y3) + x2(y3–y1) + x3(y1–y2)]
or python code can be written as:
def triangleornot(p1,p2,p3):
return (1/ 2) [p1[0](p2[1]–p3[1]) + p2[0] (p3[1]–p1[1]) + p3[0] (p1[0]–p2[0])]
+=
is the in-place addition operator.
It's the same as doing cnt = cnt + 1
. For example:
>>> cnt = 0
>>> cnt += 2
>>> print cnt
2
>>> cnt += 42
>>> print cnt
44
The operator is often used in a similar fashion to the ++
operator in C-ish languages, to increment a variable by one in a loop (i += 1
)
There are similar operator for subtraction/multiplication/division/power and others:
i -= 1 # same as i = i - 1
i *= 2 # i = i * 2
i /= 3 # i = i / 3
i **= 4 # i = i ** 4
The +=
operator also works on strings, for example:
>>> s = "Hi"
>>> s += " there"
>>> print s
Hi there
People tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the "Sequence Types" docs:
- If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.
The str.join() method refers to doing the following:
mysentence = []
for x in range(100):
mysentence.append("test")
" ".join(mysentence)
..instead of the more obvious:
mysentence = ""
for x in range(100):
mysentence += " test"
The problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation)
If you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then "".join()
'ing it.
create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS) from PLAYERREGULARSEASON where TEAM = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;
END;
/
I think you can't achieve what you want in a more efficient manner than you proposed.
The underlying problem is that the timestamps (as you seem aware) are made up of two parts. The data that represents the UTC time, and the timezone, tz_info. The timezone information is used only for display purposes when printing the timezone to the screen. At display time, the data is offset appropriately and +01:00 (or similar) is added to the string. Stripping off the tz_info value (using tz_convert(tz=None)) doesn't doesn't actually change the data that represents the naive part of the timestamp.
So, the only way to do what you want is to modify the underlying data (pandas doesn't allow this... DatetimeIndex are immutable -- see the help on DatetimeIndex), or to create a new set of timestamp objects and wrap them in a new DatetimeIndex. Your solution does the latter:
pd.DatetimeIndex([i.replace(tzinfo=None) for i in t])
For reference, here is the replace
method of Timestamp
(see tslib.pyx):
def replace(self, **kwds):
return Timestamp(datetime.replace(self, **kwds),
offset=self.offset)
You can refer to the docs on datetime.datetime
to see that datetime.datetime.replace
also creates a new object.
If you can, your best bet for efficiency is to modify the source of the data so that it (incorrectly) reports the timestamps without their timezone. You mentioned:
I want to work with timezone naive timeseries (to avoid the extra hassle with timezones, and I do not need them for the case I am working on)
I'd be curious what extra hassle you are referring to. I recommend as a general rule for all software development, keep your timestamp 'naive values' in UTC. There is little worse than looking at two different int64 values wondering which timezone they belong to. If you always, always, always use UTC for the internal storage, then you will avoid countless headaches. My mantra is Timezones are for human I/O only.
Had to restart the Eclipse after completing the installation of ARM EABI v7a system image.
You can append a select statement to your insert statement. Integer myInt = Insert into table1 (FName) values('Fred'); Select Scope_Identity(); This will return a value of the identity when executed scaler.
You must define the class before creating an instance of the class. Move the invocation of Something
to the end of the script.
You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:
From a quick glance on MDN I think you may need to include the .js
at the end of your file name so the import would read
import './course.js'
instead of import './course'
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
First, make sure you have the environment variable set up. 1. Right click on my computer 2. properties 3. advanced system settings 4. environment variables 5. edit the PATH variable. and add ;"C:\mongoDb\bin\" to the PATH variable.
Path in the quotes may differ depending on your installation directory. Do not forget the last '\' as it was the main problem in my case.
To get the value of my drop down box on page load, I use
document.addEventListener('DOMContentLoaded',fnName);
Hope this helps some one.
Try something like:
SELECT `column`
FROM `your_table`
GROUP BY `column`
ORDER BY COUNT(*) DESC
LIMIT 1;
Just in case someone is looking to this too. In .net core 3+ most of this is obsolete. The update way is:
public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env,
ILogger<Startup> logger)
{
if (env.EnvironmentName == Environments.Development)
{
// logger.LogInformation("In Development environment");
}
}
Here's an example that will center the content within the parent div. This also makes sure the overlay starts at the edge of the video, even when centered.
<div class="outer-container">
<div class="inner-container">
<div class="video-overlay">Bug Buck Bunny - Trailer</div>
<video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" controls autoplay loop></video>
</div>
</div>
with css as
.outer-container {
border: 1px dotted black;
width: 100%;
height: 100%;
text-align: center;
}
.inner-container {
border: 1px solid black;
display: inline-block;
position: relative;
}
.video-overlay {
position: absolute;
left: 0px;
top: 0px;
margin: 10px;
padding: 5px 5px;
font-size: 20px;
font-family: Helvetica;
color: #FFF;
background-color: rgba(50, 50, 50, 0.3);
}
video {
width: 100%;
height: 100%;
}
here's the jsfiddle https://jsfiddle.net/dyrepk2x/2/
Hope that helps :)
Change the onclick from
onclick="javascript:SubmitFrm()"
to
onclick="SubmitFrm()"
Constructor looks like a method but name should be as class name and no return value.
Overriding means what we have declared in Super class, that exactly we have to declare in Sub class it is called Overriding. Super class name and Sub class names are different.
If you trying to write Super class Constructor in Sub class, then Sub class will treat that as a method not constructor because name should not match with Sub class name. And it will give an compilation error that methods does not have return value. So we should declare as void, then only it will compile.
A 'router' could be doing anything - particularly NAT, which might involve any amount of bug-ridden messing with traffic...
One reason a device will send a RST is in response to receiving a packet for a closed socket.
It's hard to give a firm but general answer, because every possible perversion has been visited on TCP since its inception, and all sorts of people might be inserting RSTs in an attempt to block traffic. (Some 'national firewalls' work like this, for example.)
You can get the input element and then set its readOnly
property to true
as follows:
document.getElementById('InputFieldID').readOnly = true;
Specifically, this is what you want:
<script type="text/javascript">
function onLoadBody() {
document.getElementById('control_EMAIL').readOnly = true;
}
</script>
Call this onLoadBody()
function on body tag like:
<body onload="onLoadBody">
View Demo: jsfiddle.
From a Spring point of view, none of the HttpMessageConverter
instances registered with the RestTemplate
can convert text/html
content to a ProductList
object. The method of interest is HttpMessageConverter#canRead(Class, MediaType)
. The implementation for all of the above returns false
, including Jaxb2RootElementHttpMessageConverter
.
Since no HttpMessageConverter
can read your HTTP response, processing fails with an exception.
If you can control the server response, modify it to set the Content-type
to application/xml
, text/xml
, or something matching application/*+xml
.
If you don't control the server response, you'll need to write and register your own HttpMessageConverter
(which can extend the Spring classes, see AbstractXmlHttpMessageConverter
and its sub classes) that can read and convert text/html
.
An Observable is an object that emits a stream of events: Next, Error and Completed.
When your function returns an Observable, it is not returning a stream, but an instance of Observable. The flatMap
operator simply maps that instance to a stream.
That is the behaviour of flatMap
when compared to map
: Execute the given function and flatten the resulting object into a stream.
The shape of your matrix C
is wrong; it's the transpose of what you actually want it to be. (But I agree with ulmangt: the Right Thing is almost certainly to use numpy, really.)
Try loading your javascript after.
Try this:
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="submit" id="myButton" value="Go" />
</form>
<script src="js/script.js" type="text/javascript"></script>
Since you want to check whether textboxes contains any value or not your code should do the job. You should be more specific about the error you are having. You can also do:
if(textBox1.Text == string.Empty || textBox2.Text == string.Empty)
{
MessageBox.Show("You must enter a value into both boxes");
}
EDIT 2: based on @JonSkeet comments:
Usage of string.Compare is not required as per OP's original unedited post. String.Equals should do the job if one wants to compare strings, and StringComparison
may be used to ignore case for the comparison. string.Compare should be used for order comparison.
Originally the question contain this comparison,
string testString = "This is a test";
string testString2 = "This is not a test";
if (testString == testString2)
{
//do some stuff;
}
the if statement can be replaced with
if(testString.Equals(testString2))
or following to ignore case.
if(testString.Equals(testString2,StringComparison.InvariantCultureIgnoreCase))
Here is a simple rule that can help you decide. It is related to how interfaces are used in Java.
Take your class and imagine designing an interface for it such that the interface describes the functionality of the class but none of the underlying implementation (as an interface should). Pretend perhaps that you might implement the class in another way.
Look at the methods of the interface and consider the exceptions they might throw:
If an exception can be thrown by a method, regardless of the underlying implementation (in other words, it describes the functionality only) then it should probably be a checked exception in the interface.
If an exception is caused by the underlying implementation, it should not be in the interface. Therefore, it must either be an unchecked exception in your class (since unchecked exceptions need not appear in the interface signature), or you must wrap it and rethrow as a checked exception that is part of the interface method.
To decide if you should wrap and rethrow, you should again consider whether it makes sense for a user of the interface to have to handle the exception condition immediately, or the exception is so general that there is nothing you can do about it and it should propagate up the stack. Does the wrapped exception make sense when expressed as functionality of the new interface you are defining or is it just a carrier for a bag of possible error conditions that could also happen to other methods? If the former, it might still be a checked exception, otherwise it should be unchecked.
You should not usually plan to "bubble-up" exceptions (catch and rethrow). Either an exception should be handled by the caller (in which case it is checked) or it should go all the way up to a high level handler (in which case it is easiest if it is unchecked).
I also wanted to do this, but with a method that receives a BOOL parameter. Wrapping the bool value with NSNumber, FAILED TO PASS THE VALUE. I have no idea why.
So I ended up doing a simple hack. I put the required parameter in another dummy function and call that function using the performSelector, where withObject = nil;
[self performSelector:@selector(dummyCaller:) withObject:nil afterDelay:5.0];
-(void)dummyCaller {
[self myFunction:YES];
}
According to this documentation, starting in MySQL 8.0.13, you will be able to specify:
CREATE TABLE INVOICE(
INVOICEDATE DATE DEFAULT (CURRENT_DATE)
)
Unfortunately, as of today, that version is not yet released. You can check here for the latest updates.
Invoke mysql with the -N
(the alias for -N
is --skip-column-names
) option:
mysql -N ...
use testdb;
select * from names;
+------+-------+
| 1 | pete |
| 2 | john |
| 3 | mike |
+------+-------+
3 rows in set (0.00 sec)
Credit to ErichBSchulz for pointing out the -N alias.
To remove the grid (the vertical and horizontal lines) around the results use -s
(--silent
). Columns are separated with a TAB
character.
mysql -s ...
use testdb;
select * from names;
id name
1 pete
2 john
3 mike
To output the data with no headers and no grid just use both -s
and -N
.
mysql -sN ...
Try to check it once more according to this tutorial: http://vietpad.sourceforge.net/javaonwindows.html
Try to reboot your system.
If nothing, try to run "cmd" and type there "java", does it print anything?
That's not true Jeff.
You simply have to select a folder within your IIS 7 Manager UI (e.g. Images or event the Default Web Application folder) and then click on "HTTP Response Headers". Then you have to click on "Set Common Header.." in the right pane and select the "Expire Web content". There you can easily configure a max-age of 24 hours by choosing "After:", entering "24" in the Textbox and choose "Hours" in the combobox.
Your first paragraph regarding the web.config entry is right. I'd add the cacheControlCustom-attribute to set the cache control header to "public" or whatever is needed in that case.
You can, of course, achieve the same by providing web.config entries (or files) as needed.
Edit: removed a confusing sentence :)
Both values can be easily distinguished by using the strict comparison operator:
Working example at:
http://www.thesstech.com/tryme?filename=nullandundefined
Sample Code:
function compare(){
var a = null; //variable assigned null value
var b; // undefined
if (a === b){
document.write("a and b have same datatype.");
}
else{
document.write("a and b have different datatype.");
}
}
To make things shorter You can use this:
android.text.format.DateFormat.format("EEEE", date);
which will return day of the week as a String.
I would just like to say that it REALLY isn't that difficult to get an xrange object with slice and indexing functionality. I have written some code that works pretty dang well and is just as fast as xrange for when it counts (iterations).
from __future__ import division
def read_xrange(xrange_object):
# returns the xrange object's start, stop, and step
start = xrange_object[0]
if len(xrange_object) > 1:
step = xrange_object[1] - xrange_object[0]
else:
step = 1
stop = xrange_object[-1] + step
return start, stop, step
class Xrange(object):
''' creates an xrange-like object that supports slicing and indexing.
ex: a = Xrange(20)
a.index(10)
will work
Also a[:5]
will return another Xrange object with the specified attributes
Also allows for the conversion from an existing xrange object
'''
def __init__(self, *inputs):
# allow inputs of xrange objects
if len(inputs) == 1:
test, = inputs
if type(test) == xrange:
self.xrange = test
self.start, self.stop, self.step = read_xrange(test)
return
# or create one from start, stop, step
self.start, self.step = 0, None
if len(inputs) == 1:
self.stop, = inputs
elif len(inputs) == 2:
self.start, self.stop = inputs
elif len(inputs) == 3:
self.start, self.stop, self.step = inputs
else:
raise ValueError(inputs)
self.xrange = xrange(self.start, self.stop, self.step)
def __iter__(self):
return iter(self.xrange)
def __getitem__(self, item):
if type(item) is int:
if item < 0:
item += len(self)
return self.xrange[item]
if type(item) is slice:
# get the indexes, and then convert to the number
start, stop, step = item.start, item.stop, item.step
start = start if start != None else 0 # convert start = None to start = 0
if start < 0:
start += start
start = self[start]
if start < 0: raise IndexError(item)
step = (self.step if self.step != None else 1) * (step if step != None else 1)
stop = stop if stop is not None else self.xrange[-1]
if stop < 0:
stop += stop
stop = self[stop]
stop = stop
if stop > self.stop:
raise IndexError
if start < self.start:
raise IndexError
return Xrange(start, stop, step)
def index(self, value):
error = ValueError('object.index({0}): {0} not in object'.format(value))
index = (value - self.start)/self.step
if index % 1 != 0:
raise error
index = int(index)
try:
self.xrange[index]
except (IndexError, TypeError):
raise error
return index
def __len__(self):
return len(self.xrange)
Honestly, I think the whole issue is kind of silly and xrange should do all of this anyway...
In django 2.2 this is explained here
https://docs.djangoproject.com/en/2.2/howto/overriding-templates/
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
...,
'blog',
...,
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
...
},
]
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...
If you're using SQL Server express, change
SqlConnection conn = new SqlConnection("Server=localhost;"
+ "Database=Database1;");
to
SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;"
+ "Database=Database1;");
That, and hundreds more connection strings can be found at http://www.connectionstrings.com/
The Maximally Standards Compliant way to do it is to create a text node containing the text you want and append it to the span (removing any currently extant text nodes).
The way I would actually do it is to use jQuery's .text()
.
It's not print that does the formatting, It's a property of strings, so you can just use
newstring = "%.9f" % numvar
In Access 2007 - 2010, go to Database Tools and click Compact and Repair Database, and it will automatically reset the ID.
Raphaël supports this, with its Graffle example.
This answer is based off of Awais Akhtar's answer, and Vaibhav Jain's answer.
In my case, setting SQL Server Database Engine service startup account to NT AUTHORITY\NETWORK SERVICE failed, but setting it to NT Authority\System allowed me to succesfully install my SQL Server 2016 STD instance.
Just check the following snapshot.
For further details, check @Shanky's answer at https://dba.stackexchange.com/a/71798/66179
Remember: you can avoid server rebooting using setup's SkipRules switch:
setup.exe /ACTION=INSTALL /SkipRules=RebootRequiredCheck
setup.exe /ACTION=UNINSTALL /SkipRules=RebootRequiredCheck
http://www.unicode.org is the place to look for symbol names.
? BLACK CIRCLE 25CF
? MEDIUM BLACK CIRCLE 26AB
? BLACK LARGE CIRCLE 2B24
or even:
NEW MOON SYMBOL 1F311
Good luck finding a font that supports them all. Only one shows up in Windows 7 with Chrome.
Option 2
<ul>
<li>Choice A</li>
<li>Choice B
<ul>
<li>Sub 1</li>
<li>Sub 2</li>
</ul>
</li>
</ul>
keep it simple. Most modern browsers support a maxlength attribute on a text area (IE included), so simply add that attribute in code-behind. No JS, no Jquery, no inheritance, custom code, no fuss, no muss.
VB.Net:
fld_description.attributes("maxlength") = 255
C#
fld_description.Attributes["maxlength"] = 255
Try this code. You can use $.get
instead of $.ajax
$( "input.suggest-user" ).autocomplete({
source: function( request, response ) {
$.ajax({
dataType: "json",
type : 'Get',
url: 'yourURL',
success: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
// hide loading image
response( $.map( data, function(item) {
// your operation on data
}));
},
error: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3,
open: function() {},
close: function() {},
focus: function(event,ui) {},
select: function(event, ui) {}
});
I found the web.config route useful (tried to add it to the answer but doesn't seem to have been accepted so posting here)
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Cache-Control" value="no-cache, no-store, must-revalidate" />
<!-- HTTP 1.1. -->
<add name="Pragma" value="no-cache" />
<!-- HTTP 1.0. -->
<add name="Expires" value="0" />
<!-- Proxies. -->
</customHeaders>
</httpProtocol>
</system.webServer>
And here is the express / node.js way of doing the same:
app.use(function(req, res, next) {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
next();
});
firstOrCreate() checks for all the arguments to be present before it finds a match.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'abcd',
'lastName' => 'efgh',
'veristyName'=>'xyz',
]);
Then it check only the email
I'd factor out the prepared statement handling to at least a method. In this case, because there are no results it is fairly simple (and assuming that the connection is an instance variable that doesn't change):
private PreparedStatement updateSales;
public void updateSales(int sales, String cof_name) throws SQLException {
if (updateSales == null) {
updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
}
updateSales.setInt(1, sales);
updateSales.setString(2, cof_name);
updateSales.executeUpdate();
}
At that point, it is then just a matter of calling:
updateSales(75, "Colombian");
Which is pretty simple to integrate with other things, yes? And if you call the method many times, the update will only be constructed once and that will make things much faster. Well, assuming you don't do crazy things like doing each update in its own transaction...
Note that the types are fixed. This is because for any particular query/update, they should be fixed so as to allow the database to do its job efficiently. If you're just pulling arbitrary strings from a CSV file, pass them in as strings. There's also no locking; far better to keep individual connections to being used from a single thread instead.
I had the exact same problem and solved it running the folowing command from the command line as an admin :
1) first stop the service with the following
net stop http /y
2) then disable the startup (optional)
sc config http start= disabled
To remove the first and last characters, and in each case do the removal only if the character in question is a double quote:
import re
s = re.sub(r'^"|"$', '', s)
Note that the RE pattern is different than the one you had given, and the operation is sub
("substitute") with an empty replacement string (strip
is a string method but does something pretty different from your requirements, as other answers have indicated).
We control fork() process call by if, else statement. See my code below:
int main()
{
int forkresult, parent_ID;
forkresult=fork();
if(forkresult !=0 )
{
printf(" I am the parent my ID is = %d" , getpid());
printf(" and my child ID is = %d\n" , forkresult);
}
parent_ID = getpid();
if(forkresult ==0)
printf(" I am the child ID is = %d",getpid());
else
printf(" and my parent ID is = %d", parent_ID);
}
I know I'm late to the party, but I've been working on this problem recently. I hope someone sees this because the accepted answer, although correct, is not the best way you can do this. Not in PHPStorm at least, I haven't tested NetBeans though.
The best way involves extending the ArrayIterator class rather than using native array types. This allows you to type hint at a class-level rather than at an instance-level, meaning you only have to PHPDoc once, not throughout your code (which is not only messy and violates DRY, but can also be problematic when it comes to refactoring - PHPStorm has a habit of missing PHPDoc when refactoring)
See code below:
class MyObj
{
private $val;
public function __construct($val) { $this->val = $val; }
public function getter() { return $this->val; }
}
/**
* @method MyObj current()
*/
class MyObjCollection extends ArrayIterator
{
public function __construct(Array $array = [])
{
foreach($array as $object)
{
if(!is_a($object, MyObj::class))
{
throw new Exception('Invalid object passed to ' . __METHOD__ . ', expected type ' . MyObj::class);
}
}
parent::__construct($array);
}
public function echoContents()
{
foreach($this as $key => $myObj)
{
echo $key . ': ' . $myObj->getter() . '<br>';
}
}
}
$myObjCollection = new MyObjCollection([
new MyObj(1),
new MyObj('foo'),
new MyObj('blah'),
new MyObj(23),
new MyObj(array())
]);
$myObjCollection->echoContents();
The key here is the PHPDoc @method MyObj current()
overriding the return type inherited from ArrayIterator (which is mixed
). The inclusion of this PHPDoc means that when we iterate over the class properties using foreach($this as $myObj)
, we then get code completion when referring to the variable $myObj->...
To me, this is the neatest way to achieve this (at least until PHP introduces Typed Arrays, if they ever do), as we're declaring the iterator type in the iterable class, not on instances of the class scattered throughout the code.
I haven't shown here the complete solution for extending ArrayIterator, so if you use this technique, you may also want to:
offsetGet($index)
and next()
is_a($object, MyObj::class)
from the constructor into a private methodoffsetSet($index, $newval)
and append($value)
Isn't the easiest way to create a class contining all the needed variables? Then you have one object with all curretn variables, and if you need you can overwrite this variable?
After clicking on Properties of any installer(.exe) which block your application to install (Windows Defender SmartScreen prevented an unrecognized app ) for that issue i found one solution
- Right click on installer(.exe)
- Select properties option.
- Click on checkbox to check Unblock at the bottom of Properties.
This solution work for Heroku CLI (heroku-x64) installer(.exe)
Here is the same solution than Rukshan but in sass (in order to keep your grid configuration) for special case that don't work with Ross Allen solution (when you can't have a parent div.row)
@mixin make-grid-offset-right($class) {
@for $index from 0 through $grid-columns {
.col-#{$class}-offset-right-#{$index} {
margin-right: percentage(($index / $grid-columns));
}
}
}
@include make-grid-offset-right(xs);
@media (min-width: $screen-sm-min) {
@include make-grid-offset-right(sm);
}
@media (min-width: $screen-md-min) {
@include make-grid-offset-right(md);
}
@media (min-width: $screen-lg-min) {
@include make-grid-offset-right(lg);
}
export class ClassComponent implements OnInit {
classes = [
{
name: 'string',
level: 'string',
code: 'number',
currentLesson: '1'
}]
checkCurrentLession(current){
this.classes.forEach((obj)=>{
if(obj.currentLession == current){
return true;
}
});
return false;
}
<ul class="table lessonOverview">
<li>
<p>Lesson 1</p>
<button [routerLink]="['/lesson1']"
[disabled]="checkCurrentLession(1)" class="primair">
Start lesson</button>
</li>
<li>
<p>Lesson 2</p>
<button [routerLink]="['/lesson2']"
[disabled]="!checkCurrentLession(2)" class="primair">
Start lesson</button>
</li>
</ul>
Easy way to make a bash script log to syslog. The script output is available both through /var/log/syslog
and through stderr. syslog will add useful metadata, including timestamps.
Add this line at the top:
exec &> >(logger -t myscript -s)
Alternatively, send the log to a separate file:
exec &> >(ts |tee -a /tmp/myscript.output >&2 )
This requires moreutils
(for the ts
command, which adds timestamps).
In my case (using windows 10) gradlew.bat has the following lines of code in:
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
The APP_HOME variable is essentially gradles root folder for the project, so, if this gets messed up in some way you are going to get:
Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain
For me, this had been messed up because my project folder structure had an ampersand (&) in it. Eg C:\Test&Dev\MyProject
So, gradel was trying to find the gradle-wrapper.jar file in a root folder of C:\Test (stripping off everything after and including the '&')
I found this by adding the following line below the set APP_HOME=%DIRNAME% line above. Then ran the bat file to see the result.
echo "%APP_HOME%"
There will be a few other 'special characters' that could break a path/directory.
Push a new page onto the stack, then remove the current page. This results in a switch.
item.Tapped += async (sender, e) => {
await Navigation.PushAsync (new SecondPage ());
Navigation.RemovePage(this);
};
You need to be in a Navigation Page first:
MainPage = NavigationPage(new FirstPage());
Switching content isn't ideal as you have just one big page and one set of page events like OnAppearing ect.
132 is outside the range of a byte which is -128 to 127 (Byte.MIN_VALUE to Byte.MAX_VALUE) Instead the top bit of the 8-bit value is treated as the signed which indicates it is negative in this case. So the number is 132 - 256 = -124.
Here's my solution (in Spring with Thymeleaf and jQuery):
html:
<!DOCTYPE html>
<html
xmlns:th="http://www.thymeleaf.org"
xmlns:tiles="http://www.thymeleaf.org">
<body>
<div id="objects" th:fragment="ObjectList">
<br/>
<div id='cap'>
<span>Objects</span>
</div>
<div id="hdr">
<div>
<div class="Cell">Name</div>
<div class="Cell">Type</div>
</div>
</div>
<div id="bdy">
<div th:each="object : ${objectlist}">
<div class="Cell" th:text="${object.name}">name</div>
<div class="Cell" th:text="${object.type}">type</div>
</div>
</div>
</div>
</body>
</html>
css:
@CHARSET "UTF-8";
#cap span {
display: table-caption;
border:2px solid;
font-size: 200%;
padding: 3px;
}
#hdr {
display:block;
padding:0px;
margin-left:0;
border:2px solid;
}
#bdy {
display:block;
padding:0px;
margin-left:0;
border:2px solid;
}
#objects #bdy {
height:300px;
overflow-y: auto;
}
#hdr div div{
margin-left:-3px;
margin-right:-3px;
text-align: right;
}
#hdr div:first-child {
text-align: left;
}
#bdy div div {
margin-left:-3px;
margin-right:-3px;
text-align: right;
}
#bdy div div:first-child {
text-align: left;
}
.Cell
{
display: table-cell;
border: solid;
border-width: thin;
padding-left: 5px;
padding-right: 5px;
}
javascript:
$(document).ready(function(){
var divs = ['#objects'];
divs.forEach(function(div)
{
if ($(div).length > 0)
{
var widths = [];
var totalWidth = 0;
$(div+' #hdr div div').each(function() {
widths.push($(this).width())
});
$(div+' #bdy div div').each(function() {
var col = $(this).index();
if ( $(this).width() > widths[col] )
{
widths[col] = $(this).width();
}
});
$(div+' #hdr div div').each(function() {
var newWidth = widths[$(this).index()]+5;
$(this).css("width", newWidth);
totalWidth += $(this).outerWidth();
});
$(div+' #bdy div div').each(function() {
$(this).css("width", widths[$(this).index()]+5);
});
$(div+' #hdr').css("width", totalWidth);
$(div+' #bdy').css("width", totalWidth+($(div+' #bdy').css('overflow-y')=='auto'?15:0));
}
})
});
Use .append instead of .html
var response = "[{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}]";
// convert string to JSON
response = $.parseJSON(response);
$(function() {
$.each(response, function(i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.rank),
$('<td>').text(item.content),
$('<td>').text(item.UID)
); //.appendTo('#records_table');
console.log($tr.wrap('<p>').html());
});
});
var arr = new Array();
$('li').each(function() {
arr.push(this.innerHTML);
})
sudo apt-get install ruby-dev
This command solved the problem for me!
1)What is the difference between both the way of creating class objects.
First one is a pointer to a constructed object in heap (by new
).
Second one is an object that implicitly constructed. (Default constructor)
2)If i am creating object like Example example; how to use that in an singleton class.
It depends on your goals, easiest is put it as a member in class simply.
A sample of a singleton class which has an object from Example
class:
class Sample
{
Example example;
public:
static inline Sample *getInstance()
{
if (!uniqeInstance)
{
uniqeInstance = new Sample;
}
return uniqeInstance;
}
private:
Sample();
virtual ~Sample();
Sample(const Sample&);
Sample &operator=(const Sample &);
static Sample *uniqeInstance;
};
to check input and get confirm by check box ,use this script...
$(document).on("change", ".inputClass", function () {
if($(this).is(':checked')){
confirm_message = $(this).data('confirm');
var confirm_status = confirm(confirm_message);
if (confirm_status == true) {
//doing somethings...
}
}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> check action </lable>
<input class="inputClass" type="checkbox" data-confirm="are u sure to do ...?" >
_x000D_
According to this MSDN blog: https://blogs.msdn.microsoft.com/manishagarwal/2005/09/28/resolving-file-references-in-team-build-part-2/
There is a search order for assemblies when building. The search order is as follows:
So, if the desired assembly is found by HintPath, but an alternate assembly can be found using ReferencePath, it will prefer the ReferencePath'd assembly to the HintPath'd one.
I happened across this due to having the same problem. I'm working with variable font size, so this takes that into account:
var texts=($(this).find('.noteContent').html()).split("<br>");
for (var k in texts) {
ctx.fillText(texts[k], left, (top+((parseInt(ctx.font)+2)*k)));
}
where .noteContent is the contenteditable div the user edited (this is nested in a jQuery each function), and ctx.font is "14px Arial" (notice that the pixel size comes first)
Simplest solution for sending email from Organizational account in Office 365:
from O365 import Message
html_template = """
<html>
<head>
<title></title>
</head>
<body>
{}
</body>
</html>
"""
final_html_data = html_template.format(df.to_html(index=False))
o365_auth = ('sender_username@company_email.com','Password')
m = Message(auth=o365_auth)
m.setRecipients('receiver_username@company_email.com')
m.setSubject('Weekly report')
m.setBodyHTML(final_html_data)
m.sendMessage()
here df is a dataframe converted to html Table, which is being injected to html_template
GCC: GNU Compiler Collection
gcc
: GNU C Compiler
g++
: GNU C++ Compiler
The main differences:
gcc
will compile: *.c\*.cpp
files as C and C++ respectively.g++
will compile: *.c\*.cpp
files but they will all be treated as C++ files.g++
to link the object files it automatically links in the std C++ libraries (gcc
does not do this).gcc
compiling C files has fewer predefined macros.gcc
compiling *.cpp
and g++
compiling *.c\*.cpp
files has a few extra macros.Extra Macros when compiling *.cpp
files:
#define __GXX_WEAK__ 1
#define __cplusplus 1
#define __DEPRECATED 1
#define __GNUG__ 4
#define __EXCEPTIONS 1
#define __private_extern__ extern
For Centos 7 Use below command to install Python Development Package
Python 2.7
sudo yum install python-dev
Python 3.4
sudo yum install python34-devel
Still if your problem not solved then try installing below packages -
sudo yum install libffi-devel
sudo yum install openssl-devel
Step 1) Create Profile and Account
You need to create a profile and account using the Configure Database Mail Wizard which can be accessed from the Configure Database Mail context menu of the Database Mail node in Management Node. This wizard is used to manage accounts, profiles, and Database Mail global settings.
Step 2)
RUN:
sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO
Step 3)
USE msdb
GO
EXEC sp_send_dbmail @profile_name='yourprofilename',
@recipients='[email protected]',
@subject='Test message',
@body='This is the body of the test message.
Congrates Database Mail Received By you Successfully.'
To loop through the table
DECLARE @email_id NVARCHAR(450), @id BIGINT, @max_id BIGINT, @query NVARCHAR(1000)
SELECT @id=MIN(id), @max_id=MAX(id) FROM [email_adresses]
WHILE @id<=@max_id
BEGIN
SELECT @email_id=email_id
FROM [email_adresses]
set @query='sp_send_dbmail @profile_name=''yourprofilename'',
@recipients='''+@email_id+''',
@subject=''Test message'',
@body=''This is the body of the test message.
Congrates Database Mail Received By you Successfully.'''
EXEC @query
SELECT @id=MIN(id) FROM [email_adresses] where id>@id
END
Posted this on the following link http://ms-sql-queries.blogspot.in/2012/12/how-to-send-email-from-sql-server.html
LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception e){
e.printStackTrace();
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception e){
e.printStackTrace();
}
if(!gps_enabled && !network_enabled) {
// notify user
new AlertDialog.Builder(this)
.setMessage("Please turn on Location to continue")
.setPositiveButton("Open Location Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).
setNegativeButton("Cancel",null)
.show();
}
If you create your GUI with Netbeans, you can also insert some self written code. Just select an element (maybe the button, panel or the window) and use the "Code"-tab in the "Properties"-dialog.
There you can insert Pre- and Post- code for various parts of the creation process.
I think the "After-All-Set-Code" field of the window is a good place for your code, or you could bind it to the event ("Properties"-dialog -> "Events") "componentShown" of the text field / panel.
Vi or Vim?
Anyway, the following command works for Vim in 'nocompatible' mode. That is, I suppose, almost pure vi.
:join!
If you want to do it from normal command use
gJ
With 'gJ' you join lines as is -- without adding or removing whitespaces:
S<Switch_ID>_F<File type>
_ID<ID number>_T<date+time>_O<Original File name>.DAT
Result:
S<Switch_ID>_F<File type>_ID<ID number>_T<date+time>_O<Original File name>.DAT
With 'J' command you will have:
S<Switch_ID>_F<File type> _ID<ID number>_T<date+time>_O<Original File name>.DAT
Note space between type>
and _ID
.
this part :
"Your new price is: $"(float(price)
asks python to call this string:
"Your new price is: $"
just like you would a function:
function( some_args)
which will ALWAYS trigger the error:
TypeError: 'str' object is not callable
I used this command to get the ip address of my Ethernet network adapter into a variable called IP.
for /f "tokens=3 delims=: " %i in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i
Most commands using ipconfig
for example just print out all your IP addresses and I needed a specific one which in my case was for my Ethernet network adapter.
You can see your list of network adapters by using the netsh interface ipv4 show interfaces
command. Most people need Wi-Fi or Ethernet.
You'll see a table like so in the output to the command prompt:
Idx Met MTU State Name
--- ---------- ---------- ------------ ---------------------------
1 75 4294967295 connected Loopback Pseudo-Interface 1
15 25 1500 connected Ethernet
17 5000 1500 connected vEthernet (Default Switch)
32 15 1500 connected vEthernet (DockerNAT)
In the name column you should find the network adapter you want (i.e. Ethernet, Wi-Fi etc.).
As mentioned, I was interested in Ethernet
in my case.
To get the IP for that adapter we can use the netsh command:
netsh interface ip show config name="Ethernet"
This gives us this output:
Configuration for interface "Ethernet"
DHCP enabled: Yes
IP Address: 169.252.27.59
Subnet Prefix: 169.252.0.0/16 (mask 255.255.0.0)
InterfaceMetric: 25
DNS servers configured through DHCP: None
Register with which suffix: Primary only
WINS servers configured through DHCP: None
(I faked the actual IP number above for security reasons )
I can further specify which line I want using the findstr
command in the ms-dos command prompt.
Here I want the line containing the string IP Address
.
netsh interface ip show config name="Ethernet" | findstr "IP Address"
This gives the following output:
IP Address: 169.252.27.59
I can then use the for
command that allows me to parse files (or multiline strings in this case) and split out the strings' contents based on a delimiter and the item number that I'm interested in.
Note that I am looking for the third item (tokens=3) and that I am using the space character and :
as my delimiters (delims=:
).
for /f "tokens=3 delims=: " %i in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i
Each value or token in the loop is printed off as the variable %i but I'm only interested in the third "token" or item (hence tokens=3
). Note that I had to escape the |
and =
using a ^
At the end of the for
command you can specify a command to run with the content that is returned. In this case I am using set
to assign the value to an environment variable called IP
. If you want you could also just echo the value or what ever you like.
With that you get an environment variable with the IP Address of your preferred network adapter assigned to an environment variable. Pretty neat, huh?
If you have any ideas for improving please leave a comment.
Just send an array in the session rather than a string, like this:
Session::flash('message', ['text'=>'this is a danger message','type'=>'danger']);
@if(Session::has('message'))
<div class="alert alert-{{session('message')['type']}}">
{{session('message')['text']}}
</div>
@endif
In case you use jQuery on the client side, you may be interested in this blog post that provides code how to globally extend jQuery's $.parseJSON()
function to automatically convert dates for you.
You don't have to change existing code in case of adding this code. It doesn't affect existing calls to $.parseJSON()
, but if you start using $.parseJSON(data, true)
, dates in data
string will be automatically converted to Javascript dates.
It supports Asp.net date strings: /Date(2934612301)/
as well as ISO strings 2010-01-01T12_34_56-789Z
. The first one is most common for most used back-end web platform, the second one is used by native browser JSON support (as well as other JSON client side libraries like json2.js).
Anyway. Head over to blog post to get the code. http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html
upsert(array, item) {
const i = array.findIndex(_item => _item.id === item.id);
if (i > -1) {
let result = array.filter(obj => obj.id !== item.id);
return [...result, item]
}
else {
return [...array, item]
};
}