First, close all instances of Google Chrome. There should be no instances of chrome.exe
running in the Windows Task Manager. Then
%LOCALAPPDATA%\Google\Chrome\User Data\Default\
..txt
). This will serve as a backup, should something go wrong.window_placement
. Under window_placement
you will see things like "bottom", "left", "right", etc. with numbers after them.You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.
Just keep going with your code - you're on the right track:
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("NewColumn", typeof(System.Int32));
foreach(DataRow row in dt.Rows)
{
//need to set value to NewColumn column
row["NewColumn"] = 0; // or set it to some other value
}
// possibly save your Dataset here, after setting all the new values
In my case, the customer forgot to add new IP address in their SMTP settings. Open IIS 6.0 in the server which sets up the smtp, right click Smtp virtual server, choose Properties, Access tab, click Connections, add IP address of the new server. Then click Relay, also add IP address of the new server. This solved my issue.
I suggest you to use StringBuilder
class for it and than parse it to string if you need.
System.Text.StringBuilder strBuilder = new System.Text.StringBuilder("valta is the best place in the World");
strBuilder[0] = 'M';
string str=strBuilder.ToString();
You can't change string's characters in this way, because in C# string isn't dynamic and is immutable and it's chars are readonly. For make sure in it try to use methods of string, for example, if you do str.ToLower()
it makes new string and your previous string doesn't change.
I was getting this error:
The type com.ibm.portal.state.exceptions.StateException cannot be resolved. It is indirectly referenced from required .class files
Doing the following fixed it for me:
Properties -> Java build path -> Libraries -> Server Library[wps.base.v61]unbound -> Websphere Portal v6.1 on WAS 7 -> Finish -> OK
Your BlockID
function uses the undefined variable images
, which will lead to an error. Also, you should not use an Array
here - JavaScripts key-value-maps are plain objects:
function BlockID() {
return {
"s": "Images/Block_01.png",
"g": "Images/Block_02.png",
"C": "Images/Block_03.png",
"d": "Images/Block_04.png"
};
}
Look into the XMLSerializer
class.
If you want to save the state of objects and be able to recreate them easily at another time, serialization is your best bet.
Serialize it so you are returned the fully-formed XML. Write this to a file using the StreamWriter
class.
Later, you can read in the contents of your file, and pass it to the serializer class along with an instance of the object you want to populate, and the serializer will take care of deserializing as well.
Here's a code snippet taken from Microsoft Support:
using System;
public class clsPerson
{
public string FirstName;
public string MI;
public string LastName;
}
class class1
{
static void Main(string[] args)
{
clsPerson p=new clsPerson();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
// at this step, instead of passing Console.Out, you can pass in a
// Streamwriter to write the contents to a file of your choosing.
x.Serialize(Console.Out, p);
Console.WriteLine();
Console.ReadLine();
}
}
try this:
$string = iconv("UTF-8","UTF-8//IGNORE",$string);
According to the iconv manual, the function will take the first parameter as the input charset, second parameter as the output charset, and the third as the actual input string.
If you set both the input and output charset to UTF-8, and append the //IGNORE
flag to the output charset, the function will drop(strip) all characters in the input string that can't be represented by the output charset. Thus, filtering the input string in effect.
Another way in addition to the ones provided here for ES6
module.exports = class TEST{
constructor(size) {
this.map = new MAp();
this.size = size;
}
get(key) {
return this.map.get(key);
}
length() {
return this.map.size;
}
}
and include the same as
var TEST= require('./TEST');
var test = new TEST(1);
I had the same issue. It was related to the Build Settings -> Code Signing Identity -> Release which was set to iOS Developer. If has to be set to iOS Distribution in order for Xcode upload to work.
You can not ask for instance during configuration phase - you can ask only for providers.
var app = angular.module('modx', []);
// configure stuff
app.config(function($routeProvider, $locationProvider) {
// you can inject any provider here
});
// run blocks
app.run(function($rootScope) {
// you can inject any instance here
});
See http://docs.angularjs.org/guide/module for more info.
you can search this file : resetroot.bat
just double click it so that your root accout will be reset and all the privileges are turned into YES
For list of objects you may need something like this:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
import static org.hamcrest.Matchers.is;
@Test
@SuppressWarnings("unchecked")
public void test_returnsList(){
arrange();
List<MyBean> myList = act();
assertThat(myList , contains(allOf(hasProperty("id", is(7L)),
hasProperty("name", is("testName1")),
hasProperty("description", is("testDesc1"))),
allOf(hasProperty("id", is(11L)),
hasProperty("name", is("testName2")),
hasProperty("description", is("testDesc2")))));
}
Use containsInAnyOrder if you do not want to check the order of the objects.
P.S. Any help to avoid the warning that is suppresed will be really appreciated.
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
layout.setLayoutParams(labelLayoutParams);
// If you want to add some controls in this Relative Layout
labelLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
labelLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
ImageView mImage = new ImageView(this);
mImage.setBackgroundResource(R.drawable.popupnew_bg);
layout.addView(mImage,labelLayoutParams);
setContentView(layout);
$items=array();
$j=0;
foreach($group_membership as $i => $username){
$items[$j++]=$username;
}
Just try the above in your code .
WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;
Or you could just slow-click twice on the column in SQL Management Studio and rename it through the UI...
Vlookup
is good if the reference values (column A, sheet 1) are in ascending order. Another option is Index and Match, which can be used no matter the order (As long as the values in column a, sheet 1 are unique)
This is what you would put in column B on sheet 2
=INDEX(Sheet1!A$1:B$6,MATCH(A1,Sheet1!A$1:A$6),2)
Setting Sheet1!A$1:B$6
and Sheet1!A$1:A$6
as named ranges makes it a little more user friendly.
You can use jsdom
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { document } = (new JSDOM(`...`)).window;
or, take a look at cheerio, it may more suitable in your case.
callback from adapter to activity can be done using registering listener in form of interface: Make an interface:
public MyInterface{
public void yourmethod(//incase needs parameters );
}
In Adapter Let's Say MyAdapter:
public MyAdapter extends BaseAdapter{
private MyInterface listener;
MyAdapter(Context context){
try {
this. listener = (( MyInterface ) context);
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement MyInterface");
}
//do this where u need to fire listener l
try {
listener . yourmethod ();
} catch (ClassCastException exception) {
// do something
}
In Activity Implement your method:
MyActivity extends AppCompatActivity implements MyInterface{
yourmethod(){
//do whatever you want
}
}
This function will return the IE major version number as an integer, or undefined
if the browser isn't Internet Explorer. This, like all user agent solutions, is suceptible to user agent spoofing (which has been an official feature of IE since version 8).
function getIEVersion() {
var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:)(\d+)/);
return match ? parseInt(match[1]) : undefined;
}
The important difference is that when passing by const
reference, no new object is created. In the function body, the parameter is effectively an alias for the object passed in.
Because the reference is a const
reference the function body cannot directly change the value of that object. This has a similar property to passing by value where the function body also cannot change the value of the object that was passed in, in this case because the parameter is a copy.
There are crucial differences. If the parameter is a const
reference, but the object passed it was not in fact const
then the value of the object may be changed during the function call itself.
E.g.
int a;
void DoWork(const int &n)
{
a = n * 2; // If n was a reference to a, n will have been doubled
f(); // Might change the value of whatever n refers to
}
int main()
{
DoWork(a);
}
Also if the object passed in was not actually const
then the function could (even if it is ill advised) change its value with a cast.
e.g.
void DoWork(const int &n)
{
const_cast<int&>(n) = 22;
}
This would cause undefined behaviour if the object passed in was actually const
.
When the parameter is passed by const reference, extra costs include dereferencing, worse object locality, fewer opportunities for compile optimizing.
When the parameter is passed by value and extra cost is the need to create a parameter copy. Typically this is only of concern when the object type is large.
There are a number of different options, based on what exactly the effect you're going for is. Chris Coyier did a piece on just this way back when. Worth a read:
if(!strcmp(favoriteDairyProduct, "cheese"))
{
printf("You like cheese too!");
}
else
{
printf("I like cheese more.");
}
This will work for junit. for TestNG use following command
-ea -Dmykey="value" -Dmykey2="value2"
list(newdict)
works in both Python 2 and Python 3, providing a simple list of the keys in newdict
. keys()
isn't necessary. (:
Here's a macro that allows you to shuffle selected cells in a column:
Option Explicit
Sub ShuffleSelectedCells()
'Do nothing if selecting only one cell
If Selection.Cells.Count = 1 Then Exit Sub
'Save selected cells to array
Dim CellData() As Variant
CellData = Selection.Value
'Shuffle the array
ShuffleArrayInPlace CellData
'Output array to spreadsheet
Selection.Value = CellData
End Sub
Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim J As Long, _
N As Long, _
Temp As Variant
'Randomize
For N = LBound(InArray) To UBound(InArray)
J = CLng(((UBound(InArray) - N) * Rnd) + N)
If J <> N Then
Temp = InArray(N, 1)
InArray(N, 1) = InArray(J, 1)
InArray(J, 1) = Temp
End If
Next N
End Sub
You can read the comments to see what the macro is doing. Here's how to install the macro:
Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).
For Laravel 4.2, Unnawut's answer above is the best one. But if you are using table prefix, then you need to alter your code a little.
function up()
{
$table_prefix = DB::getTablePrefix();
DB::statement('ALTER TABLE `' . $table_prefix . 'throttle` MODIFY `user_id` INTEGER UNSIGNED NULL;');
}
And to make sure you can still rollback your migration, we'll do the down()
as well.
function down()
{
$table_prefix = DB::getTablePrefix();
DB::statement('ALTER TABLE `' . $table_prefix . 'throttle` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}
That's not possible using the built-in Array.prototype.map
. However, you could use a simple for
-loop instead, if you do not intend to map
any values:
var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] < 10) {
hasValueLessThanTen = true;
break;
}
}
Or, as suggested by @RobW
, use Array.prototype.some
to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:
var hasValueLessThanTen = myArray.some(function (val) {
return val < 10;
});
Marko's solution works well.
To contrast with recommended Angular way (as shown by treeface's plunkr) is to use a callback expression which does not require defining the expressionHandler. In marko's example change:
In template
<div my-method="theMethodToBeCalled(myParam)"></div>
In directive link function
$(element).click(function( e, rowid ) {
scope.method({myParam: id});
});
This does have one disadvantage compared to marko's solution - on first load theMethodToBeCalled function will be invoked with myParam === undefined.
A working exampe can be found at @treeface Plunker
While git clean
works well, I still find it useful to use my own script to clean the git repo, it has some advantages.
This shows a list of files to be cleaned, then interactively prompts to clean or not. This is nearly always what I want since interactively prompting per file gets tedious.
It also allows manual filtering of the list which comes in handy when there are file types you don't want to clean (and have reason not to commit).
git_clean.sh
#!/bin/bash
readarray -t -d '' FILES < <(
git ls-files -z --other --directory |
grep --null-data --null -v '.bin$\|Cargo.lock$'
)
if [ "$FILES" = "" ]; then
echo "Nothing to clean!"
exit 0
fi
echo "Dirty files:"
printf ' %s\n' "${FILES[@]}"
DO_REMOVE=0
while true; do
echo ""
read -p "Remove ${#FILES[@]} files? [y/n]: " choice
case "$choice" in
y|Y )
DO_REMOVE=1
break ;;
n|N )
echo "Exiting!"
break ;;
* ) echo "Invalid input, expected [Y/y/N/n]"
continue ;;
esac
done
if [ "$DO_REMOVE" -eq 1 ];then
echo "Removing!"
for f in "${FILES[@]}"; do
rm -rfv "$f"
done
fi
Since they are already inline-block
child elements, you can set text-align:center
on the parent without having to set a width
or margin:0px auto
on the child. Meaning it will work for dynamically generated content with varying widths
.
.img_container, .img_container2 {
text-align: center;
}
This will center the child within both div
containers.
UPDATE:
For vertical centering, you can use the calc()
function assuming the height of the icon is known.
.img_container > i, .img_container2 > i {
position:relative;
top: calc(50% - 10px); /* 50% - 3/4 of icon height */
}
jsFiddle demo - it works.
For what it's worth - you can also use vertical-align:middle
assuming display:table-cell
is set on the parent.
In the case of a non blocking socket that has no data available, recv will throw the socket.error exception and the value of the exception will have the errno of either EAGAIN or EWOULDBLOCK. Example:
import sys
import socket
import fcntl, os
import errno
from time import sleep
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK)
while True:
try:
msg = s.recv(4096)
except socket.error, e:
err = e.args[0]
if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
sleep(1)
print 'No data available'
continue
else:
# a "real" error occurred
print e
sys.exit(1)
else:
# got a message, do something :)
The situation is a little different in the case where you've enabled non-blocking behavior via a time out with socket.settimeout(n)
or socket.setblocking(False)
. In this case a socket.error is stil raised, but in the case of a time out, the accompanying value of the exception is always a string set to 'timed out'. So, to handle this case you can do:
import sys
import socket
from time import sleep
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
s.settimeout(2)
while True:
try:
msg = s.recv(4096)
except socket.timeout, e:
err = e.args[0]
# this next if/else is a bit redundant, but illustrates how the
# timeout exception is setup
if err == 'timed out':
sleep(1)
print 'recv timed out, retry later'
continue
else:
print e
sys.exit(1)
except socket.error, e:
# Something else happened, handle error, exit, etc.
print e
sys.exit(1)
else:
if len(msg) == 0:
print 'orderly shutdown on server end'
sys.exit(0)
else:
# got a message do something :)
As indicated in the comments, this is also a more portable solution since it doesn't depend on OS specific functionality to put the socket into non-blockng mode.
See recv(2) and python socket for more details.
This can be more complicated than it looks depending on how you want to count things. For instance, if you have a list of ints, do you want the size of the list containing the references to the ints? (ie. list only, not what is contained in it), or do you want to include the actual data pointed to, in which case you need to deal with duplicate references, and how to prevent double-counting when two objects contain references to the same object.
You may want to take a look at one of the python memory profilers, such as pysizer to see if they meet your needs.
You Can do by Two ways,
1. Cloning the Remote Repo to your Local host
example: git clone https://github.com/user-name/repository.git
2. Pulling the Remote Repo to your Local host
First you have to create a git local repo by,
example: git init or git init repo-name then, git pull https://github.com/user-name/repository.git
That's all, All commits and branch in the remote repo now available in the local repository of your computer.
Happy Coding, cheers -:)
I wasn't happy with any of the answers here, and went looking for a command-line solution.
In macOS Sierra 10.12, Apple introduced a new way for users to remap keys.
If that sounds good to you, take a look at hidutil
.
For example, to remap caps-lock to escape, refer to the key table and find that caps-lock has usage code 0x39 and escape has usage code 0x29. Put these codes or'd with the hex value 0x700000000 in the source and dest like this:
hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x700000029}]}'
You may add other mappings in the same command. Personally, I like to remap caps-lock to backspace, and remap backspace to delete:
hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x70000002A}, {"HIDKeyboardModifierMappingSrc":0x70000002A,"HIDKeyboardModifierMappingDst":0x70000004C}]}'
To see the current mapping:
hidutil property --get "UserKeyMapping"
Your changes will be lost at system reboot. If you want them to persist, configure them in a launch agent. Here's mine:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- Place in ~/Library/LaunchAgents/ -->
<!-- launchctl load com.ldaws.CapslockBackspace.plist -->
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.ldaws.CapslockEsc</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/hidutil</string>
<string>property</string>
<string>--set</string>
<string>{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x70000002A},{"HIDKeyboardModifierMappingSrc":0x70000002A,"HIDKeyboardModifierMappingDst":0x70000004C}]}</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
I've placed this content into a file located at ~/Library/LaunchAgents/com.ldaws.CapslockBackspace.plist
and then executed:
launchctl load com.ldaws.CapslockBackspace.plist
Set is the good approach here, because it orders the variables, what seems to be your goal here. {z,y,x}
is {0,1,3}
whatever the order of the parameters.
>>> ["cdef"[i] for i in {z,x,y}]
['c', 'd', 'f']
This way, the whole solution is O(n).
No, no, NO!
In single threated tasks you don't need to use Iterator, moreover, CopyOnWriteArrayList (due to performance hit).
Solution is much simpler: try to use canonical for loop instead of for-each loop.
According to Java copyright owners (some years ago Sun, now Oracle) for-each loop guide, it uses iterator to walk through collection and just hides it to make code looks better. But, unfortunately as we can see, it produced more problems than profits, otherwise this topic would not arise.
For example, this code will lead to java.util.ConcurrentModificationException when entering next iteration on modified ArrayList:
// process collection
for (SomeClass currElement: testList) {
SomeClass founDuplicate = findDuplicates(currElement);
if (founDuplicate != null) {
uniqueTestList.add(founDuplicate);
testList.remove(testList.indexOf(currElement));
}
}
But following code works just fine:
// process collection
for (int i = 0; i < testList.size(); i++) {
SomeClass currElement = testList.get(i);
SomeClass founDuplicate = findDuplicates(currElement);
if (founDuplicate != null) {
uniqueTestList.add(founDuplicate);
testList.remove(testList.indexOf(currElement));
i--; //to avoid skipping of shifted element
}
}
So, try to use indexing approach for iterating over collections and avoid for-each loop, as they are not equivalent! For-each loop uses some internal iterators, which check collection modification and throw ConcurrentModificationException exception. To confirm this, take a closer look at the printed stack trace when using first example that I've posted:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at TestFail.main(TestFail.java:43)
For multithreading use corresponding multitask approaches (like synchronized keyword).
Per Mozilla's Map documentation, you can initialize as follows:
private _gridOptions:Map<string, Array<string>> =
new Map([
["1", ["test"]],
["2", ["test2"]]
]);
Port 465: IANA has reassigned a new service to this port, and it should no longer be used for SMTP communications.
However, because it was once recognized by IANA as valid, there may be legacy systems that are only capable of using this connection method. Typically, you will use this port only if your application demands it. A quick Google search, and you'll find many consumer ISP articles that suggest port 465 as the recommended setup. Hopefully this ends soon! It is not RFC compliant.
Port 587: This is the default mail submission port. When a mail client or server is submitting an email to be routed by a proper mail server, it should always use this port.
Everyone should consider using this port as default, unless you're explicitly blocked by your upstream network or hosting provider. This port, coupled with TLS encryption, will ensure that email is submitted securely and following the guidelines set out by the IETF.
Port 25: This port continues to be used primarily for SMTP relaying. SMTP relaying is the transmittal of email from email server to email server.
In most cases, modern SMTP clients (Outlook, Mail, Thunderbird, etc) shouldn't use this port. It is traditionally blocked, by residential ISPs and Cloud Hosting Providers, to curb the amount of spam that is relayed from compromised computers or servers. Unless you're specifically managing a mail server, you should have no traffic traversing this port on your computer or server.
This is a fast solution with a temporary object.
var records = [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }],_x000D_
empid = [1, 4, 5],_x000D_
object = {},_x000D_
result;_x000D_
_x000D_
records.forEach(function (a) {_x000D_
object[a.empid] = a;_x000D_
});_x000D_
_x000D_
result = empid.map(function (a) {_x000D_
return object[a];_x000D_
});_x000D_
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
_x000D_
The problem comes from your Java application (or a library you are using).
First, you should read the entire outputs (Google for StreamGobbler), and pronto!
Javadoc says:
The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
Secondly, waitFor()
your process to terminate.
You then should close the input, output and error streams.
Finally destroy()
your Process.
My sources:
var res = (from element in list)
.OrderBy(x => x.F2).AsEnumerable()
.GroupBy(x => x.F1)
.Select()
Use .AsEnumerable() after OrderBy()
believe there should be a way in accessing file system.
Include node.d.ts
using npm i @types/node
. And then create a new tsconfig.json
file (npx tsc --init
) and create a .ts
file as followed:
import fs from 'fs';
fs.readFileSync('foo.txt','utf8');
You can use other functions in fs
as well : https://nodejs.org/api/fs.html
Node quick start : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html
If you have a very limited number of levels, you could try converting y
into factor and change its levels.
> xy <- data.frame(x = c(1, 2, 4), y = c(1, 4, 5))
> xy$w <- as.factor(xy$y)
> levels(xy$w) <- c("good", "fair", "bad")
> xy
x y w
1 1 1 good
2 2 4 fair
3 4 5 bad
For Windows Server® 2008, Windows 7, Windows Server 2003, Windows Vista®, or Windows XP run "control userpasswords2"
Click the Start button, then click Run (Windows XP, Server 2003 or below)
Type control userpasswords2 and press Enter on your keyboard.
Note: For Windows 7 and Windows Vista, this command will not run by typing it in the Serach box on the Start Menu - it must be run using the Run option. To add the Run command to your Start menu, right-click on it and choose the option to customize it, then go to the Advanced options. Check to option to add the Run command.
You will see a window of user details!
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
mysqli_error
function requires $myConnection
as parameters, that's why you get the warning
You will not have access to your real sd card in emulator. You will have to follow the steps in this tutorial to direct your emulator to a directory on your development environment acting as your SD card.
From this answer:
[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
var content = request.Content;
string jsonContent = content.ReadAsStringAsync().Result;
}
Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.
transform: scale();
will make original element preserve its size.
I found the best option is to use vw
.
It's working like a charm:
https://jsfiddle.net/tomekmularczyk/6ebv9Lxw/1/
#div1,_x000D_
#div2,_x000D_
#div3 {_x000D_
background:url('//www.google.pl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png') no-repeat;_x000D_
background-size: 50vw; _x000D_
border: 1px solid black;_x000D_
margin-bottom: 40px;_x000D_
}_x000D_
_x000D_
#div1 {_x000D_
background-position: 0 0;_x000D_
width: 12.5vw;_x000D_
height: 13vw;_x000D_
}_x000D_
#div2 {_x000D_
background-position: -13vw -4vw;_x000D_
width: 17.5vw;_x000D_
height: 9vw;_x000D_
transform: scale(1.8);_x000D_
}_x000D_
#div3 {_x000D_
background-position: -30.5vw 0;_x000D_
width: 19.5vw;_x000D_
height: 17vw;_x000D_
}
_x000D_
<div id="div1">_x000D_
</div>_x000D_
<div id="div2">_x000D_
</div>_x000D_
<div id="div3">_x000D_
</div>
_x000D_
For SwiftUI, try
TextField ("Email", text: $email)
.textFieldStyle(RoundedBorderTextFieldStyle()).padding()
SecureField ("Password", text: $password)
.textFieldStyle(RoundedBorderTextFieldStyle()).padding()
This error message can also be caused by SELinux. Check if SELinux is enabled with getenforce
You need to adjust SELinux to use your port and restart.
I.E.
semanage port -a -t http_port_t -p tcp 9080 2>/dev/null || semanage port -m -t http_port_t -p tcp 9080
Java 8 Native Type
List<Integer> example;
example.add(1);
example.add(2);
example.add(3);
...
example.stream().collect(Collectors.joining(","));
Java 8 Custom Object:
List<Person> person;
...
person.stream().map(Person::getAge).collect(Collectors.joining(","));
your form is missing the method...
<form name="registrationform" action="register.php" method="post"> //here
anywyas to check the posted data u can use isset()..
Determine if a variable is set and is not NULL
if(!isset($firstname) || trim($firstname) == '')
{
echo "You did not fill out the required fields.";
}
After spending a lot of time with this issue, Here is what I got working
$state.go('stateName',params,{
// prevent the events onStart and onSuccess from firing
notify:false,
// prevent reload of the current state
reload:false,
// replace the last record when changing the params so you don't hit the back button and get old params
location:'replace',
// inherit the current params on the url
inherit:true
});
I know this is an old question but according what @mikejones1477 said, modern front end libraries and frameworks escape the text giving you protection against XSS. The reason why cookies are not a secure method using credentials is that cookies doesn't prevent CSRF when localStorage does (also remember that cookies are accessible by javascript too, so XSS isn't the big problem here), this answer resume why.
The reason storing an authentication token in local storage and manually adding it to each request protects against CSRF is that key word: manual. Since the browser is not automatically sending that auth token, if I visit evil.com and it manages to send a POST http://example.com/delete-my-account, it will not be able to send my authn token, so the request is ignored.
Of course httpOnly is the holy grail but you can't access from reactjs or any js framework beside you still have CSRF vulnerability. My recommendation would be localstorage or if you want to use cookies make sure implemeting some solution to your CSRF problem like django does.
Regarding with the CDN's make sure you're not using some weird CDN, for example CDN like google or bootstrap provide, are maintained by the community and doesn't contain malicious code, if you are not sure, you're free to review.
Unless you want to go the VBA route to work out the Tab name, the Excel formula is fairly ugly based upon Mid functions, etc. But both these methods can be found here if you want to go that way.
Rather, the way I would do it is:
1) Make one cell on your sheet named, for example, Reference_Sheet
and put in that cell the value "Jan Item" for example.
2) Now, use the Indirect
function like:
=INDIRECT(Reference_Sheet&"!J3")
3) Now, for each month's sheet, you just have to change that one Reference_Sheet
cell.
Hope this gives you what you're looking for!
select person, language
from table A
group by person, language
will return unique rows
Key insights for me were: - ensure that label content comes after the input-radio field - I tweaked my css to make everything a little closer
.radio-inline+.radio-inline {
margin-left: 5px;
}
If I understand what you need, try this:
SELECT id, pass, AVG(val) AS val_1
FROM data_r1
GROUP BY id, pass;
Or, if you want just one row for every id, this:
SELECT d1.id,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 1) as val_1,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 2) as val_2,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 3) as val_3,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 4) as val_4,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 5) as val_5,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 6) as val_6,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id
Give this a try...
server {
listen 80;
server_name dev.int.com;
access_log off;
location / {
proxy_pass http://IP:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:8080/jira /;
proxy_connect_timeout 300;
}
location ~ ^/stash {
proxy_pass http://IP:7990;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:7990/ /stash;
proxy_connect_timeout 300;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/nginx/html;
}
}
Correct way shall be to autowire AbstractManager, as Max suggested, but this should work fine as well.
@Autowired
@Qualifier(value="mailService")
public MailManager mailManager;
and
@Component("mailService")
@Transactional
public class MailManager extends AbstractManager {
}
NO, you can't do it other way than so.
Two ways out of possible solutions to achieve this are:
1. Create a .htaccess
file in root folder as under (just replace example.com and my_dir with your corresponding values):
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/my_dir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /my_dir/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ my_dir/index.php [L]
</IfModule>
Use RedirectMatch to only redirect the root URL “/” to another folder or URL,
RedirectMatch ^/$ http://www.example.com/my_dir
Do you want an incrementing integer column returned with your recordset? If so: -
--Check for existance
if exists (select * from dbo.sysobjects where [id] = object_id(N'dbo.t') AND objectproperty(id, N'IsUserTable') = 1)
drop table dbo.t
go
--create dummy table and insert data
create table dbo.t(x char(1) not null primary key, y char(1) not null)
go
set nocount on
insert dbo.t (x,y) values ('A','B')
insert dbo.t (x,y) values ('C','D')
insert dbo.t (x,y) values ('E','F')
--create temp table to add an identity column
create table dbo.#TempWithIdentity(i int not null identity(1,1) primary key,x char(1) not null unique,y char(1) not null)
--populate the temporary table
insert into dbo.#TempWithIdentity(x,y) select x,y from dbo.t
--return the data
select i,x,y from dbo.#TempWithIdentity
--clean up
drop table dbo.#TempWithIdentity
\includegraphics<1>{A}%
\includegraphics<2>{B}%
\includegraphics<3>{C}%
The % is important. This will keep all the images fixed.
SELECT DATENAME(dw,GETDATE()) -- Friday
SELECT DATEPART(dw,GETDATE()) -- 6
\b
matches at word boundaries (without actually matching any characters), so the following should do what you want:
\bstackoverflow\b
In case anyone is running in a Spring Boot app, and you want to read the response body of a RestTemplate
(which is why I want to read a stream twice), there is a clean(er) way of doing this.
First of all, you need to use Spring's StreamUtils
to copy the stream to a String:
String text = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()))
But that's not all. You also need to use a request factory that can buffer the stream for you, like so:
ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
RestTemplate restTemplate = new RestTemplate(factory);
Or, if you're using the factory bean, then (this is Kotlin but nevertheless):
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun createRestTemplate(): RestTemplate = RestTemplateBuilder()
.requestFactory { BufferingClientHttpRequestFactory(SimpleClientHttpRequestFactory()) }
.additionalInterceptors(loggingInterceptor)
.build()
A recursive solution in python. The good thing about this code is that it exports a dictionary, with keys as strings and all possible permutations as values. All possible string lengths are included, so in effect, you are creating a superset.
If you only require the final permutations, you can delete other keys from the dictionary.
In this code, the dictionary of permutations is global.
At the base case, I store the value as both possibilities in a list. perms['ab'] = ['ab','ba']
.
For higher string lengths, the function refers to lower string lengths and incorporates the previously calculated permutations.
The function does two things:
Expensive for memory.
perms = {}
def perm(input_string):
global perms
if input_string in perms:
return perms[input_string] # This will send a list of all permutations
elif len(input_string) == 2:
perms[input_string] = [input_string, input_string[-1] + input_string [-2]]
return perms[input_string]
else:
perms[input_string] = []
for index in range(0, len(input_string)):
new_string = input_string[0:index] + input_string[index +1:]
perm(new_string)
for entries in perms[new_string]:
perms[input_string].append(input_string[index] + entries)
return perms[input_string]
As @martin and this answer explained, it is complicated. There is no bullet-proof way of getting the client's ip address.
The best that you can do is to try to parse "X-Forwarded-For"
and rely on request.getRemoteAddr();
public static String getClientIpAddress(HttpServletRequest request) {
String xForwardedForHeader = request.getHeader("X-Forwarded-For");
if (xForwardedForHeader == null) {
return request.getRemoteAddr();
} else {
// As of https://en.wikipedia.org/wiki/X-Forwarded-For
// The general format of the field is: X-Forwarded-For: client, proxy1, proxy2 ...
// we only want the client
return new StringTokenizer(xForwardedForHeader, ",").nextToken().trim();
}
}
I wanted to encrypt and decrypt the string as a readable string.
Here is a very simple quick example in C# Visual Studio 2019 WinForms based on the answer from @Pradip
.
Right click project > properties > settings > Create a username
and password
setting.
Now you can leverage those settings you just created. Here I save the username
and password
but only encrypt the password
in it's respectable value field in the user.config
file.
Example of the encrypted string in the user.config
file.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<userSettings>
<secure_password_store.Properties.Settings>
<setting name="username" serializeAs="String">
<value>admin</value>
</setting>
<setting name="password" serializeAs="String">
<value>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAQpgaPYIUq064U3o6xXkQOQAAAAACAAAAAAAQZgAAAAEAACAAAABlQQ8OcONYBr9qUhH7NeKF8bZB6uCJa5uKhk97NdH93AAAAAAOgAAAAAIAACAAAAC7yQicDYV5DiNp0fHXVEDZ7IhOXOrsRUbcY0ziYYTlKSAAAACVDQ+ICHWooDDaUywJeUOV9sRg5c8q6/vizdq8WtPVbkAAAADciZskoSw3g6N9EpX/8FOv+FeExZFxsm03i8vYdDHUVmJvX33K03rqiYF2qzpYCaldQnRxFH9wH2ZEHeSRPeiG</value>
</setting>
</secure_password_store.Properties.Settings>
</userSettings>
</configuration>
Full Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace secure_password_store
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Exit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Login_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
Properties.Settings.Default.username = textBox1.Text;
Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
Properties.Settings.Default.Save();
}
else if (checkBox1.Checked == false)
{
Properties.Settings.Default.username = "";
Properties.Settings.Default.password = "";
Properties.Settings.Default.Save();
}
MessageBox.Show("{\"data\": \"some data\"}","Login Message Alert",MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void DecryptString_Click(object sender, EventArgs e)
{
SecureString password = DecryptString(Properties.Settings.Default.password);
string readable = ToInsecureString(password);
textBox4.AppendText(readable + Environment.NewLine);
}
private void Form_Load(object sender, EventArgs e)
{
//textBox1.Text = "UserName";
//textBox2.Text = "Password";
if (Properties.Settings.Default.username != string.Empty)
{
textBox1.Text = Properties.Settings.Default.username;
checkBox1.Checked = true;
SecureString password = DecryptString(Properties.Settings.Default.password);
string readable = ToInsecureString(password);
textBox2.Text = readable;
}
groupBox1.Select();
}
static byte[] entropy = Encoding.Unicode.GetBytes("SaLtY bOy 6970 ePiC");
public static string EncryptString(SecureString input)
{
byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(ToInsecureString(input)),entropy,DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedData);
}
public static SecureString DecryptString(string encryptedData)
{
try
{
byte[] decryptedData = ProtectedData.Unprotect(Convert.FromBase64String(encryptedData),entropy,DataProtectionScope.CurrentUser);
return ToSecureString(Encoding.Unicode.GetString(decryptedData));
}
catch
{
return new SecureString();
}
}
public static SecureString ToSecureString(string input)
{
SecureString secure = new SecureString();
foreach (char c in input)
{
secure.AppendChar(c);
}
secure.MakeReadOnly();
return secure;
}
public static string ToInsecureString(SecureString input)
{
string returnValue = string.Empty;
IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
try
{
returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
}
finally
{
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
}
return returnValue;
}
private void EncryptString_Click(object sender, EventArgs e)
{
Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
textBox3.AppendText(Properties.Settings.Default.password.ToString() + Environment.NewLine);
}
}
}
You can try this:
select Regexp_Replace('single spaces only','( ){2,}', ' ') from dual;
The two above it is not run.
The table edit button:
<a data-toggle="modal" type="edit" id="{{$b->id}}" data-id="{{$b->id}}" data-target="#form_edit_masterbank" data-bank_nama="{{ $b->bank_nama }}" data-bank_accnama="{{ $b->bank_accnama }}" data-bank_accnum="{{ $b->bank_accnum }}" data-active="{{ $b->active }}" data-logobank="{{asset('components/images/user/masterbank/')}}/{{$b->images}}" href="#" class="edit edit-masterbank" ><i class="fa fa-edit" ></i></a>
and then in JavaScript:
$('.imagepreview555').attr('src', logobank);
and then in HTML:
<img src="" class="imagepreview555" style="width: 100%;" />
Not it runs.
I think this guide explains it pretty well https://github.com/yannickcr/eslint-plugin-react/issues/678
class Field extends Component {
const { inputRef } = this.props;
render() {
return (
<input type="text" ref={inputRef} />
)
}
}
class MyComponent extends Component {
componentDidMount() {
this.inputNode.focus();
}
render() {
return (
<div>
Hello, <Field inputRef={node => this.inputNode = node} />
</div>
)
}
}
On modern computer systems, localhost as a hostname translates to an IPv4 address in the 127.0.0.0/8 (loopback) net block, usually 127.0.0.1, or ::1 in IPv6.
The only difference is that it would be looking up in the DNS for the system what localhost
resolves to. This lookup is really, really quick. For instance, to get to stackoverflow.com
you typed in that to the address bar (or used a bookmarklet that pointed here). Either way, you got here through a hostname. localhost
provides a similar functionality.
public static final String YOUR_STRING_CONSTANT = "";
open your Redis cli and There two possible option that you could use:
FLUSHDB - Delete all the keys of the currently selected DB. FLUSHALL - Delete all the keys of all the existing databases, not just the currently selected one.
INSERT INTO ... ON DUPLICATE KEY UPDATE will only work for MYSQL, not for SQL Server.
for SQL server, the way to work around this is to first declare a temp table, insert value to that temp table, and then use MERGE
Like this:
declare @Source table
(
name varchar(30),
age decimal(23,0)
)
insert into @Source VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29);
MERGE beautiful AS Tg
using @source as Sc
on tg.namet=sc.name
when matched then update
set tg.age=sc.age
when not matched then
insert (name, age) VALUES
(SC.name, sc.age);
put:
If I want to update my first
name, then I send a put request:
{ "first": "Nazmul", "last": "hasan" }
But here is a problem with using put
request: When I want to send put
request I have to send all two parameters that is first
and last
(whereas I only need to update first
) so it is mandatory to send them all again with put
request.
patch:
patch
request, on the other hand, says: only specify the data
which you need to update
and it won't be affecting or changing other data.
So no need to send all values again. Do I only need to change first
name? Well, It only suffices to specify first
in patch
request.
Here you go: Working Fidddle
$(function(){
var dateFormat = 'DD-MM-YYYY';
alert(moment(moment("2012-10-19").format(dateFormat),dateFormat,true).isValid());
});
The following methods actually work.
if you wish - using a theme
By default a buttons color is android:colorAccent
. So, if you create a style like this...
<style name="Button.White" parent="ThemeOverlay.AppCompat">
<item name="colorAccent">@android:color/white</item>
</style>
You can use it like this...
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/Button.White"
/>
alternatively - using a tint
You can simply add android:backgroundTint
for API Level 21 and higher, or app:backgroundTint
for API Level 7 and higher.
For more information, see this blog.
If you replace the background with a color you will loose the effect of the button, and the color will be applied to the entire area of the button. It will not respect the padding, shadow, and corner radius.
Usually, if the command is an external program, you can use the OS to help you here.
command > file_output.txt
So your C code would be doing something like
exec("command > file_output.txt");
Then you can use the file_output.txt file.
Currently it only works for the .dropdown-menu
:
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
If you want it for other use, in your own css, following the bootstrap.css create another one:
.divider {
height: 1px;
width:100%;
display:block; /* for use on default inline elements like span */
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
As listed on the other answers, there are many reasons you can find to avoid this. It all boils down to one reason that makes the rest moot. The System()
function is inherently insecure/untrusted, and should not be introduced into a program unless necessary.
For a student assignment, this condition was never met, and for this reason I would fail an assignment without even running the program if a call to this method was present. (This was made clear from the start.)
Simply use the below code for the fragment.
@Override
public void onOtherButtonClick(ActionSheet actionSheet, int index) {
if (index == 1)
{
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 1) {
if (requestCode == 1) {
Uri selectedImageUri = data.getData();
//selectedImagePath = getPath(selectedImageUri);
}
}
}
onActivityResult will call without calling its parent.
The error also happens when trying to use the
with multiprocessing.Pool() as pool:
# ...
with a Python version that is too old (like Python 2.X) and does not support using with
together with multiprocessing pools.
(See this answer https://stackoverflow.com/a/25968716/1426569 to another question for more details)
Use this:
echo "${@:2}"
The following syntax:
echo "${*:2}"
would work as well, but is not recommended, because as @Gordon already explained, that using *
, it runs all of the arguments together as a single argument with spaces, while @
preserves the breaks between them (even if some of the arguments themselves contain spaces). It doesn't make the difference with echo
, but it matters for many other commands.
let restaurant = restaurants.find(element => element.restaurant.food == "chicken");
The find() method returns the value of the first element in the provided array that satisfies the provided testing function.
in: https://developer.mozilla.org/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Array/find
It's not possible to create a many-to-many relationship with a customized join table. In a many-to-many relationship EF manages the join table internally and hidden. It's a table without an Entity class in your model. To work with such a join table with additional properties you will have to create actually two one-to-many relationships. It could look like this:
public class Member
{
public int MemberID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<MemberComment> MemberComments { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public string Message { get; set; }
public virtual ICollection<MemberComment> MemberComments { get; set; }
}
public class MemberComment
{
[Key, Column(Order = 0)]
public int MemberID { get; set; }
[Key, Column(Order = 1)]
public int CommentID { get; set; }
public virtual Member Member { get; set; }
public virtual Comment Comment { get; set; }
public int Something { get; set; }
public string SomethingElse { get; set; }
}
If you now want to find all comments of members with LastName
= "Smith" for example you can write a query like this:
var commentsOfMembers = context.Members
.Where(m => m.LastName == "Smith")
.SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
.ToList();
... or ...
var commentsOfMembers = context.MemberComments
.Where(mc => mc.Member.LastName == "Smith")
.Select(mc => mc.Comment)
.ToList();
Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:
var membersWithComments = context.Members
.Where(m => m.LastName == "Smith")
.Select(m => new
{
Member = m,
Comments = m.MemberComments.Select(mc => mc.Comment)
})
.ToList();
If you want to find all comments of a member with MemberId
= 1:
var commentsOfMember = context.MemberComments
.Where(mc => mc.MemberId == 1)
.Select(mc => mc.Comment)
.ToList();
Now you can also filter by the properties in your join table (which would not be possible in a many-to-many relationship), for example: Filter all comments of member 1 which have a 99 in property Something
:
var filteredCommentsOfMember = context.MemberComments
.Where(mc => mc.MemberId == 1 && mc.Something == 99)
.Select(mc => mc.Comment)
.ToList();
Because of lazy loading things might become easier. If you have a loaded Member
you should be able to get the comments without an explicit query:
var commentsOfMember = member.MemberComments.Select(mc => mc.Comment);
I guess that lazy loading will fetch the comments automatically behind the scenes.
Edit
Just for fun a few examples more how to add entities and relationships and how to delete them in this model:
1) Create one member and two comments of this member:
var member1 = new Member { FirstName = "Pete" };
var comment1 = new Comment { Message = "Good morning!" };
var comment2 = new Comment { Message = "Good evening!" };
var memberComment1 = new MemberComment { Member = member1, Comment = comment1,
Something = 101 };
var memberComment2 = new MemberComment { Member = member1, Comment = comment2,
Something = 102 };
context.MemberComments.Add(memberComment1); // will also add member1 and comment1
context.MemberComments.Add(memberComment2); // will also add comment2
context.SaveChanges();
2) Add a third comment of member1:
var member1 = context.Members.Where(m => m.FirstName == "Pete")
.SingleOrDefault();
if (member1 != null)
{
var comment3 = new Comment { Message = "Good night!" };
var memberComment3 = new MemberComment { Member = member1,
Comment = comment3,
Something = 103 };
context.MemberComments.Add(memberComment3); // will also add comment3
context.SaveChanges();
}
3) Create new member and relate it to the existing comment2:
var comment2 = context.Comments.Where(c => c.Message == "Good evening!")
.SingleOrDefault();
if (comment2 != null)
{
var member2 = new Member { FirstName = "Paul" };
var memberComment4 = new MemberComment { Member = member2,
Comment = comment2,
Something = 201 };
context.MemberComments.Add(memberComment4);
context.SaveChanges();
}
4) Create relationship between existing member2 and comment3:
var member2 = context.Members.Where(m => m.FirstName == "Paul")
.SingleOrDefault();
var comment3 = context.Comments.Where(c => c.Message == "Good night!")
.SingleOrDefault();
if (member2 != null && comment3 != null)
{
var memberComment5 = new MemberComment { Member = member2,
Comment = comment3,
Something = 202 };
context.MemberComments.Add(memberComment5);
context.SaveChanges();
}
5) Delete this relationship again:
var memberComment5 = context.MemberComments
.Where(mc => mc.Member.FirstName == "Paul"
&& mc.Comment.Message == "Good night!")
.SingleOrDefault();
if (memberComment5 != null)
{
context.MemberComments.Remove(memberComment5);
context.SaveChanges();
}
6) Delete member1 and all its relationships to the comments:
var member1 = context.Members.Where(m => m.FirstName == "Pete")
.SingleOrDefault();
if (member1 != null)
{
context.Members.Remove(member1);
context.SaveChanges();
}
This deletes the relationships in MemberComments
too because the one-to-many relationships between Member
and MemberComments
and between Comment
and MemberComments
are setup with cascading delete by convention. And this is the case because MemberId
and CommentId
in MemberComment
are detected as foreign key properties for the Member
and Comment
navigation properties and since the FK properties are of type non-nullable int
the relationship is required which finally causes the cascading-delete-setup. Makes sense in this model, I think.
You could break by RETURN
. For example
def a = [1, 2, 3, 4, 5, 6, 7]
def ret = 0
a.each {def n ->
if (n > 5) {
ret = n
return ret
}
}
It works for me!
JQuery has an inbuilt json data type for Ajax and converts the data into a object. PHP% also has inbuilt json_encode function which converts an array into json formatted string. Saves a lot of parsing, decoding effort.
Use the readlink utility from the coreutils package.
MY_PATH=$(readlink -f "$0")
In case of adding new rows for array in loop, Assign the array directly for firsttime in loop instead of initialising an empty array.
for i in range(0,len(0,100)):
SOMECALCULATEDARRAY = .......
if(i==0):
finalArrayCollection = SOMECALCULATEDARRAY
else:
finalArrayCollection = np.vstack(finalArrayCollection,SOMECALCULATEDARRAY)
This is mainly useful when the shape of the array is unknown
The way I like, is if you have a date object you can subtract another date object from it to get the difference. Date objects are based on milliseconds from a certain date.
var date1 = new Date(2015, 02, 18); // "18/03/2015", month is 0-index
var date2 = new Date(2015, 02, 20); // "20/03/2015"
var msDiff = date2 - date1; // 172800000, this is time in milliseconds
var daysDiff = msDiff / 1000 / 60 / 60 / 24; // 2 days
So this is how you subtract dates. Now if you want to add them? date1 + date2 gives an error.. But if I want to get the time in ms I can use:
var dateMs = date1 - 0;
// say I want to add 5 days I can use
var days = 5;
var msToAdd = days * 24 * 60 * 60 * 1000;
var newDate = new Date(dateMs + msToAdd);
By subtracting 0 you turn the date object into the milliseconds format.
M.Ali's answer could be modified as
select Cast(Cast((37.0/38.0)*100 as decimal(18,2)) as varchar(5)) + ' %' as Percentage
I have created a JSFiddle with my bindHTML knockout binding handler here: https://jsfiddle.net/glaivier/9859uq8t/
First, save the binding handler into its own (or a common) file and include after Knockout.
If you use this switch your bindings to this:
<div data-bind="bindHTML: htmlValue"></div>
OR
<!-- ko bindHTML: htmlValue --><!-- /ko -->
There isn't any magic to it. Boolean expressions like a || b || c || d
are lazily evaluated. Interpeter looks for the value of a
, it's undefined so it's false so it moves on, then it sees b
which is null, which still gives false result so it moves on, then it sees c
- same story. Finally it sees d
and says 'huh, it's not null, so I have my result' and it assigns it to the final variable.
This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).
Better late than never!
https://getbootstrap.com/docs/4.5/layout/grid/
<div class="container">
<div class="row">
<div class="col-sm">
One of three columns
</div>
<div class="col-sm">
One of three columns
</div>
<div class="col-sm">
One of three columns
</div>
</div>
</div>
I don't think you can use braces.
According to the Bash manual about case in Conditional Constructs.
Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.
Nothing about Brace Expansion unfortunately.
So you'd have to do something like this:
case $1 in
req*)
...
;;
met*|meet*)
...
;;
*)
# You should have a default one too.
esac
ng-model-options in AngularJS 1.3 (beta as of this writing) is documented to support {updateOn: 'blur'}. For earlier versions, something like the following worked for me:
myApp.directive('myForm', function() {
return {
require: 'form',
link: function(scope, element, attrs, formController) {
scope.validate = function(name) {
formController[name].isInvalid
= formController[name].$invalid;
};
}
};
});
With a template like this:
<form name="myForm" novalidate="novalidate" data-my-form="">
<input type="email" name="eMail" required="required" ng-blur="validate('eMail')" />
<span ng-show="myForm.eMail.isInvalid">Please enter a valid e-mail address.</span>
<button type="submit">Submit Form</button>
</form>
You can achieve this by "interpolating" the className passed from the parent component to the child component using this.props.className
. Example below:
export default class ParentComponent extends React.Component {
render(){
return <ChildComponent className="your-modifier-class" />
}
}
export default class ChildComponent extends React.Component {
render(){
return <div className={"original-class " + this.props.className}></div>
}
}
I'm currently experimenting with canvas and pixels... I'm finding this logic works out for me better.
add to offset the 'tint' value
var grey = (r + g + b) / 3;
var grey2 = (new_r + new_g + new_b) / 3;
var dr = grey - grey2 * 1;
var dg = grey - grey2 * 1
var db = grey - grey2 * 1;
tint_r = new_r + dr;
tint_g = new_g + dg;
tint_b = new_b _ db;
or something like that...
Assignment in javascript works from right to left. var var1 = var2 = var3 = 1;
.
If the value of any of these variables is 1
after this statement, then logically it must have started from the right, otherwise the value or var1
and var2
would be undefined.
You can think of it as equivalent to var var1 = (var2 = (var3 = 1));
where the inner-most set of parenthesis is evaluated first.
You can cast like this:
return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);
Or like this if you want to be compatible with tsx mode:
return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);
Just remember that this is a compile-time cast, and not a runtime cast.
Change /etc/mysql/my.cnf
:
bind-address = 127.0.0.1 to 0.0.0.0
Create user with '%' host
and restart:
/etc/init.d/mysql restart
Works for me! :)
For showing result of batch file in text file, you can use
this command
chdir > test.txt
This command will redirect result to test.txt.
When you open test.txt you will found current path of directory in test.txt
select t3.name, sum(t3.prod_A) as Prod_A, sum(t3.prod_B) as Prod_B, sum(t3.prod_C) as Prod_C, sum(t3.prod_D) as Prod_D, sum(t3.prod_E) as Prod_E
from
(select t2.name as name,
case when t2.prodid = 1 then t2.counts
else 0 end prod_A,
case when t2.prodid = 2 then t2.counts
else 0 end prod_B,
case when t2.prodid = 3 then t2.counts
else 0 end prod_C,
case when t2.prodid = 4 then t2.counts
else 0 end prod_D,
case when t2.prodid = "5" then t2.counts
else 0 end prod_E
from
(SELECT partners.name as name, sales.products_id as prodid, count(products.name) as counts
FROM test.sales left outer join test.partners on sales.partners_id = partners.id
left outer join test.products on sales.products_id = products.id
where sales.partners_id = partners.id and sales.products_id = products.id group by partners.name, prodid) t2) t3
group by t3.name ;
Add condition in Click event to restrict the clickable area .
$('#thing').click(function(e) {
if (e.clientX > $(this).offset().left + 90 &&
e.clientY < $(this).offset().top + 10) {
// action when clicking on after-element
// your code here
}
});
In Symfony 2.6 and older versions, to get a parameter in a controller - you should get the container first, and then - the needed parameter.
$this->container->getParameter('api_user');
This documentation chapter explains it.
While $this->get()
method in a controller will load a service (doc)
In Symfony 2.7 and newer versions, to get a parameter in a controller you can use the following:
$this->getParameter('api_user');
For me, this one works well (thanks to the last comments for pointing out the directory /var/lib/docker/):
chroot /var/lib/docker/containers/2465790aa2c4*/root/
Here, 2465790aa2c4 is the short ID of the running container (as displayed by docker ps), followed by a star.
using LINQ and Lamba, i wanted to return two field values and assign it to single entity object field;
as Name = Fname + " " + LName;
See my below code which is working as expected; hope this is useful;
Myentity objMyEntity = new Myentity
{
id = obj.Id,
Name = contxt.Vendors.Where(v => v.PQS_ID == obj.Id).Select(v=> new { contact = v.Fname + " " + v.LName}).Single().contact
}
no need to declare the 'contact'
Have a look at mongoose:
This will work with "org.bouncycastle.util.encoders.Hex" following package
return new String(Hex.encode(digest));
Its in bouncycastle jar.
The most important thing is, the action created must return partial view, see below.
public ActionResult _YourPartialViewSection()
{
return PartialView();
}
Change your code:
a.image_container img {
width: 100%;
}
To this:
a.image_container img {
width: auto; // to maintain aspect ratio. You can use 100% if you don't care about that
height: 100%;
}
If you want to display an icon and are using a dark theme. Which means the icon provided above doesn't look that great. Then you can find the icon here
C:\Program Files\Git\mingw64\share\git\git-for-windows
I copied it into.
%LOCALAPPDATA%\packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState
and named it git-bash_32px
as suggested above.
Control the opacity with CTRL + SHIFT + scrolling.
{
"acrylicOpacity" : 0.75,
"closeOnExit" : true,
"colorScheme" : "Campbell",
"commandline" : "\"%PROGRAMFILES%\\git\\usr\\bin\\bash.exe\" -i -l",
"cursorColor" : "#FFFFFF",
"cursorShape" : "bar",
"fontFace" : "Consolas",
"fontSize" : 10,
"guid" : "{73225108-7633-47ae-80c1-5d00111ef646}",
"historySize" : 9001,
"icon" : "ms-appdata:///roaming/git-bash_32px.ico",
"name" : "Bash",
"padding" : "0, 0, 0, 0",
"snapOnInput" : true,
"startingDirectory" : "%USERPROFILE%",
"useAcrylic" : true
},
Try this:
<html>
<table>
<tr>
<td style="padding-left: 5px;
padding-bottom: 3px;">
<strong style="font-size: 35px;">Datum:</strong><br />
November 2010
</td>
</tr>
</table>
</html>
Notice that I also included the table-tag, which you seem to have forgotten. This has to be included if you want this to appear as a table.
Let's consider I want specific implementation depending on some dynamic state.
@Bean
is perfect for that case.
@Bean
@Scope("prototype")
public SomeService someService() {
switch (state) {
case 1:
return new Impl1();
case 2:
return new Impl2();
case 3:
return new Impl3();
default:
return new Impl();
}
}
However there is no way to do that with @Component
.
What are you doing: (I am using bytes instead of in for better reading)
You start with int *ap
and so on, so your (your computers) memory looks like this:
-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory --------
100: something <- here is *ap
101: 41 <- here starts a[]
102: 42
103: 43
104: 44
105: 45
106: something <- here waits x
lets take a look waht happens when (print short cut for ...print("$d", ...)
print a[0] -> 41 //no surprise
print a -> 101 // because a points to the start of the array
print *a -> 41 // again the first element of array
print a+1 -> guess? 102
print *(a+1) -> whats behind 102? 42 (we all love this number)
and so on, so a[0] is the same as *a, a[1] = *(a+1), ....
a[n] just reads easier.
now, what happens at line 9?
ap=a[4] // we know a[4]=*(a+4) somehow *105 ==> 45
// warning! converting int to pointer!
-------------- your memory --------
100: 45 <- here is *ap now 45
x = *ap; // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang! // dont touch neighbours garden
So the "warning" is not just a warning it's a severe error.
You could try to assign properties to the ENUM you're trying to create and statically contruct it by using a loaded properties file. Big hack, but it works :)
No-one seems to have mentioned this solution. Obvious really - but tripped me over for a moment...
The default access modifier for a new resources file is Internal
(or Friend
in VB.Net.)
Make sure you change this to Public
(in the resx designer there is a dropdown at the top for the access modifier)
This was also an easy way to add script and css in main.php
<script src="<?=Yii::app()->theme->baseUrl; ?>/js/bootstrap.min.js"></script>
<link href="<?=Yii::app()->theme->baseUrl; ?>/css/bootstrap.css" rel="stylesheet" type="text/css">
Try the following:
$ch = curl_init("http://www.example-webpage.com/file.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
I would only recommend this for small files. Big files are read as a whole and are likely to produce a memory error.
EDIT: after some discussion in the comments we found out that the problem was that the server couldn't resolve the host name and the page was in addition a HTTPS resource so here comes your temporary solution (until your server admin fixes the name resolving).
what i did is just pinging graph.facebook.com to see the IP address, replace the host name with the IP address and instead specify the header manually. This however renders the SSL certificate invalid so we have to suppress peer verification.
//$url = "https://graph.facebook.com/19165649929?fields=name";
$url = "https://66.220.146.224/19165649929?fields=name";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: graph.facebook.com'));
$output = curl_exec($ch);
curl_close($ch);
Keep in mind that the IP address might change and this is an error source. you should also do some error handling using curl_error();
.
You should look into the strtotime() function.
IMHO the safer way would be to create a new collection, to iterate over your given collection, adding each element in the new collection, and adding extra elements as needed in the new collection as well, finally returning the new collection.
No, any method will require you to resolve every result. You can do
iter_length = len(list(iterable))
but running that on an infinite iterator will of course never return. It also will consume the iterator and it will need to be reset if you want to use the contents.
Telling us what real problem you're trying to solve might help us find you a better way to accomplish your actual goal.
Edit: Using list()
will read the whole iterable into memory at once, which may be undesirable. Another way is to do
sum(1 for _ in iterable)
as another person posted. That will avoid keeping it in memory.
There are two useful tools which will generate Java code (rough but good enough) from an unknown APK file.
Use the tool to convert the APK file to JAR:
$ d2j-dex2jar.bat demo.apk
dex2jar demo.apk -> ./demo-dex2jar.jar
Once the JAR file is generated, use JD-GUI to open the JAR file. You will see the Java files.
The output will be similar to:
Do NOT do that! setNum(num);//fix- until someone fixes your setter. Your getter should not call your setter with the uninitialized value of
num(e.g.
0`).
I suggest making a few small changes -
public static class Vars { private int num = 5; // Default to 5. public void setNum(int x) { this.num = x; // actually "set" the value. } public int getNum() { return num; } }
Even without pop
the list we can do with set_index
pd.DataFrame(table).T.set_index(0).T
Out[11]:
0 Heading1 Heading2
1 1 2
2 3 4
Update from_records
table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]
pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]:
Heading1 Heading2
0 1 2
1 3 4
Simply
SELECT @@system_time_zone;
Returns PST
(or whatever is relevant to your system).
If you're trying to determine the session timezone you can use this query:
SELECT IF(@@session.time_zone = 'SYSTEM', @@system_time_zone, @@session.time_zone);
Which will return the session timezone if it differs from the system timezone.
I did this for a home folder where all the folders are on the desktops of the corresponding users, reachable through a shortcut which did not have the appropriate permissions, so that users couldn't see it even if it was there. So I used Robocopy with the parameter to overwrite the file with the right settings:
FOR /F "tokens=*" %G IN ('dir /b') DO robocopy "\\server02\Folder with shortcut" "\\server02\home\%G\Desktop" /S /A /V /log+:C:\RobocopyShortcut.txt /XF *.url *.mp3 *.hta *.htm *.mht *.js *.IE5 *.css *.temp *.html *.svg *.ocx *.3gp *.opus *.zzzzz *.avi *.bin *.cab *.mp4 *.mov *.mkv *.flv *.tiff *.tif *.asf *.webm *.exe *.dll *.dl_ *.oc_ *.ex_ *.sy_ *.sys *.msi *.inf *.ini *.bmp *.png *.gif *.jpeg *.jpg *.mpg *.db *.wav *.wma *.wmv *.mpeg *.tmp *.old *.vbs *.log *.bat *.cmd *.zip /SEC /IT /ZB /R:0
As you see there are many file types which I set to ignore (just in case), just set them for your needs or your case scenario.
It was tested on Windows Server 2012, and every switch is documented on Microsoft's sites and others.
Cursor c = myDB.rawQuery("SELECT distinct p_name,p_price FROM products order by Id desc",new String[]{});
this works for me!!!
The NUMBER
type can be specified in different styles:
Resulting Resulting Precision Specification Precision Scale Check Comment ------------------------------------------------------------------------------- NUMBER NULL NULL NO 'maximum range and precision', values are stored 'as given' NUMBER(P, S) P S YES Error code: ORA-01438 NUMBER(P) P 0 YES Error code: ORA-01438 NUMBER(*, S) 38 S NO
Where the precision is the total number of digits and scale is the number of digits right or left (negative scale) of the decimal point.
Oracle specifies ORA-01438 as
value larger than specified precision allowed for this column
As noted in the table, this integrity check is only active if the precision is explicitly specified. Otherwise Oracle silently rounds the inserted or updated value using some unspecified method.
If you are forcing www. in url or forcing ssl prototcol, then try to use possible variations in htaccess file, such as:
RewriteEngine On RewriteBase / ### Force WWW ### RewriteCond %{HTTP_HOST} ^example\.com RewriteRule (.*) http://www.example.com/$1 [R=301,L] ## Force SSL ### RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://example.com/$1 [R,L] ## Block IP's ### Order Deny,Allow Deny from 256.251.0.139 Deny from 199.127.0.259
savefig
specifies the DPI for the saved figure (The default is 100 if it's not specified in your .matplotlibrc, have a look at the dpi
kwarg to savefig
). It doesn't inheret it from the DPI of the original figure.
The DPI affects the relative size of the text and width of the stroke on lines, etc. If you want things to look identical, then pass fig.dpi
to fig.savefig
.
E.g.
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png', dpi=fig.dpi)
Set the ValueMember
/DisplayMember
properties to the name of the properties of your Language
objects.
class Language
{
string text;
string value;
public string Text
{
get
{
return text;
}
}
public string Value
{
get
{
return value;
}
}
public Language(string text, string value)
{
this.text = text;
this.value = value;
}
}
...
combo.DisplayMember= "Text";
combo.ValueMember = "Value";
combo.Items.Add(new Language("English", "en"));
I guess for Wicket it's better to call add
method in the onInitialize()
(see components lifecycle) :
public abstract class BasicPage extends WebPage {
public BasicPage() {
}
@Override
public void onInitialize() {
add(new Label("title", getTitle()));
}
protected abstract String getTitle();
}
Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.
For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.
For enabling headers in Ubuntu:
sudo a2enmod headers
For php server to accept request from different origin use:
Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:
pause
to the batch file so that you can see what is happening before it exits.
.bat
files and select "edit". This will open the file in notepad.pause
.- OR -
.bat
files are located, hold down the "shift" key and right click in the white space.Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.
If every input asks the same question, you should use a for
loop and an array of inputs:
Scanner dd = new Scanner(System.in);
int[] vars = new int[3];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
Or as Chip suggested, you can parse the input from one line:
Scanner in = new Scanner(System.in);
int[] vars = new int[3];
System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();
You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.
Are there any performance benefits to using one over the other?
The current answer is no, because none of the current browser engines implements import/export
from the ES6 standard.
Some comparison charts http://kangax.github.io/compat-table/es6/ don't take this into account, so when you see almost all greens for Chrome, just be careful. import
keyword from ES6 hasn't been taken into account.
In other words, current browser engines including V8 cannot import new JavaScript file from the main JavaScript file via any JavaScript directive.
( We may be still just a few bugs away or years away until V8 implements that according to the ES6 specification. )
This document is what we need, and this document is what we must obey.
And the ES6 standard said that the module dependencies should be there before we read the module like in the programming language C, where we had (headers) .h
files.
This is a good and well-tested structure, and I am sure the experts that created the ES6 standard had that in mind.
This is what enables Webpack or other package bundlers to optimize the bundle in some special cases, and reduce some dependencies from the bundle that are not needed. But in cases we have perfect dependencies this will never happen.
It will need some time until import/export
native support goes live, and the require
keyword will not go anywhere for a long time.
What is require
?
This is node.js
way to load modules. ( https://github.com/nodejs/node )
Node uses system-level methods to read files. You basically rely on that when using require
. require
will end in some system call like uv_fs_open
(depends on the end system, Linux, Mac, Windows) to load JavaScript file/module.
To check that this is true, try to use Babel.js, and you will see that the import
keyword will be converted into require
.
You should probably use NOT EXISTS
for multiple columns.
from http://api.jquery.com/height/ (Note: The difference between the use for the window and the document object)
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
from http://api.jquery.com/scrollTop/
$(window).scrollTop() // return the number of pixels scrolled vertically
Assuming that you have a data frame called students
, you can select individual rows or columns using the bracket syntax, like this:
students[1,2]
would select row 1 and column 2, the result here would be a single cell.students[1,]
would select all of row 1, students[,2]
would select all of column 2.If you'd like to select multiple rows or columns, use a list of values, like this:
students[c(1,3,4),]
would select rows 1, 3 and 4, students[c("stu1", "stu2"),]
would select rows named stu1
and stu2
.Hope I could help.
One thing to ensure is that nothing can reassign your variable. If it is not a Boolean in the end, relying on truthiness will lead to bugs. The beauty of conditional programming in dynamically typed languages :).
The following prints "no".
x = False
if x:
print 'yes'
else:
print 'no'
Now let's change x.
x = 'False'
Now the statement prints "yes", because the string is truthy.
if x:
print 'yes'
else:
print 'no'
This statement, however, correctly outputs "no".
if x == True:
print 'yes'
else:
print 'no'
Besides using one of the default formats you can specify any size you want in the unit you specify.
For example:
// Document of 210mm wide and 297mm high
new jsPDF('p', 'mm', [297, 210]);
// Document of 297mm wide and 210mm high
new jsPDF('l', 'mm', [297, 210]);
// Document of 5 inch width and 3 inch high
new jsPDF('l', 'in', [3, 5]);
The 3rd parameter of the constructor can take an array of the dimensions. However they do not correspond to width and height, instead they are long side and short side (or flipped around).
Your 1st parameter (landscape
or portrait
) determines what becomes the width and the height.
In the sourcecode on GitHub you can see the supported units (relative proportions to pt
), and you can also see the default page formats (with their sizes in pt
).
You were almost there.
Remove protected $dates = ['license_expire']
and then change your LicenseExpire
accessor to:
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date);
}
This way it will return a Carbon
instance no matter what.
So for your form you would just have $employee->license_expire->format('Y-m-d')
(or whatever format is required) and diffForHumans()
should work on your home page as well.
Hope this helps!
Uninstall NPM and install it again.
As of February 27, 2014 npm no longer supports its self-signed certificates. http://blog.npmjs.org/post/78085451721/npms-self-signed-certificate-is-no-more
The link above suggests upgrading NPM using NPM. This also fails with SELF_SIGNED_CERT_IN_CHAIN...
While the indentation errors are obvious in the StackOverflow page, they may not be in your editor. You have a mix of different indentation types here, 1, 4 and 8 spaces. You should always use four spaces for indentation, as per PEP8. You should also avoid mixing tabs and spaces.
I also recommend that you try to run your script using the '-tt
' command-line option to determine when you accidentally mix tabs and spaces. Of course any decent editor will be able to highlight tabs versus spaces (such as Vim's 'list'
option).
The updatePolicy tag didn't work for me. However Rich Seller mentioned that snapshots should be disabled anyways so I looked further and noticed that the extra repository that I added to my settings.xml was causing the problem actually. Adding the snapshots section to this repository in my settings.xml did the trick!
<repository>
<id>jboss</id>
<name>JBoss Repository</name>
<url>http://repository.jboss.com/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
I finally found the fix for this!
As we have found, IB doesn't allow us to change the height of the rounded corner border style. So change it to any of the other styles and set the desired height. In the code change the border style back.
textField.borderStyle = UITextBorderStyleRoundedRect;
The S parameter does not do anything on its own.
/S Modifies the treatment of string after /C or /K (see below)
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
Try something like this instead
Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)
You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.
Shell("perl a.pl c:\temp")
-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn
Here's a way I am doing it after researching it for a while. I wanted to make a Laravel API endpoint that checks if a field is "in use", so the important information is: 1) which DB table? 2) what DB column? and 3) is there a value in that column that matches the search terms?
Knowing this, we can construct our associative array:
$SEARCHABLE_TABLE_COLUMNS = [
'users' => [ 'email' ],
];
Then, we can set our values that we will check:
$table = 'users';
$column = 'email';
$value = '[email protected]';
Then, we can use array_key_exists()
and in_array()
with eachother to execute a one, two step combo and then act upon the truthy
condition:
// step 1: check if 'users' exists as a key in `$SEARCHABLE_TABLE_COLUMNS`
if (array_key_exists($table, $SEARCHABLE_TABLE_COLUMNS)) {
// step 2: check if 'email' is in the array: $SEARCHABLE_TABLE_COLUMNS[$table]
if (in_array($column, $SEARCHABLE_TABLE_COLUMNS[$table])) {
// if table and column are allowed, return Boolean if value already exists
// this will either return the first matching record or null
$exists = DB::table($table)->where($column, '=', $value)->first();
if ($exists) return response()->json([ 'in_use' => true ], 200);
return response()->json([ 'in_use' => false ], 200);
}
// if $column isn't in $SEARCHABLE_TABLE_COLUMNS[$table],
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}
// if $table isn't a key in $SEARCHABLE_TABLE_COLUMNS,
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);
I apologize for the Laravel-specific PHP code, but I will leave it because I think you can read it as pseudo-code. The important part is the two if
statements that are executed synchronously.
array_key_exists()
andin_array()
are PHP functions.
source:
The nice thing about the algorithm that I showed above is that you can make a REST endpoint such as GET /in-use/{table}/{column}/{value}
(where table
, column
, and value
are variables).
You could have:
$SEARCHABLE_TABLE_COLUMNS = [
'accounts' => [ 'account_name', 'phone', 'business_email' ],
'users' => [ 'email' ],
];
and then you could make GET requests such as:
GET /in-use/accounts/account_name/Bob's Drywall
(you may need to uri encode the last part, but usually not)
GET /in-use/accounts/phone/888-555-1337
GET /in-use/users/email/[email protected]
Notice also that no one can do:
GET /in-use/users/password/dogmeat1337
because password
is not listed in your list of allowed columns for user
.
Good luck on your journey.
I tried this code to accept files using Ajax and on submit file gets store using my php file. Code modified slightly to work. (Uploaded Files: PDF,JPG)
function verify1() {
jQuery.ajax({
type: 'POST',
url:"functions.php",
data: new FormData($("#infoForm1")[0]),
processData: false,
contentType: false,
success: function(returnval) {
$("#show1").html(returnval);
$('#show1').show();
}
});
}
Just print the file details and check. You will get Output. If error let me know.
Have you taken a look at ExpandoObject?
From MSDN:
The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").
Allowing you to do cool things like:
dynamic dynObject = new ExpandoObject();
dynObject.SomeDynamicProperty = "Hello!";
dynObject.SomeDynamicAction = (msg) =>
{
Console.WriteLine(msg);
};
dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);
Based on your actual code you may be more interested in:
public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
return new MyDynObject(properties);
}
public sealed class MyDynObject : DynamicObject
{
private readonly Dictionary<string, object> _properties;
public MyDynObject(Dictionary<string, object> properties)
{
_properties = properties;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _properties.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_properties.ContainsKey(binder.Name))
{
result = _properties[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_properties.ContainsKey(binder.Name))
{
_properties[binder.Name] = value;
return true;
}
else
{
return false;
}
}
}
That way you just need:
var dyn = GetDynamicObject(new Dictionary<string, object>()
{
{"prop1", 12},
});
Console.WriteLine(dyn.prop1);
dyn.prop1 = 150;
Deriving from DynamicObject allows you to come up with your own strategy for handling these dynamic member requests, beware there be monsters here: the compiler will not be able to verify a lot of your dynamic calls and you won't get intellisense, so just keep that in mind.
One can simply use
INSERT INTO MY_TABLE(MY_TIMESTAMP_FIELD)
VALUES (TIMESTAMP '2019-02-15 13:22:11.871+02:00');
This way you won't have to worry about date format string, just use default timestamp format.
Works with Oracle 11, have no idea if it does for earlier Oracle versions.
At university we were taught 'best practice' was to use != when working for employers, though all the operators above have the same functionality.
Try to change where Member class
public function users() {
return $this->hasOne('User');
}
return $this->belongsTo('User');
You should have access to the POST dictionary on the request object.
DefaultThreadCurrentCulture
and DefaultThreadCurrentUICulture
are present in Framework 4.0 too, but they are Private. Using Reflection you can easily set them. This will affect all threads where CurrentCulture
is not explicitly set (running threads too).
Public Sub SetDefaultThreadCurrentCulture(paCulture As CultureInfo)
Thread.CurrentThread.CurrentCulture.GetType().GetProperty("DefaultThreadCurrentCulture").SetValue(Thread.CurrentThread.CurrentCulture, paCulture, Nothing)
Thread.CurrentThread.CurrentCulture.GetType().GetProperty("DefaultThreadCurrentUICulture").SetValue(Thread.CurrentThread.CurrentCulture, paCulture, Nothing)
End Sub
I also had the error error/constitute.c/ReadImage/453
when trying to convert an eps to a gif with image magick. I tried the solution proposed by sNICkerssss but still had errors (though different from the first one)e error/constitute.c/ReadImage/412
What solved the problem was to put read
to other entries
<policy domain="coder" rights="read" pattern="PS" />
<policy domain="coder" rights="read" pattern="EPS" />
<policy domain="coder" rights="read" pattern="PDF" />
<policy domain="coder" rights="read" pattern="XPS" />
<policy domain="coder" rights="read|write" pattern="LABEL" />
Having tried other solutions which worked fine, but the pitfall of their answers is that only fields already existing would update adding upsert to it would do nothing, so I came up with this.
Person.update({'items.id': 2}, {$set: {
'items': { "item1", "item2", "item3", "item4" } }, {upsert:
true })
Probably you have a sub asp.net project folder within the project folder which is not configured as virtual directory. Setup the project to run in IIS.
Take a look at expect
linux utility.
It allows you to send output to stdio based on simple pattern matching on stdin.
You can use this code to find HyperLink
in GridView. Use of e.Row.Cells[0].Controls[0]
to find First position of control in GridView.
protected void AspGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView v = (DataRowView)e.Row.DataItem;
if (e.Row.Cells.Count > 0 && e.Row.Cells[0] != null && e.Row.Cells[0].Controls.Count > 0)
{
HyperLink link = e.Row.Cells[0].Controls[0] as HyperLink;
if (link != null)
{
link.Text = "Edit";
}
}
}
}
The direct answer to this question is:
if(rows.Any()) //prevent IndexOutOfRangeException for empty list
{
rows.RemoveAt(rows.Count - 1);
}
However... in the specific case of this question, it makes more sense not to add the row in the first place:
Row row = new Row();
//...
if (!row.cell[0].Equals("Something"))
{
rows.Add(row);
}
TBH, I'd go a step further by testing "Something"
against user.""
, and not even instantiating a Row
unless the condition is satisfied, but seeing as user.""
won't compile, I'll leave that as an exercise for the reader.
You could install Web Tool Platform on top of your current installation to help you learn about Java EE. Download the Web Tools Platform by using Eclipse Software Update (Instruction at http://download.eclipse.org/webtools/updates/). It has features to get you going with learning Java EE. You could learn more about Web Tools Platform at http://www.eclipse.org/webtools/
This rings a bell. I came across a similar problem in the past,
You can generate an assemblyInfo.cs by right clicking the project and chosing properties. In the application tab fill in the details and press save, this will generate the assemblyInfo.cs file for you. If you build your project after that, it should work.
Cheers, Tarun
Update 2016-07-08:
For Visual Studio 2010 through the most recent version (2015 at time of writing), LandedGently's comment still applies:
After you select project Properties and the Application tab as @Tarun mentioned, there is a button "Assembly Information..." which opens another dialog. You need to at least fill in the Title here. VS will add the GUID and versions, but if the title is empty, it will not create the AssemblyInfo.cs file.
You can use charAt() function to find out spaces in string.
public class Test {
public static void main(String args[]) {
String fav="Hi Testing 12 3";
int counter=0;
for( int i=0; i<fav.length(); i++ ) {
if(fav.charAt(i) == ' ' ) {
counter++;
}
}
System.out.println("Number of spaces "+ counter);
//This will print Number of spaces 4
}
}
I had a similar issue , The function name i was using matched one of the inbuilt functions declared in one of the header files that i included in the program.Reading through the compiler error message will tell you the exact header file and function name.Changing the function name solved this issue for me
I have faced the same problem once:
Pattern ptr = Pattern.compile("^[a-zA-Z][\\']?[a-zA-Z\\s]+$");
The above failed!
Pattern ptr = Pattern.compile("(^[a-zA-Z][\\']?[a-zA-Z\\s]+$)");
The above worked with pattern within (
and )
.
Simplified and updated version of the Scala answer by Paolo:
import scala.collection.JavaConversions.{collectionAsScalaIterable => asScala}
import com.amazonaws.services.s3.AmazonS3
import com.amazonaws.services.s3.model.{ListObjectsRequest, ObjectListing, S3ObjectSummary}
def buildListing(s3: AmazonS3, request: ListObjectsRequest): List[S3ObjectSummary] = {
def buildList(listIn: List[S3ObjectSummary], bucketList:ObjectListing): List[S3ObjectSummary] = {
val latestList: List[S3ObjectSummary] = bucketList.getObjectSummaries.toList
if (!bucketList.isTruncated) listIn ::: latestList
else buildList(listIn ::: latestList, s3.listNextBatchOfObjects(bucketList))
}
buildList(List(), s3.listObjects(request))
}
Stripping out the generics and using the ListObjectRequest generated by the SDK builders.
if you want to strip all tags, then try this
function:
String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}
usage:
var newText=$('selector').html().stripTags();
As someone more experienced with Oracle DB, I was concerned about this limit too. I carried out a performance test for a query with ~10'000 parameters in an IN
-list, fetching prime numbers up to 100'000 from a table with the first 100'000 integers by actually listing all the prime numbers as query parameters.
My results indicate that you need not worry about overloading the query plan optimizer or getting plans without index usage, since it will transform the query to use = ANY({...}::integer[])
where it can leverage indices as expected:
-- prepare statement, runs instantaneous:
PREPARE hugeplan (integer, integer, integer, ...) AS
SELECT *
FROM primes
WHERE n IN ($1, $2, $3, ..., $9592);
-- fetch the prime numbers:
EXECUTE hugeplan(2, 3, 5, ..., 99991);
-- EXPLAIN ANALYZE output for the EXECUTE:
"Index Scan using n_idx on primes (cost=0.42..9750.77 rows=9592 width=5) (actual time=0.024..15.268 rows=9592 loops=1)"
" Index Cond: (n = ANY ('{2,3,5,7, (...)"
"Execution time: 16.063 ms"
-- setup, should you care:
CREATE TABLE public.primes
(
n integer NOT NULL,
prime boolean,
CONSTRAINT n_idx PRIMARY KEY (n)
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.primes
OWNER TO postgres;
INSERT INTO public.primes
SELECT generate_series(1,100000);
However, this (rather old) thread on the pgsql-hackers mailing list indicates that there is still a non-negligible cost in planning such queries, so take my word with a grain of salt.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in dirs:
print os.path.join(root, name)
Walk is a good built-in for what you are doing
First you need to wrap your code in a Label
or Literal
control so that you can reference it properly. What's happening is that there's no way for the system to keep track of it, because there's no control associated with the text. It's the control's responsibility to add its contents to viewstate.
You need to use gridView.FindControl("controlName"); to get the control in the row. From there you can get at its properties including Text
.
You can also get at the DataItem property of the Row in question and cast it to the appropriate type and extract the information directly.
Use the id
of the element to do the same.
document.getElementById(id).style.visibility = 'hidden';
Another kludge, ugh, but it's easy and works for me in VS 2013. Click on the project. In the properties panel should be an entry named Project File with a value
(your project name).vbproj
Change the project name - such as adding an -01 to the end. The original .zip file that was locked is still there, but no longer referenced ... so your work can continue. Next time the computer is rebooted, that lock disappears and you can delete the errant file.
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
// Create a new StringBuilder.
StringBuilder builder = new StringBuilder();
// Loop and append values.
for (int i = 0; i < 5; i++) {
builder.append("abc ");
}
// Convert to string.
String result = builder.toString();
// Print result.
System.out.println(result);
}
}
This is correct formula to find integers from i
to j
where i <= R <= j
FLOOR(min+RAND()*(max-min))
You can convert your RDD
to a DataFrame
then show()
it.
// For implicit conversion from RDD to DataFrame
import spark.implicits._
fruits = sc.parallelize([("apple", 1), ("banana", 2), ("orange", 17)])
// convert to DF then show it
fruits.toDF().show()
This will show the top 20 lines of your data, so the size of your data should not be an issue.
+------+---+
| _1| _2|
+------+---+
| apple| 1|
|banana| 2|
|orange| 17|
+------+---+
I have a sample app where I prepare the intent and just pass the CITY_NAME in the intent to the maps marker activity which eventually calculates longitude and latitude by Geocoder using CITY_NAME.
Below is the code snippet of starting the maps marker activity and the complete MapsMarkerActivity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.action_refresh) {
Log.d(APP_TAG, "onOptionsItemSelected Refresh selected");
new MainActivityFragment.FetchWeatherTask().execute(CITY, FORECAS_DAYS);
return true;
} else if (id == R.id.action_map) {
Log.d(APP_TAG, "onOptionsItemSelected Map selected");
Intent intent = new Intent(this, MapsMarkerActivity.class);
intent.putExtra("CITY_NAME", CITY);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public class MapsMarkerActivity extends AppCompatActivity
implements OnMapReadyCallback {
private String cityName = "";
private double longitude;
private double latitude;
static final int numberOptions = 10;
String [] optionArray = new String[numberOptions];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_map);
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Test whether geocoder is present on platform
if(Geocoder.isPresent()){
cityName = getIntent().getStringExtra("CITY_NAME");
geocodeLocation(cityName);
} else {
String noGoGeo = "FAILURE: No Geocoder on this platform.";
Toast.makeText(this, noGoGeo, Toast.LENGTH_LONG).show();
return;
}
}
/**
* Manipulates the map when it's available.
* The API invokes this callback when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user receives a prompt to install
* Play services inside the SupportMapFragment. The API invokes this method after the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(latitude, longitude);
// If cityName is not available then use
// Default Location.
String markerDisplay = "Default Location";
if (cityName != null
&& cityName.length() > 0) {
markerDisplay = "Marker in " + cityName;
}
googleMap.addMarker(new MarkerOptions().position(sydney)
.title(markerDisplay));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
/**
* Method to geocode location passed as string (e.g., "Pentagon"), which
* places the corresponding latitude and longitude in the variables lat and lon.
*
* @param placeName
*/
private void geocodeLocation(String placeName){
// Following adapted from Conder and Darcey, pp.321 ff.
Geocoder gcoder = new Geocoder(this);
// Note that the Geocoder uses synchronous network access, so in a serious application
// it would be best to put it on a background thread to prevent blocking the main UI if network
// access is slow. Here we are just giving an example of how to use it so, for simplicity, we
// don't put it on a separate thread. See the class RouteMapper in this package for an example
// of making a network access on a background thread. Geocoding is implemented by a backend
// that is not part of the core Android framework, so we use the static method
// Geocoder.isPresent() to test for presence of the required backend on the given platform.
try{
List<Address> results = null;
if(Geocoder.isPresent()){
results = gcoder.getFromLocationName(placeName, numberOptions);
} else {
Log.i(MainActivity.APP_TAG, "No Geocoder found");
return;
}
Iterator<Address> locations = results.iterator();
String raw = "\nRaw String:\n";
String country;
int opCount = 0;
while(locations.hasNext()){
Address location = locations.next();
if(opCount == 0 && location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
country = location.getCountryName();
if(country == null) {
country = "";
} else {
country = ", " + country;
}
raw += location+"\n";
optionArray[opCount] = location.getAddressLine(0)+", "
+location.getAddressLine(1)+country+"\n";
opCount ++;
}
// Log the returned data
Log.d(MainActivity.APP_TAG, raw);
Log.d(MainActivity.APP_TAG, "\nOptions:\n");
for(int i=0; i<opCount; i++){
Log.i(MainActivity.APP_TAG, "("+(i+1)+") "+optionArray[i]);
}
Log.d(MainActivity.APP_TAG, "latitude=" + latitude + ";longitude=" + longitude);
} catch (Exception e){
Log.d(MainActivity.APP_TAG, "I/O Failure; do you have a network connection?",e);
}
}
}
Links expire so i have pasted complete code above but just in case if you would like to see complete code then its available at : https://github.com/gosaliajigar/CSC519/tree/master/CSC519_HW4_89753
Handlebars can use an array as the context. You can use .
as the root of the data. So you can loop through your array data with {{#each .}}
.
var data = [_x000D_
{_x000D_
Category: "General",_x000D_
DocumentList: [_x000D_
{_x000D_
DocumentName: "Document Name 1 - General",_x000D_
DocumentLocation: "Document Location 1 - General"_x000D_
},_x000D_
{_x000D_
DocumentName: "Document Name 2 - General",_x000D_
DocumentLocation: "Document Location 2 - General"_x000D_
}_x000D_
]_x000D_
},_x000D_
{_x000D_
Category: "Unit Documents",_x000D_
DocumentList: [_x000D_
{_x000D_
DocumentName: "Document Name 1 - Unit Documents",_x000D_
DocumentList: "Document Location 1 - Unit Documents"_x000D_
}_x000D_
]_x000D_
},_x000D_
{_x000D_
Category: "Minutes"_x000D_
}_x000D_
];_x000D_
_x000D_
$(function() {_x000D_
var source = $("#document-template").html();_x000D_
var template = Handlebars.compile(source);_x000D_
var html = template(data);_x000D_
$('#DocumentResults').html(html);_x000D_
});
_x000D_
.row {_x000D_
border: 1px solid red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div id="DocumentResults">pos</div>_x000D_
<script id="document-template" type="text/x-handlebars-template">_x000D_
<div>_x000D_
{{#each .}}_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
<h2>{{Category}}</h2>_x000D_
{{#DocumentList}}_x000D_
<p>{{DocumentName}} at {{DocumentLocation}}</p>_x000D_
{{/DocumentList}}_x000D_
</div>_x000D_
</div>_x000D_
{{/each}}_x000D_
</div>_x000D_
</script>
_x000D_
Assuming that you wanted to know the "fraction" of the month that dates were in, which I did, then you need to do a bit more work.
from datetime import datetime, date
import calendar
def monthdiff(start_period, end_period, decimal_places = 2):
if start_period > end_period:
raise Exception('Start is after end')
if start_period.year == end_period.year and start_period.month == end_period.month:
days_in_month = calendar.monthrange(start_period.year, start_period.month)[1]
days_to_charge = end_period.day - start_period.day+1
diff = round(float(days_to_charge)/float(days_in_month), decimal_places)
return diff
months = 0
# we have a start date within one month and not at the start, and an end date that is not
# in the same month as the start date
if start_period.day > 1:
last_day_in_start_month = calendar.monthrange(start_period.year, start_period.month)[1]
days_to_charge = last_day_in_start_month - start_period.day +1
months = months + round(float(days_to_charge)/float(last_day_in_start_month), decimal_places)
start_period = datetime(start_period.year, start_period.month+1, 1)
last_day_in_last_month = calendar.monthrange(end_period.year, end_period.month)[1]
if end_period.day != last_day_in_last_month:
# we have lest days in the last month
months = months + round(float(end_period.day) / float(last_day_in_last_month), decimal_places)
last_day_in_previous_month = calendar.monthrange(end_period.year, end_period.month - 1)[1]
end_period = datetime(end_period.year, end_period.month - 1, last_day_in_previous_month)
#whatever happens, we now have a period of whole months to calculate the difference between
if start_period != end_period:
months = months + (end_period.year - start_period.year) * 12 + (end_period.month - start_period.month) + 1
# just counter for any final decimal place manipulation
diff = round(months, decimal_places)
return diff
assert monthdiff(datetime(2015,1,1), datetime(2015,1,31)) == 1
assert monthdiff(datetime(2015,1,1), datetime(2015,02,01)) == 1.04
assert monthdiff(datetime(2014,1,1), datetime(2014,12,31)) == 12
assert monthdiff(datetime(2014,7,1), datetime(2015,06,30)) == 12
assert monthdiff(datetime(2015,1,10), datetime(2015,01,20)) == 0.35
assert monthdiff(datetime(2015,1,10), datetime(2015,02,20)) == 0.71 + 0.71
assert monthdiff(datetime(2015,1,31), datetime(2015,02,01)) == round(1.0/31.0,2) + round(1.0/28.0,2)
assert monthdiff(datetime(2013,1,31), datetime(2015,02,01)) == 12*2 + round(1.0/31.0,2) + round(1.0/28.0,2)
provides an example that works out the number of months between two dates inclusively, including the fraction of each month that the date is in. This means that you can work out how many months is between 2015-01-20 and 2015-02-14, where the fraction of the date in the month of January is determined by the number of days in January; or equally taking into account that the number of days in February can change form year to year.
For my reference, this code is also on github - https://gist.github.com/andrewyager/6b9284a4f1cdb1779b10
Don't use the IP address to definitively determine location (and hence timezone)-- that's because with NAT, proxies (increasingly popular), and VPNs, IP addresses do not necessarily realistically reflect the user's actual location, but the location at which the servers implementing those protocols reside.
Similar to how US area codes are no longer useful for locating a telephone user, given the popularity of number portability.
IP address and other techniques shown above are useful for suggesting a default that the user can adjust/correct.
Another simple option that updates on a click of the checkbox.
HTML:
<input type="checkbox" id="checkbox/>
<input disabled type="submit" id="item"/>
jQuery:
$('#checkbox').click(function() {
if (this.checked) {
$('#item').prop('disabled', false); // If checked enable item
} else {
$('#item').prop('disabled', true); // If checked disable item
}
});
In action: link
Python's power operator is **
and Euler's number is math.e
, so:
from math import e
x.append(1-e**(-value1**2/2*value2**2))
I met this issue due to operation system, simple to different platform about JRE implementation.
new SecureRandom(key.getBytes())
will get the same value in Windows, while it's different in Linux. So in Linux need to be changed to
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
"SHA1PRNG" is the algorithm used, you can refer here for more info about algorithms.
Generally speak I defined null
as it indicates a human set the value and undefined
to indicate no setting has taken place.
It is better to use a sequential for
loop:
for (var i = 0; i < myStringArray.length; i++) {
// Do something
}
You could use the string to index into a hash table of function pointers.
Edit: glib has a hash table implementation that supports strings as keys and arbitrary pointers as values: http://library.gnome.org/devel/glib/stable/glib-Hash-Tables.html
I have found better option,
<style type="text/css">
.form {
margin: 0 auto;
width: 210px;
}
.form label{
display: inline-block;
text-align: right;
float: left;
}
.form input{
display: inline-block;
text-align: left;
float: right;
}
</style>
Demo here: https://jsfiddle.net/durtpwvx/
as of Jan 2017, unfortunately @Adi's answer, while it seems like it should work, does not. (Google's API key process is buggy)
you'll need to click "get a key" from this link: https://developers.google.com/maps/documentation/javascript/get-api-key
also I strongly recommend you don't ever choose "secure key" until you are ready to switch to production. I did http referrer restrictions on a key and afterwards was unable to get it working with localhost, even after disabling security for the key. I had to create a new key for it to work again.
VBA is not VB/VB.NET
The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:
Do While counter < 20
counter = counter + 1
Loop
(But a For..Next might be more appropriate here.)
Happy coding.