It can typically occur when you changed the target framework of .csproj and reverted it back to what you started with.
Make sure 1 if supportedRuntime version="a different runtime from cs project target" under startup tag in app.config.
Make sure 2 That also means checking other autogenerated or other files in may be properties folder to see if there is no more runtime mismatch between these files and one that is defined in .csproj file.
These might just save you lot of time before you start trying different things with project properties to overcome the error.
I recently hit this issue, the app would run fine on the developer machines and select others machines but not on recently installed machines. It turned out that the machines it did work on had the Visual C++ 11 Runtime installed while the freshly installed machines didn't. Adding the Visual C++ 11 Runtime redistributable to the app installer fixed the issue...
EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'
check field execution_status
0 - Returns only those jobs that are not idle or suspended.
1 - Executing.
2 - Waiting for thread.
3 - Between retries.
4 - Idle.
5 - Suspended.
7 - Performing completion actions.
If you need the result of execution, check the field last_run_outcome
0 = Failed
1 = Succeeded
3 = Canceled
5 = Unknown
This worked for me in ASP.NET Core MVC.
<script type="text/javascript">
var ar = @Html.Raw(Json.Serialize(Model.Addresses));
</script>
I think the simplest way is:
<th data-searchable="false">Column</th>
You can edit only the table you have to modify, without change common CSS or JS.
another solution is catching onClick event and for aggregate data to js function you can
.hmtl.erb
<%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>
.js
// handle my-class click
$('a.my-class').on('click', function () {
var link = $(this);
var array = link.data('array');
});
Using Node.removeChild() does the job for you, simply use something like this:
var leftSection = document.getElementById('left-section');
leftSection.parentNode.removeChild(leftSection);
In DOM 4, the remove method applied, but there is a poor browser support according to W3C:
The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.
But you can use remove method if you using jQuery...
$('#left-section').remove(); //using remove method in jQuery
Also in new frameworks like you can use conditions to remove an element, for example *ngIf
in Angular and in React, rendering different views, depends on the conditions...
Did they add a runtime List<> and/or Map<> type class to typepad 1.0
No, providing a runtime is not the focus of the TypeScript team.
is there a solid library out there someone wrote that provides this functionality?
I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections
JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts
: https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want
In order to fix this issue, the process I have mentioned below.
Please cancel the current process of“react-native run-android” by CTRL + C or CMD + C
Close metro bundler(terminal) window command line which opened automatically.
Run the command again on terminal, “react-native run-android
Using setup
from distutils.core
instead of setuptools
in setup.py worked for me, too:
#from setuptools import setup
from distutils.core import setup
Answer from 2014 for the people who are down-voting me:
Well, S3 isn't FTP. There are lots and lots of clients that support S3, however.
Pretty much every notable FTP client on OS X has support, including Transmit and Cyberduck.
If you're on Windows, take a look at Cyberduck or CloudBerry.
Updated answer for 2019:
AWS has recently released the AWS Transfer for SFTP service, which may do what you're looking for.
Something like...
Minutes.minutesBetween(getStart(), getEnd()).getMinutes();
I was looking long and hard for a solution to this problem and the best I found was a root FTP server on the phone that you connect to on Windows with an FTP client like FileZilla, on the same WiFi network of course.
The root FTP server app I ended up using is FTP Droid. I tried a lot of other FTP apps with bigger download numbers but none of them worked for me for whatever reason. So install this app and set a user with home as / or wherever you want.
Then make note of the phone IP and connect with FileZilla and you should have access to the root of the phone. The biggest benefit I found is I can download entire folders and FTP will just queue it up and take care of it. So I downloaded all of my /data/data/ folder when I was looking for an app and could search on my PC. Very handy.
In order to make the terminal always have the file ~/.bashrc
and there put the path you wish to use, by adding:
export PATH=$PATH:/XXX
where XXX is the path that you wish to use.
for adb, here's what i use:
export PATH=$PATH:/home/user/Android/android-sdk-linux_x86/platform-tools/
(where "user" is my user name).
If you're putting a <meta> tag in your css files, you're doing something wrong. The <meta> tag belongs in your html files, and tells the browser how the html is encoded, it doesn't say anything about the css, which is a separate file. You could conceivably have completely different encodings for your html and css, although I can't imagine this would be a good idea.
If you run sudo apt-get install lib32z1 lib32ncurses5 libbz2-1.0 lib32stdc++6
and got a message like: "The following packages have unmet dependencies: lib32stdc++6 : Depends: lib32gcc1 (>= 1:4.1.1)
".
You can do something like this tut: https://askubuntu.com/questions/671791/lib32stdc6-package-depends-on-gcc-base-but-my-installed-version-is-newer
KeyPress is only fired by printable characters and is fired after the KeyDown event. Depending on the typing delay settings there can be multiple KeyDown and KeyPress events but only one KeyUp event.
KeyDown
KeyPress
KeyUp
save as png solved the problem for me.
For Visual Studio 2012 while debugging that error accrued
Website Menu -> Use IIS Express did it for me
I liked @KyleMit's answer on how to make an unstyled input group, but in my case, I only wanted the right side unstyled - I still wanted to use an input-group-addon on the left side and have it look like normal bootstrap. So, I did this:
css
.input-group.input-group-unstyled-right input.form-control {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.input-group-unstyled-right .input-group-addon.input-group-addon-unstyled {
border-radius: 4px;
border: 0px;
background-color: transparent;
}
html
<div class="input-group input-group-unstyled-right">
<span class="input-group-addon">
<i class="fa fa-envelope-o"></i>
</span>
<input type="text" class="form-control">
<span class="input-group-addon input-group-addon-unstyled">
<i class="fa fa-check"></i>
</span>
</div>
This is working to me
'int numRows = dgbDatos.Rows.Count;
for (int i = 0; i < numRows; i++)
{
try
{
int max = dgbDatos.Rows.Count - 1;
dgbDatos.Rows.Remove(dgbDatos.Rows[max]);
btnAgregar.Enabled = true;
}
catch (Exception exe)
{
MessageBox.Show("No se puede eliminar " + exe, "",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}`
The following examples are source ordered i.e. column 1 appears before column 2 in the HTML source. Whether a column appears on left or right is controlled by CSS:
Fixed Right
#wrapper {_x000D_
margin-right: 200px;_x000D_
}_x000D_
#content {_x000D_
float: left;_x000D_
width: 100%;_x000D_
background-color: #CCF;_x000D_
}_x000D_
#sidebar {_x000D_
float: right;_x000D_
width: 200px;_x000D_
margin-right: -200px;_x000D_
background-color: #FFA;_x000D_
}_x000D_
#cleared {_x000D_
clear: both;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="content">Column 1 (fluid)</div>_x000D_
<div id="sidebar">Column 2 (fixed)</div>_x000D_
<div id="cleared"></div>_x000D_
</div>
_x000D_
Fixed Left
#wrapper {_x000D_
margin-left: 200px;_x000D_
}_x000D_
#content {_x000D_
float: right;_x000D_
width: 100%;_x000D_
background-color: #CCF;_x000D_
}_x000D_
#sidebar {_x000D_
float: left;_x000D_
width: 200px;_x000D_
margin-left: -200px;_x000D_
background-color: #FFA;_x000D_
}_x000D_
#cleared {_x000D_
clear: both;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="content">Column 1 (fluid)</div>_x000D_
<div id="sidebar">Column 2 (fixed)</div>_x000D_
<div id="cleared"></div>_x000D_
</div>
_x000D_
Alternate solution is to use display: table-cell; which results in equal height columns.
Since Node.js is using the CommonJS patterns, you can only share variables between modules with module.exports
or by setting a global var like you would in the browser, but instead of using window you use global.your_var = value;
.
You need to push a bytes-like
object (bytes
, bytearray
, etc) to the base64.b64encode()
method. Here are two ways:
>>> import base64
>>> data = base64.b64encode(b'data to be encoded')
>>> print(data)
b'ZGF0YSB0byBiZSBlbmNvZGVk'
Or with a variable:
>>> import base64
>>> string = 'data to be encoded'
>>> data = base64.b64encode(string.encode())
>>> print(data)
b'ZGF0YSB0byBiZSBlbmNvZGVk'
In Python 3, str
objects are not C-style character arrays (so they are not byte arrays), but rather, they are data structures that do not have any inherent encoding. You can encode that string (or interpret it) in a variety of ways. The most common (and default in Python 3) is utf-8, especially since it is backwards compatible with ASCII (although, as are most widely-used encodings). That is what is happening when you take a string
and call the .encode()
method on it: Python is interpreting the string in utf-8 (the default encoding) and providing you the array of bytes that it corresponds to.
Originally the question title asked about Base-64 encoding. Read on for Base-64 stuff.
base64
encoding takes 6-bit binary chunks and encodes them using the characters A-Z, a-z, 0-9, '+', '/', and '=' (some encodings use different characters in place of '+' and '/'). This is a character encoding that is based off of the mathematical construct of radix-64 or base-64 number system, but they are very different. Base-64 in math is a number system like binary or decimal, and you do this change of radix on the entire number, or (if the radix you're converting from is a power of 2 less than 64) in chunks from right to left.
In base64
encoding, the translation is done from left to right; those first 64 characters are why it is called base64
encoding. The 65th '=' symbol is used for padding, since the encoding pulls 6-bit chunks but the data it is usually meant to encode are 8-bit bytes, so sometimes there are only two or 4 bits in the last chunk.
Example:
>>> data = b'test'
>>> for byte in data:
... print(format(byte, '08b'), end=" ")
...
01110100 01100101 01110011 01110100
>>>
If you interpret that binary data as a single integer, then this is how you would convert it to base-10 and base-64 (table for base-64):
base-2: 01 110100 011001 010111 001101 110100 (base-64 grouping shown)
base-10: 1952805748
base-64: B 0 Z X N 0
base64
encoding, however, will re-group this data thusly:
base-2: 011101 000110 010101 110011 011101 00(0000) <- pad w/zeros to make a clean 6-bit chunk
base-10: 29 6 21 51 29 0
base-64: d G V z d A
So, 'B0ZXN0' is the base-64 version of our binary, mathematically speaking. However, base64
encoding has to do the encoding in the opposite direction (so the raw data is converted to 'dGVzdA') and also has a rule to tell other applications how much space is left off at the end. This is done by padding the end with '=' symbols. So, the base64
encoding of this data is 'dGVzdA==', with two '=' symbols to signify two pairs of bits will need to be removed from the end when this data gets decoded to make it match the original data.
Let's test this to see if I am being dishonest:
>>> encoded = base64.b64encode(data)
>>> print(encoded)
b'dGVzdA=='
base64
encoding?Let's say I have to send some data to someone via email, like this data:
>>> data = b'\x04\x6d\x73\x67\x08\x08\x08\x20\x20\x20'
>>> print(data.decode())
>>> print(data)
b'\x04msg\x08\x08\x08 '
>>>
There are two problems I planted:
\x04
character was read, because that is ASCII for END-OF-TRANSMISSION
(Ctrl-D), so the remaining data would be left out of the transmission.BACKSPACE
characters and three SPACE
characters to erase the 'msg'. Thus, even if I didn't have the EOF
character there the end user wouldn't be able to translate from the text on screen to the real, raw data.This is just a demo to show you how hard it can be to simply send raw data. Encoding the data into base64 format gives you the exact same data but in a format that ensures it is safe for sending over electronic media such as email.
DO NOT USE THIS ANSWER. The URL is pointing at jQuery 1.11 (and always will).
Credits to Basic for above snippet
http://code.jquery.com/jquery-latest.min.js is the minified version, always up-to-date.
You can use npm i y-websockets-server
and then use the below command
y-websockets-server --port 11000
and here in my case, the port No is 11000.
I use this subtle alias:
alias vim='gnome-terminal -- vim'
-x is deprecated now. We need to use -- instead
if (x)
coerces x using JavaScript's internal toBoolean (http://es5.github.com/#x9.2)
x == false
coerces both sides using internal toNumber coercion (http://es5.github.com/#x9.3) or toPrimitive for objects (http://es5.github.com/#x9.1)
For full details see http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/
In the spring boot reference,it said:
When a class doesn’t include a package declaration it is considered to be in the “default package”. The use of the “default package” is generally discouraged, and should be avoided. It can cause particular problems for Spring Boot applications that use @ComponentScan, @EntityScan or @SpringBootApplication annotations, since every class from every jar, will be read.
com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
In your cases. You must add scanBasePackages
in the @SpringBootApplication
annotation.just like@SpringBootApplication(scanBasePackages={"domain","contorller"..})
After hours of finding ways on how to get the data from the row selected on a WPF DataGrid Control, as I was using MongoDB. I found this post and used Tony's answer. I revised the code to be relevant to my project. Maybe someone can use this to get an idea.
private void selectionChanged(object sender, SelectionChangedEventArgs e)
{
facultyData row = (facultyData)facultyDataGrid.SelectedItem;
facultyID_Textbox.Text = row.facultyID;
lastName_TextBox.Text = row.lastName;
firstName_TextBox.Text = row.firstName;
middleName_TextBox.Text = row.middleName;
age_TextBox.Text = row.age.ToString();
}
}
class facultyData
{
public ObjectId _id { get; set; }
public string facultyID { get; set; }
public string acadYear { get; set; }
public string program { get; set; }
}
try this
public void setUpTableData() {
DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
/**
* additional code.
**/
tableModel.setRowCount(0);
/**/
ArrayList<Contact> list = new ArrayList<Contact>();
if (!con.equals(""))
list = sql.getContactListsByGroup(con);
else
list = sql.getContactLists();
for (int i = 0; i < list.size(); i++) {
String[] data = new String[7];
data[0] = list.get(i).getName();
data[1] = list.get(i).getEmail();
data[2] = list.get(i).getPhone1();
data[3] = list.get(i).getPhone2();
data[4] = list.get(i).getGroup();
data[5] = list.get(i).getId();
tableModel.addRow(data);
}
jTable.setModel(tableModel);
/**
* additional code.
**/
tableModel.fireTableDataChanged();
/**/
}
In regards to this question, this can be easily achieved using a few lines of SASS;
HTML:
<a href="https://www.urbandictionary.com/define.php?term=techninja" data-tool-tip="What's a tech ninja?" target="_blank"><i class="fas fa-2x fa-user-ninja" id="tech--ninja"></i></a>
CSS output would be:
a[data-tool-tip]{
position: relative;
text-decoration: none;
color: rgba(255,255,255,0.75);
}
a[data-tool-tip]::after{
content: attr(data-tool-tip);
display: block;
position: absolute;
background-color: dimgrey;
padding: 1em 3em;
color: white;
border-radius: 5px;
font-size: .5em;
bottom: 0;
left: -180%;
white-space: nowrap;
transform: scale(0);
transition:
transform ease-out 150ms,
bottom ease-out 150ms;
}
a[data-tool-tip]:hover::after{
transform: scale(1);
bottom: 200%;
}
Basically the attribute selector [data-tool-tip] selects the content of whatever's inside and allows you to animate it however you want.
If polling is good enough for you, I'd just watch if the "modified time" file stat changes. To read it:
os.stat(filename).st_mtime
(Also note that the Windows native change event solution does not work in all circumstances, e.g. on network drives.)
import os
class Monkey(object):
def __init__(self):
self._cached_stamp = 0
self.filename = '/path/to/file'
def ook(self):
stamp = os.stat(self.filename).st_mtime
if stamp != self._cached_stamp:
self._cached_stamp = stamp
# File has changed, so do something...
If you have a hash structure like this:
Parameters: {"link"=>{"title"=>"Something", "time_span"=>[{"start"=>"2017-05-06T16:00:00.000Z", "end"=>"2017-05-06T17:00:00.000Z"}]}}
Then this is how I got it to work:
params.require(:link).permit(:title, time_span: [[:start, :end]])
The guy above gave comparison for HashMap / HashSet vs. TreeMap / TreeSet.
I will talk about ArrayList vs. LinkedList:
ArrayList:
get()
add()
ListIterator.add()
or Iterator.remove()
, it will be O(n) to shift all the following elements LinkedList:
get()
add()
ListIterator.add()
or Iterator.remove()
, it will be O(1)you can always use memset:
int myArray[10];
memset( myArray, 0, 10 * sizeof( int ));
http://blueimp.github.com/jQuery-File-Upload/ = great solution
According to their docs, the following browsers support drag & drop:
i wrote a simple function for this:
Function (stringVar param)
(
Local stringVar oneChar := '0';
Local numberVar strLen := Length(param);
Local numberVar index := strLen;
oneChar = param[strLen];
while index > 0 and oneChar = '0' do
(
oneChar := param[index];
index := index - 1;
);
Left(param , index + 1);
)
Use following meta tag in your html header file, This works for me.
<meta http-equiv="Pragma" content="no-cache">
This is not possible, for the sake of keeping Redis simple.
Quoth Antirez, creator of Redis:
Hi, it is not possible, either use a different top-level key for that specific field, or store along with the filed another field with an expire time, fetch both, and let the application understand if it is still valid or not based on current time.
Ask them how they ensure their pages continue to be usable when the user has JavaScript turned off or JavaScript isn't available.
There's no One True Answer, but you're fishing for an answer talking about some strategies for Progressive Enhancement.
Progressive Enhancement consists of the following core principles:
- basic content should be accessible to all browsers
- basic functionality should be accessible to all browsers
- sparse, semantic markup contains all content
- enhanced layout is provided by externally linked CSS
- enhanced behavior is provided by [[Unobtrusive JavaScript|unobtrusive]], externally linked JavaScript
- end user browser preferences are respected
As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:
<?php
$world = _("World");
$str = <<<EOF
<p>Hello</p>
<p>$world</p>
EOF;
echo $str;
?>
a workaround idea that comes to mind is building a class with a magic getter method.
You would declare a class like this:
class Translator
{
public function __get($name) {
return _($name); // Does the gettext lookup
}
}
Initialize an object of the class at some point:
$translate = new Translator();
You can then use the following syntax to do a gettext lookup inside a HEREDOC block:
$str = <<<EOF
<p>Hello</p>
<p>{$translate->World}</p>
EOF;
echo $str;
?>
$translate->World
will automatically be translated to the gettext lookup thanks to the magic getter method.
To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!
, you will have to use the following notation:
$translate->{"Hello World!!!!!!"}
This is all untested but should work.
Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.
You can use extension method, recursion to resolve this problem:
public static bool DeepCompare(this object obj, object another)
{
if (ReferenceEquals(obj, another)) return true;
if ((obj == null) || (another == null)) return false;
//Compare two object's class, return false if they are difference
if (obj.GetType() != another.GetType()) return false;
var result = true;
//Get all properties of obj
//And compare each other
foreach (var property in obj.GetType().GetProperties())
{
var objValue = property.GetValue(obj);
var anotherValue = property.GetValue(another);
if (!objValue.Equals(anotherValue)) result = false;
}
return result;
}
public static bool CompareEx(this object obj, object another)
{
if (ReferenceEquals(obj, another)) return true;
if ((obj == null) || (another == null)) return false;
if (obj.GetType() != another.GetType()) return false;
//properties: int, double, DateTime, etc, not class
if (!obj.GetType().IsClass) return obj.Equals(another);
var result = true;
foreach (var property in obj.GetType().GetProperties())
{
var objValue = property.GetValue(obj);
var anotherValue = property.GetValue(another);
//Recursion
if (!objValue.DeepCompare(anotherValue)) result = false;
}
return result;
}
or compare by using Json (if object is very complex) You can use Newtonsoft.Json:
public static bool JsonCompare(this object obj, object another)
{
if (ReferenceEquals(obj, another)) return true;
if ((obj == null) || (another == null)) return false;
if (obj.GetType() != another.GetType()) return false;
var objJson = JsonConvert.SerializeObject(obj);
var anotherJson = JsonConvert.SerializeObject(another);
return objJson == anotherJson;
}
Try:
var myUrl = "my.aspx?val=%2Fxyz2F";
var decodeUrl = System.Uri.UnescapeDataString(myUrl);
Use an image editor to cut out a portion of the background, then apply CSS's background-repeat property to make the small image fill the area where it is used.
In some cases, background-repeat creates seams where the image repeats. A solution is to use an image editor as follows: starting with the background image, copy the image, flip (mirror, not rotate) the copy left-to-right, and paste it to the right edge of the original, overlapping 1 pixel. Crop to remove 1 pixel from the right edge of the combined image. Now repeat for the vertical: copy the combined image, flip the copy top-to-bottom, paste it to the bottom of the combined, overlapping one pixel. Crop to remove 1 pixel from the bottom. The resulting image should be seam-free.
According to maven website, the last version to support Java 6 is 3.2.5, and 3.3 and up use Java 7. My hunch is that you're using Maven 3.3 or higher, and should either upgrade to Java 7 (and set proper source/target attributes in your pom) or downgrade maven.
select top 1 yr,count(*) from movie
join casting on casting.movieid=movie.id
join actor on casting.actorid = actor.id
where actor.name = 'John Travolta'
group by yr order by 2 desc
I had this same issue and solved it by setting up my ~/.ssh/config file to explicitly use the correct username (i.e. the one you use to login to the server, not your local machine). So, for example:
Host server.hostname User username
I found this blog post helpful: http://www.highlevelbits.com/2007/04/svn-over-ssh-prompts-for-wrong-username.html
In Python 3.8+ you can do
import hashlib
with open("your_filename.txt", "rb") as f:
file_hash = hashlib.md5()
while chunk := f.read(8192):
file_hash.update(chunk)
print(file_hash.digest())
print(file_hash.hexdigest()) # to get a printable str instead of bytes
Consider using hashlib.blake2b
instead of md5
(just replace md5
with blake2b
in the above snippet). It's cryptographically secure and faster than MD5.
While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this
mkdir -p {main,test}/{resources,scala/com/company}
It will create following directory structure under the directory from where it is invoked
+-- main
¦ +-- resources
¦ +-- scala
¦ +-- com
¦ +-- company
+-- test
+-- resources
+-- scala
+-- com
+-- company
The example was taken from this link for creating SBT directory structure
SELECT SUBSTR(TRIM(rtp.role),1,12) AS ROLE
, SUBSTR(rp.grantee,1,16) AS GRANTEE
, SUBSTR(TRIM(rtp.privilege),1,12) AS PRIVILEGE
, SUBSTR(TRIM(rtp.owner),1,12) AS OWNER
, SUBSTR(TRIM(rtp.table_name),1,28) AS TABLE_NAME
, SUBSTR(TRIM(rtp.column_name),1,20) AS COLUMN_NAME
, SUBSTR(rtp.common,1,4) AS COMMON
, SUBSTR(rtp.grantable,1,4) AS GRANTABLE
, SUBSTR(rp.default_role,1,16) AS DEFAULT_ROLE
, SUBSTR(rp.admin_option,1,4) AS ADMIN_OPTION
FROM role_tab_privs rtp
LEFT JOIN dba_role_privs rp
ON (rtp.role = rp.granted_role)
WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
ORDER BY 1
, 2
, 3
, 4
;
SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.
You can also use the new HTML5 custom data- attributes.
<script type="text/javascript">
$(document).ready(function() {
$('.my_button').click(function() {
alert($(this).attr('data-value'));
});
});
</script>
<button class="my_button" name="buttonName" data-value="buttonValue">Button Label</button>
sed 's/[^"]*"\([^"]*\).*/\1/'
does the job.
explanation of the part inside ' '
basically s/search for this/replace with this/ but we're telling him to replace the whole line with just a piece of it we found earlier.
install TypeScript :
npm install typescript
add tsc script to package.json:
"scripts": {
"tsc": "tsc"
},
run this:
npx tsc --init
I am an old hand at programming and came back recently to my old passion and am struggling to fit in this Object oriented, event driven bright new world and while i see the advantages of the non sequential behavior of Javascript there are time where it really get in the way of simplicity and reusability. A simple example I have worked on was to take a photo (Mobile phone programmed in javascript, HTML, phonegap, ...), resize it and upload it on a web site. The ideal sequence is :
All this would be a very simple sequential program if we would have each step returning control to the next one when it is finished, but in reality :
And btw 4 of the 5 steps involve callback functions.
My solution thus is to nest each step in the previous one and use .onload and other similar stratagems, It look something like this :
takeAPhoto(takeaphotocallback(photo) {
photo.onload = function () {
resizePhoto(photo, resizePhotoCallback(photo) {
uploadPhoto(photo, uploadPhotoCallback(status) {
informUserOnOutcome();
});
});
};
loadPhoto(photo);
});
(I hope I did not make too many mistakes bringing the code to it's essential the real thing is just too distracting)
This is I believe a perfect example where async is no good and sync is good, because contrary to Ui event handling we must have each step finish before the next is executed, but the code is a Russian doll construction, it is confusing and unreadable, the code reusability is difficult to achieve because of all the nesting it is simply difficult to bring to the inner function all the parameters needed without passing them to each container in turn or using evil global variables, and I would have loved that the result of all this code would give me a return code, but the first container will be finished well before the return code will be available.
Now to go back to Tom initial question, what would be the smart, easy to read, easy to reuse solution to what would have been a very simple program 15 years ago using let say C and a dumb electronic board ?
The requirement is in fact so simple that I have the impression that I must be missing a fundamental understanding of Javsascript and modern programming, Surely technology is meant to fuel productivity right ?.
Thanks for your patience
Raymond the Dinosaur ;-)
If you are using Linux environment then you can use the PHP's exec command to invoke the linux curl. Here is a sample code, which will make a Asynchronous HTTP post.
function _async_http_post($url, $json_string) {
$run = "curl -X POST -H 'Content-Type: application/json'";
$run.= " -d '" .$json_string. "' " . "'" . $url . "'";
$run.= " > /dev/null 2>&1 &";
exec($run, $output, $exit);
return $exit == 0;
}
This code does not need any extra PHP libs and it can complete the http post in less than 10 milliseconds.
RecyclerView
onBindViewHolder
, No onCreateViewHolder
handling.I show here setting two different RecyclerView
by 1 adapter -
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="listOne"
type="java.util.List"/>
<variable
name="listTwo"
type="java.util.List"/>
<variable
name="onItemClickListenerOne"
type="com.ks.nestedrecyclerbindingexample.callbacks.OnItemClickListener"/>
<variable
name="onItemClickListenerTwo"
type="com.ks.nestedrecyclerbindingexample.callbacks.OnItemClickListener"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
rvItemLayout="@{@layout/row_one}"
rvList="@{listOne}"
rvOnItemClick="@{onItemClickListenerOne}"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
/>
<android.support.v7.widget.RecyclerView
rvItemLayout="@{@layout/row_two}"
rvList="@{listTwo}"
rvOnItemClick="@{onItemClickListenerTwo}"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
/>
</LinearLayout>
</layout>
You can see I pass list, item layout id and click listener from layout.
rvItemLayout="@{@layout/row_one}"
rvList="@{listOne}"
rvOnItemClick="@{onItemClickListenerOne}"
This custom attributes are created by BindingAdapter.
public class BindingAdapters {
@BindingAdapter(value = {"rvItemLayout", "rvList", "rvOnItemClick"}, requireAll = false)
public static void setRvAdapter(RecyclerView recyclerView, int rvItemLayout, List rvList, @Nullable OnItemClickListener onItemClickListener) {
if (rvItemLayout != 0 && rvList != null && rvList.size() > 0)
recyclerView.setAdapter(new GeneralAdapter(rvItemLayout, rvList, onItemClickListener));
}
}
Now from Activity, you pass list, click listener like
HomeActivity.java
public class HomeActivity extends AppCompatActivity {
ActivityHomeBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_home);
binding.setListOne(new ArrayList()); // pass your list or set list from response of API
binding.setListTwo(new ArrayList());
binding.setOnItemClickListenerOne(new OnItemClickListener() {
@Override
public void onItemClick(View view, Object object) {
if (object instanceof ModelParent) {
// TODO: your action here
}
}
});
binding.setOnItemClickListenerTwo(new OnItemClickListener() {
@Override
public void onItemClick(View view, Object object) {
if (object instanceof ModelChild) {
// TODO: your action here
}
}
});
}
}
You can see GeneralAdapter.java
in above repo.
If you have problems while setting up data binding, please see this answer.
I chose System.web.MVC from reference folder and right clicked on it to go property window where I could see version of MVC. This solution works for me. Thanks
I am just wondering why to use some libraries for JWT token decoding and verification at all.
Encoded JWT token can be created using following pseudocode
var headers = base64URLencode(myHeaders);
var claims = base64URLencode(myClaims);
var payload = header + "." + claims;
var signature = base64URLencode(HMACSHA256(payload, secret));
var encodedJWT = payload + "." + signature;
It is very easy to do without any specific library. Using following code:
using System;
using System.Text;
using System.Security.Cryptography;
public class Program
{
// More info: https://stormpath.com/blog/jwt-the-right-way/
public static void Main()
{
var header = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
var claims = "{\"sub\":\"1047986\",\"email\":\"[email protected]\",\"given_name\":\"John\",\"family_name\":\"Doe\",\"primarysid\":\"b521a2af99bfdc65e04010ac1d046ff5\",\"iss\":\"http://example.com\",\"aud\":\"myapp\",\"exp\":1460555281,\"nbf\":1457963281}";
var b64header = Convert.ToBase64String(Encoding.UTF8.GetBytes(header))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
var b64claims = Convert.ToBase64String(Encoding.UTF8.GetBytes(claims))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
var payload = b64header + "." + b64claims;
Console.WriteLine("JWT without sig: " + payload);
byte[] key = Convert.FromBase64String("mPorwQB8kMDNQeeYO35KOrMMFn6rFVmbIohBphJPnp4=");
byte[] message = Encoding.UTF8.GetBytes(payload);
string sig = Convert.ToBase64String(HashHMAC(key, message))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
Console.WriteLine("JWT with signature: " + payload + "." + sig);
}
private static byte[] HashHMAC(byte[] key, byte[] message)
{
var hash = new HMACSHA256(key);
return hash.ComputeHash(message);
}
}
The token decoding is reversed version of the code above.To verify the signature you will need to the same and compare signature part with calculated signature.
UPDATE: For those how are struggling how to do base64 urlsafe encoding/decoding please see another SO question, and also wiki and RFCs
1.
Directory.GetCurrentDirectory();
2.
Thread.GetDomain().BaseDirectory
3.
Environment.CurrentDirectory
I'm not able to comment first answer to your question, but there's a small mistake. You should use parseInt or Math.floor to convert floating point numbers to integer, i
var days, hours, minutes, seconds, x;
x = ms / 1000;
seconds = Math.floor(x % 60);
x /= 60;
minutes = Math.floor(x % 60);
x /= 60;
hours = Math.floor(x % 24);
x /= 24;
days = Math.floor(x);
Personally, I use CoffeeScript in my projects and my code looks like that:
getFormattedTime : (ms)->
x = ms / 1000
seconds = Math.floor x % 60
x /= 60
minutes = Math.floor x % 60
x /= 60
hours = Math.floor x % 24
x /= 24
days = Math.floor x
formattedTime = "#{seconds}s"
if minutes then formattedTime = "#{minutes}m " + formattedTime
if hours then formattedTime = "#{hours}h " + formattedTime
formattedTime
Write below code into your MainActivity file after setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
And below import statement into your java file.
import android.os.StrictMode;
perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/' file1 file2
For those who prefer a bit more practical learning, select the segue in dock, open the attribute inspector and switch between different kinds of segues (dropdown "Kind"). This will reveal options specific for each of them: for example you can see that "present modally" allows you to choose a transition type etc.
In UTF-8:
1 byte: 0 - 7F (ASCII)
2 bytes: 80 - 7FF (all European plus some Middle Eastern)
3 bytes: 800 - FFFF (multilingual plane incl. the top 1792 and private-use)
4 bytes: 10000 - 10FFFF
In UTF-16:
2 bytes: 0 - D7FF (multilingual plane except the top 1792 and private-use )
4 bytes: D800 - 10FFFF
In UTF-32:
4 bytes: 0 - 10FFFF
10FFFF is the last unicode codepoint by definition, and it's defined that way because it's UTF-16's technical limit.
It is also the largest codepoint UTF-8 can encode in 4 byte, but the idea behind UTF-8's encoding also works for 5 and 6 byte encodings to cover codepoints until 7FFFFFFF, ie. half of what UTF-32 can.
Simply running /bin/bash --login
did the trick for me, weirdly. Can't explain it.
For concatenating selectors together when nesting, you need to use the parent selector (&
):
.class {
margin:20px;
&:hover {
color:yellow;
}
}
Had the same issue but mine was working for weeks before this. Realised I had changed my password on the server.
Remember to update your password if you've got the option selected 'Run whether user is logged on or not'
To fully answer this question in 2020, let me quote several statements from official Python docs:
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order.
Changed in version 3.8: Dictionaries are now reversible.
Dictionaries and dictionary views are reversible.
A statement regarding OrderedDict vs Dict:
Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).
Your problem is that you have declare twice the exec-maven-plugin :
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-
integration\src\main\java\example\Main< /mainClass>
</configuration>
</plugin>
...
< plugin>
< groupId>org.codehaus.mojo</groupId>
< artifactId>exec-maven-plugin</artifactId>
< version>1.2</version>
< /plugin>
You could specify the dtype directly when constructing the DataFrame:
>>> df = pd.DataFrame(index=range(0,4),columns=['A'], dtype='float')
>>> df.dtypes
A float64
dtype: object
Specifying the dtype forces Pandas to try creating the DataFrame with that type, rather than trying to infer it.
You can create an extension method that you can call on any IEnumerable:
public static string JoinStrings<T>(
this IEnumerable<T> values, string separator)
{
var stringValues = values.Select(item =>
(item == null ? string.Empty : item.ToString()));
return string.Join(separator, stringValues.ToArray());
}
Then you can just call the method on the original list:
string commaSeparated = myList.JoinStrings(", ");
$('.update-cart').click(function(e) {
updateCartWidget();
e.stopPropagation();
e.preventDefault();
});
$('.update-cart').click(function() {
updateCartWidget();
return false;
});
The following methods achieve the exact same thing.
I got this when I accidentally passed too many parameters into a jquery function that only expected one callback parameter.
For others troubleshooting: make sure you check all your jquery function calls for extra parameters.
Something like this lets you test your procedure on almost any client:
DECLARE
v_cur SYS_REFCURSOR;
v_a VARCHAR2(10);
v_b VARCHAR2(10);
BEGIN
your_proc(v_cur);
LOOP
FETCH v_cur INTO v_a, v_b;
EXIT WHEN v_cur%NOTFOUND;
dbms_output.put_line(v_a || ' ' || v_b);
END LOOP;
CLOSE v_cur;
END;
Basically, your test harness needs to support the definition of a SYS_REFCURSOR
variable and the ability to call your procedure while passing in the variable you defined, then loop through the cursor result set. PL/SQL does all that, and anonymous blocks are easy to set up and maintain, fairly adaptable, and quite readable to anyone who works with PL/SQL.
Another, albeit similar way would be to build a named procedure that does the same thing, and assuming the client has a debugger (like SQL Developer, PL/SQL Developer, TOAD, etc.) you could then step through the execution.
If I remember correctly (from a couple of years ago), one of the senior developers was talking about a fast way to bzero() on PowerPC (specs said we needed to zero almost all the memory on power up). It might not translate well (if at all) to x86, but it could be worth exploring.
The idea was to load a data cache line, clear that data cache line, and then write the cleared data cache line back to memory.
For what it is worth, I hope it helps.
I am using JQuery > 1.8 and this works for me...
$('#dropDownId').attr('disabled', true);
A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.
If you are on Windows, you can use the CreateThreadpoolTimer function to schedule a callback without needing to worry about thread management and without blocking the current thread.
template<typename T>
static void __stdcall timer_fired(PTP_CALLBACK_INSTANCE, PVOID context, PTP_TIMER timer)
{
CloseThreadpoolTimer(timer);
std::unique_ptr<T> callable(reinterpret_cast<T*>(context));
(*callable)();
}
template <typename T>
void call_after(T callable, long long delayInMs)
{
auto state = std::make_unique<T>(std::move(callable));
auto timer = CreateThreadpoolTimer(timer_fired<T>, state.get(), nullptr);
if (!timer)
{
throw std::runtime_error("Timer");
}
ULARGE_INTEGER due;
due.QuadPart = static_cast<ULONGLONG>(-(delayInMs * 10000LL));
FILETIME ft;
ft.dwHighDateTime = due.HighPart;
ft.dwLowDateTime = due.LowPart;
SetThreadpoolTimer(timer, &ft, 0 /*msPeriod*/, 0 /*msWindowLength*/);
state.release();
}
int main()
{
auto callback = []
{
std::cout << "in callback\n";
};
call_after(callback, 1000);
std::cin.get();
}
For me it worked when on the right tab > Localization, I checked English check box. Initially only Base was checked. After that I had no more problems. Hope this helps!
Just to clarify things:
$('#checkbox_ID').is(":checked")
Will return 'true' or 'false'
You can change or import a theme by using the icon that the "Duplicate Theme" arrow is pointing to in the photo.
Every one sees color differently. Most times a small change in contrast is all you need. Removing the hase from Dracula by changing the Background color to 242527 was perfect for me.
You need to use $_POST
not $_post
.
This code using merge and convert 200 dbi
static void Main(string[] args)
{ Path string Outputpath = @"C:\Users\MDASARATHAN\Desktop\TX_HARDIN_10-01-2016_K";
string[] TotalFiles = Directory.GetFiles(Outputpath, "*.tif", SearchOption.AllDirectories);
foreach (string filename in TotalFiles)
{
Bitmap bitmap = (Bitmap)Image.FromFile(filename);
string ExportFilename = string.Empty;
int Pagecount = 0;
bool bFirstImage = true;
bitmap.SetResolution(200, 200);
ExportFilename = Path.GetDirectoryName(filename) + "\\" + Path.GetFileName(filename)+"f";
MemoryStream byteStream = new MemoryStream();
Pagecount = bitmap.GetFrameCount(FrameDimension.Page);
if (bFirstImage)
{
bitmap.Save(byteStream, ImageFormat.Tiff);
bFirstImage = false;
} Image tiff = Image.FromStream(byteStream);
ImageCodecInfo encoderInfo = ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");
EncoderParameters encoderParams = new EncoderParameters(2);
EncoderParameter parameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4);
encoderParams.Param[0] = parameter;
parameter = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame);
encoderParams.Param[1] = parameter;
// bitmap.Dispose();
try
{
tiff.Save(ExportFilename, encoderInfo, encoderParams);
}
catch (Exception ex)
{
}
EncoderParameters EncoderParams = new EncoderParameters(2);
EncoderParameter SaveEncodeParam = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage);
EncoderParameter CompressionEncodeParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4);
EncoderParams.Param[0] = CompressionEncodeParam;
EncoderParams.Param[1] = SaveEncodeParam;
if (bFirstImage == false)
{
for (int i = 1; i < Pagecount; i++)
{
//bitmap = (Bitmap)Image.FromFile(filenames);
byteStream = new MemoryStream();
bitmap.SelectActiveFrame(FrameDimension.Page, i);
bitmap.Save(byteStream, ImageFormat.Tiff);
bitmap.SetResolution(200, 200);
tiff.SaveAdd(bitmap, EncoderParams);
}
} SaveEncodeParam = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush);
EncoderParams = new EncoderParameters(1);
EncoderParams.Param[0] = SaveEncodeParam;
tiff.SaveAdd(EncoderParams);
tiff.Dispose();
bitmap.Dispose();
File.Delete(filename);
}
}
According to the stack trace:
Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/ProxyObject at java.lang.ClassLoader.defineClass1(Native Method)
The issue is caused by "java.lang.NoClassDefFoundError", so I think you should focus on this.
The direct solution is to add dependency
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
to your pom.xml.
Number(1).toFixed(2); // 1.00
Number(1.341).toFixed(2); // 1.34
Number(1.345).toFixed(2); // 1.34 NOTE: See andy's comment below.
Number(1.3450001).toFixed(2); // 1.35
document.getElementById('line1').innerHTML = Number(1).toFixed(2);_x000D_
document.getElementById('line2').innerHTML = Number(1.341).toFixed(2);_x000D_
document.getElementById('line3').innerHTML = Number(1.345).toFixed(2);_x000D_
document.getElementById('line4').innerHTML = Number(1.3450001).toFixed(2);
_x000D_
<span id="line1"></span>_x000D_
<br/>_x000D_
<span id="line2"></span>_x000D_
<br/>_x000D_
<span id="line3"></span>_x000D_
<br/>_x000D_
<span id="line4"></span>
_x000D_
I don't understand how to apply your solution :( – kalmanIsAGameChanger
Working with Arduino Sketch, I had a function causing my warnings.
Original function: char StrContains(char *str, char *sfind)
To stop the warnings I added the const in front of the char *str and the char *sfind.
Modified: char StrContains(const char *str, const char *sfind).
All warnings went away.
PJL is right. I have used his suggestion and this is what i have done:
defined global variables for fragment:
private final Object attachingActivityLock = new Object();
private boolean syncVariable = false;
implemented
@Override public void onAttach(Activity activity) { super.onAttach(activity); synchronized (attachingActivityLock) { syncVariable = true; attachingActivityLock.notifyAll(); } }
3 . I wrapped up my function, where I need to call getActivity(), in thread, because if it would run on main thread, i would block the thread with the step 4. and onAttach() would never be called.
Thread processImage = new Thread(new Runnable() {
@Override
public void run() {
processImage();
}
});
processImage.start();
4 . in my function where I need to call getActivity(), I use this (before the call getActivity())
synchronized (attachingActivityLock) {
while(!syncVariable){
try {
attachingActivityLock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If you have some UI updates, remember to run them on UI thread. I need to update ImgeView so I did:
image.post(new Runnable() {
@Override
public void run() {
image.setImageBitmap(imageToShow);
}
});
In a hacky way it can be done for channels which one attempts to write to by recovering the raised panic. But you cannot check if a read channel is closed without reading from it.
Either you will
v <- c
)v, ok <- c
)v, ok <- c
)v <- c
)Only the last one technically doesn't read from the channel, but that's of little use.
Looking at the question, ftell
can easily get the number of bytes.
long size = ftell(FILENAME);
printf("total size is %ld bytes",size);
You can get it writing less without external libraries:
String hex = (new HexBinaryAdapter()).marshal(md5.digest(YOUR_STRING.getBytes()))
Update April 2019
jQuery isn't needed for cookie reading/manipulation, so don't use the original answer below.
Go to https://github.com/js-cookie/js-cookie instead, and use the library there that doesn't depend on jQuery.
Basic examples:
// Set a cookie
Cookies.set('name', 'value');
// Read the cookie
Cookies.get('name') => // => 'value'
See the docs on github for details.
Before April 2019 (old)
See the plugin:
https://github.com/carhartl/jquery-cookie
You can then do:
$.cookie("test", 1);
To delete:
$.removeCookie("test");
Additionally, to set a timeout of a certain number of days (10 here) on the cookie:
$.cookie("test", 1, { expires : 10 });
If the expires option is omitted, then the cookie becomes a session cookie and is deleted when the browser exits.
To cover all the options:
$.cookie("test", 1, {
expires : 10, // Expires in 10 days
path : '/', // The value of the path attribute of the cookie
// (Default: path of page that created the cookie).
domain : 'jquery.com', // The value of the domain attribute of the cookie
// (Default: domain of page that created the cookie).
secure : true // If set to true the secure attribute of the cookie
// will be set and the cookie transmission will
// require a secure protocol (defaults to false).
});
To read back the value of the cookie:
var cookieValue = $.cookie("test");
You may wish to specify the path parameter if the cookie was created on a different path to the current one:
var cookieValue = $.cookie("test", { path: '/foo' });
UPDATE (April 2015):
As stated in the comments below, the team that worked on the original plugin has removed the jQuery dependency in a new project (https://github.com/js-cookie/js-cookie) which has the same functionality and general syntax as the jQuery version. Apparently the original plugin isn't going anywhere though.
I'd also suggest moving the event handler outside render.
var OnSubmitTest = React.createClass({
submit: function(e){
e.preventDefault();
alert('it works!');
}
render: function() {
return (
<form onSubmit={this.submit}>
<button>Click me</button>
</form>
);
}
});
You should try this syntax - assuming you want to have @OrderID
as a parameter for your stored procedure:
CREATE PROCEDURE dbo.YourStoredProcNameHere
@OrderID INT
AS
BEGIN
DECLARE @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SELECT @OrderItemID = OrderItemID
FROM [OrderItem]
WHERE OrderID = @OrderID
SELECT @AppointmentID = AppoinmentID
FROM [Appointment]
WHERE OrderID = @OrderID
SELECT @PurchaseOrderID = PurchaseOrderID
FROM [PurchaseOrder]
WHERE OrderID = @OrderID
END
OF course, that only works if you're returning exactly one value (not multiple values!)
So, by unset'ting the array index 2, you essentially remove that element in the array and decrement the array size (?).
I made my own test..
foo=(5 6 8)
echo ${#foo[*]}
unset foo
echo ${#foo[*]}
Which results in..
3
0
So just to clarify that unset'ting the entire array will in fact remove it entirely.
Do note that on newer Apache versions the RewriteLog
and RewriteLogLevel
have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):
AH00526: Syntax error on line xx of path/to/config/file.conf: Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`
Instead, you're now supposed to use the general LogLevel
directive, with a level of trace1
up to trace8
. 'debug' didn't display any rewrite messages in the log for me.
Example: LogLevel warn rewrite:trace3
For the official documentation, see here.
Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.
You forgot the C: after the file:///
This works for me
<!DOCTYPE html>
<html>
<head>
<title>Experiment</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
html,body { width: 100%; height: 100%; }
</style>
</head>
<body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
</body>
</html>
I made a librairy to make Hexadecimal / Decimal conversion without the use of stdio.h
. Very simple to use :
unsigned hexdec (const char *hex, const int s_hex);
Before the first conversion intialize the array used for conversion with :
void init_hexdec ();
Here the link on github : https://github.com/kevmuret/libhex/
Do you mean like this?
var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);
To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll()
to accomplish this:
HTML
<div class="abc"></div>
<div class="abc"></div>
JS
var abcElements = document.querySelectorAll('.abc');
// Set their ids
for (var i = 0; i < abcElements.length; i++)
abcElements[i].id = 'abc-' + i;
This will assign the ID 'abc-<index number>'
to each element. So it would come out like this:
<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>
To create an element and assign an id
we can use document.createElement()
and then appendChild()
.
var div = document.createElement('div');
div.id = 'hello1';
var body = document.querySelector('body');
body.appendChild(div);
Update
You can set the id
on your element like this if your script is in your HTML file.
<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">
<script type="text/javascript">
var s = document.getElementsByClassName('assign-me')[0];
s.id = btoa({{str(produit["avt"]["fto"])}});
</script>
Your requirements still aren't 100% clear though.
Escape single quote with an additional single as Kirtan pointed out
And if you are trying to execute a dynamic sql (which is not a good idea in the first place) via sp_executesql then the below code would work for you
sp_executesql N'INSERT INTO SomeTable (SomeColumn) VALUES (''John''''s'')'
If you want to keep your CustomView
and its xib
independent of File's Owner
, then follow these steps
File's Owner
field empty.xib
file of your CustomView
and set its Custom Class
as CustomView
(name of your custom view class)IBOutlet
in .h
file of your custom view..xib
file of your custom view, click on view and go in Connection Inspector
. Here you will all your IBOutlets which you define in .h
filein .m
file of your CustomView
class, override the init
method as follow
-(CustomView *) init{
CustomView *result = nil;
NSArray* elements = [[NSBundle mainBundle] loadNibNamed: NSStringFromClass([self class]) owner:self options: nil];
for (id anObject in elements)
{
if ([anObject isKindOfClass:[self class]])
{
result = anObject;
break;
}
}
return result;
}
Now when you want to load your CustomView
, use the following line of code
[[CustomView alloc] init];
In javascript there are no block-level scopes
only function-level scopes
:
Read this article about javaScript Scoping and Hoisting.
var deferred = $q.defer();
deferred.count = i;
console.log(deferred.count); // 0,1,2,3,4,5 --< all deferred objects
// some code
.success(function(data){
console.log(deferred.count); // 5,5,5,5,5,5 --< only the last deferred object
deferred.resolve(data);
})
var deferred= $q.defer();
inside a for loop it's hoisted to the top of the function, it means that javascript declares this variable on the function scope outside of the for loop
.closure scope
even after functions are executed.angular.forEach
:Here is a demo plunker: http://plnkr.co/edit/NGMp4ycmaCqVOmgohN53?p=preview
UploadService.uploadQuestion = function(questions){
var promises = [];
angular.forEach(questions , function(question) {
var promise = $http({
url : 'upload/question',
method: 'POST',
data : question
});
promises.push(promise);
});
return $q.all(promises);
}
Array#map
:Here is a demo plunker: http://plnkr.co/edit/KYeTWUyxJR4mlU77svw9?p=preview
UploadService.uploadQuestion = function(questions){
var promises = questions.map(function(question) {
return $http({
url : 'upload/question',
method: 'POST',
data : question
});
});
return $q.all(promises);
}
It's a bit late, but I think your problem was your URL. If instead of
http://127.0.0.1:8080/test.html?target=bob
you had
http://127.0.0.1:8080/test.html#/?target=bob
I'm pretty sure it would have worked. Angular is really picky about its #/
It means you're passing the variable by reference.
In fact, in a declaration of a type, it means reference, just like:
int x = 42;
int& y = x;
declares a reference to x
, called y
.
Here is a VBA approach:
Sub change()
toText Sheets(1).Range("A1:F20")
End Sub
Sub toText(target As Range)
Dim cell As Range
For Each cell In target
cell.Value = cell.Text
cell.NumberFormat = "@"
Next cell
End Sub
If you are looking for a solution without programming, the Question should be moved to SuperUser.
Flushing the output buffers:
printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is
or
fprintf(fd, "Buffered, will be flushed");
fflush(fd); //Prints to a file
Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf()
it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf
something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.
Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf()
, so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.
I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf()
is an expensive operation (which is why it doesn't by default flush the buffer).
As far as flushing the input buffer (stdin
), you should not do that. Flushing stdin
is undefined behavior according to the C11 standard §7.21.5.2 part 2:
If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.
On some systems, Linux being one as you can see in the man page for fflush()
, there's a defined behavior but it's system dependent so your code will not be portable.
Now if you're worried about garbage "stuck" in the input buffer you can use fpurge()
on that.
See here for more on fflush()
and fpurge()
If you are on Windows and have Visual Studio installed you might have something in your PATH that is pointing to an old version of TypeScript. I found that removing the folder "C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\" from my PATH (or deleting/renaming this folder) will allow the more recent npm globally installed TypeScript version of tsc to work.
Try below :
DECLARE @myDateTime DATETIME
SET @myDateTime = '2013-02-02'
-- Convert to string now
SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)
Update: The project is EOL and not maintained anymore. He recommends switching to the Browscap project.
You can use the bitwalker useragentutils library: https://github.com/HaraldWalker/user-agent-utils. It will provide you information about the Browser (name, type, version, manufacturer, etc.) and about the OperatingSystem. A good thing about it is that it is maintained. Access the link that I have provided to see the Maven dependency that you need to add to you project in order to use it.
See below sample code that returns the browser name and browser version.
UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
Browser browser = userAgent.getBrowser();
String browserName = browser.getName();
//or
// String browserName = browser.getGroup().getName();
Version browserVersion = userAgent.getBrowserVersion();
System.out.println("The user is using browser " + browserName + " - version " + browserVersion);
Perhaps the best way to explain it is with an example:
git checkout master && git pull
. Master is already up to date.git checkout master && git pull
. Master is already up to date.git merge topic-branch-A
git merge topic-branch-B
git push origin master
before Alicegit push origin master
, which is rejected because it's not a fast-forward merge.git pull --rebase origin master
git push origin master
, and everyone is happy they don't have to read a useless merge commit when they look at the logs in the future.Note that the specific branch being merged into is irrelevant to the example. Master in this example could just as easily be a release branch or dev branch. The key point is that Alice & Bob are simultaneously merging their local branches to a shared remote branch.
TL;DR: The only 100% correct method is to check for @-sign somewhere in the entered email address and then posting a validation message to given email address. If they can follow validation instructions in the email message, the inputted email address is correct.
Long answer:
David Gilbertson wrote about this years ago:
There are two questions we need to ask:
- Did the user understand that they were supposed to type an email address into this field?
- Did the user correctly type their own email address into this field?
If you have a well laid-out form with a label that says “email”, and the user enters an ‘@’ symbol somewhere, then it’s safe to say they understood that they were supposed to be entering an email address. Easy.
Next, we want to do some validation to ascertain if they correctly entered their email address.
Not possible.
[...]
Any mistype will definitely result in an incorrect email address, but only maybe result in an invalid email address.
[...]
There is no point in trying to work out if an email address is ‘valid’. A user is far more likely to enter a wrong and valid email address than they are to enter an invalid one.
In other words, it's important to notice that any kind of string based validation can only check if the syntax is invalid. It cannot check if the user can actually see the email (e.g. because the user already lost credentials, typed address of somebody else or typed work email instead of personal email address for a given use case). How often the question you're really after is "is this email syntactically valid" instead of "can I communicate with the user using given email address"? If you validate the string more than "does it contain @
", you're trying to answer the former question! Personally, I'm always interested about the latter question only.
In addition, some email addresses that may be syntactically or politically invalid, do work. For example, postmaster@ai
does technically work even though TLDs should not have MX records. Also see discussion about email validation on the WHATWG mailing list (where HTML5 is designed in the first place).
Oracle specific, and doesn't rely on pre-existing large tables or complicated system views over data dictionary objects.
SELECT c1 from dual
MODEL DIMENSION BY (1 as rn) MEASURES (sysdate as c1)
RULES ITERATE (365)
(c1[ITERATION_NUMBER]=SYSDATE-ITERATION_NUMBER)
order by 1
Resolved the issue... you need to add the ssh public key to your github account.
ssh-keygen
~/.ssh/id_rsa
)~/.ssh/id_rsa.pub
) to github account git clone
. It works!
Initial status (public key not added to git hub account)
foo@bn18-251:~$ rm -rf test foo@bn18-251:~$ ls foo@bn18-251:~$ git clone [email protected]:devendra-d-chavan/test.git Cloning into 'test'... Permission denied (publickey). fatal: The remote end hung up unexpectedly foo@bn18-251:~$
Now, add the public key ~/.ssh/id_rsa.pub
to the github account (I used cat ~/.ssh/id_rsa.pub
)
foo@bn18-251:~$ ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/home/foo/.ssh/id_rsa): Created directory '/home/foo/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/foo/.ssh/id_rsa. Your public key has been saved in /home/foo/.ssh/id_rsa.pub. The key fingerprint is: xxxxx The key's randomart image is: +--[ RSA 2048]----+ xxxxx +-----------------+ foo@bn18-251:~$ cat ./.ssh/id_rsa.pub xxxxx foo@bn18-251:~$ git clone [email protected]:devendra-d-chavan/test.git Cloning into 'test'... The authenticity of host 'github.com (207.97.227.239)' can't be established. RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'github.com,207.97.227.239' (RSA) to the list of known hosts. Enter passphrase for key '/home/foo/.ssh/id_rsa': warning: You appear to have cloned an empty repository. foo@bn18-251:~$ ls test foo@bn18-251:~/test$ git status # On branch master # # Initial commit # nothing to commit (create/copy files and use "git add" to track)
To get all the values from a list of dictionaries, use the following code :
list = [{'text': 1, 'b': 2}, {'text': 3, 'd': 4}, {'text': 5, 'f': 6}]
subtitle=[]
for value in list:
subtitle.append(value['text'])
you can update your war from the command line using java commands as mentioned here:
jar -uvf test.war yourclassesdir
Other useful commands:
Command to unzip/explode the war file
jar -xvf test.war
Command to create the war file
jar -cvf test.war yourclassesdir
Eg:
jar -cvf test.war *
jar -cvf test.war WEB-INF META-INF
Splice is the best to remove element from specific index. The given example is tested on console.
card = [1, 2, 3, 4];
card.splice(1,1); // [2]
card // (3) [1, 3, 4]
splice(startingIndex, totalNumberOfElements)
startingIndex start from 0.
Add the following line to the beginning script1.py
#!/usr/bin/env python
and then make the script executable:
$ chmod +x script1.py
If the script resides in a directory that appears in your PATH
variable, you can simply type
$ script1.py
Otherwise, you'll need to provide the full path (either absolute or relative). This includes the current working directory, which should not be in your PATH
.
$ ./script1.py
It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.
I finally made it. I was able to install AppFabric for Win Server 2012 R2. I am not really sure what exact change made it worked. I saw and tried many many solutions from various websites but above solution of making changes to Registry - 'HKEY_CLASSES_ROOT'worked (please think twice before making changes to Registry on production environment - this was my demo environment so I just went ahead); I changed the temporary folder path but it did not worked first time. Then I deleted the registry entry and then uninstalled AppFabric 1.1 pre-installed instance from Control panel. Then I tried Installation and it worked. This also restored the Registry entry.
On my MAC I got it working:
add to .bash_profile
code() {
open -a Visual\ Studio\ Code.app $1
}
save and in terminal 'source .bash_profile'
Then in terminal code index.html (or whatever) will open that file in VS Code.
Here is what it worked for me.. I wanted to create a hello world java application with gradle with the following requirements.
Here is the solution :
gradle init --type java-application
Runnable fat Jar
task fatJar(type: Jar) {
clean
println("Creating fat jar")
manifest {
attributes 'Main-Class': 'com.abc.gradle.hello.App'
}
archiveName "${runnableJar}"
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
} with jar
println("Fat jar is created")
}
Copy Dependencies
task copyDepends(type: Copy) {
from configurations.default
into "${dependsDir}"
}
Create jar with classpath dependecies in manifest
task createJar(type: Jar) {
println("Cleaning...")
clean
manifest {
attributes('Main-Class': 'com.abc.gradle.hello.App',
'Class-Path': configurations.default.collect { 'dependencies/' +
it.getName() }.join(' ')
)
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
} with jar
println "${outputJar} created"
}
Here is the complete build.gradle
plugins {
id 'java'
id 'application'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.slf4j:slf4j-api:1.7.30'
implementation 'ch.qos.logback:logback-classic:1.2.3'
implementation 'ch.qos.logback:logback-core:1.2.3'
testImplementation 'junit:junit:4.13'
}
def outputJar = "${buildDir}/libs/${rootProject.name}.jar"
def dependsDir = "${buildDir}/libs/dependencies/"
def runnableJar = "${rootProject.name}_fat.jar";
//Create runnable fat jar
task fatJar(type: Jar) {
clean
println("Creating fat jar")
manifest {
attributes 'Main-Class': 'com.abc.gradle.hello.App'
}
archiveName "${runnableJar}"
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
} with jar
println("Fat jar is created")
}
//Copy dependent libraries to directory.
task copyDepends(type: Copy) {
from configurations.default
into "${dependsDir}"
}
//Create runnable jar with dependencies
task createJar(type: Jar) {
println("Cleaning...")
clean
manifest {
attributes('Main-Class': 'com.abc.gradle.hello.App',
'Class-Path': configurations.default.collect { 'dependencies/' +
it.getName() }.join(' ')
)
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
} with jar
println "${outputJar} created"
}
Gradle build commands
Create fat jar : gradle fatJar
Copy dependencies : gradle copyDepends
Create runnable jar with dependencies : gradle createJar
More details can be read here : https://jafarmlp.medium.com/a-simple-java-project-with-gradle-2c323ae0e43d
If you have multiple databases for testing and development this might help
development:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
test:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
production:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
By default, the DirectoryIndex is set to:
DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml
Apache will look for each of the above files, in order, and serve the first one it finds when a visitor requests just a directory. If the webserver finds no files in the current directory that match names in the DirectoryIndex directive, then a directory listing will be displayed to the browser, showing all files in the current directory.
The order should be DirectoryIndex index.html index.php
// default is index.html
Reference: Here.
I wasn't able to use Model::truncate()
as it would error:
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint
And unfortunately Model::delete()
doesn't work (at least in Laravel 5.0):
Non-static method Illuminate\Database\Eloquent\Model::delete() should not be called statically, assuming $this from incompatible context
But this does work:
(new Model)->newQuery()->delete()
That will soft-delete all rows, if you have soft-delete set up. To fully delete all rows including soft-deleted ones you can change to this:
(new Model)->newQueryWithoutScopes()->forceDelete()
You cannot undo the latest git add, but you can undo all add
s since the last commit. git reset
without a commit argument resets the index (unstages staged changes):
git reset
myWebView.setAlpha(0);
is the best answer. It works!
Easiest implementation.
<script>
$( ".selectpicker" ).change(function() {
alert( "Handler for .change() called." );
});
</script>
It looks to me as though the basic problem is that you have one wait()
call rather than a loop that waits until there are no more children. You also only wait if the last fork()
is successful rather than if at least one fork()
is successful.
You should only use _exit()
if you don't want normal cleanup operations - such as flushing open file streams including stdout
. There are occasions to use _exit()
; this is not one of them. (In this example, you could also, of course, simply have the children return instead of calling exit()
directly because returning from main()
is equivalent to exiting with the returned status. However, most often you would be doing the forking and so on in a function other than main()
, and then exit()
is often appropriate.)
Hacked, simplified version of your code that gives the diagnostics I'd want. Note that your for
loop skipped the first element of the array (mine doesn't).
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(void)
{
pid_t child_pid, wpid;
int status = 0;
int i;
int a[3] = {1, 2, 1};
printf("parent_pid = %d\n", getpid());
for (i = 0; i < 3; i++)
{
printf("i = %d\n", i);
if ((child_pid = fork()) == 0)
{
printf("In child process (pid = %d)\n", getpid());
if (a[i] < 2)
{
printf("Should be accept\n");
exit(1);
}
else
{
printf("Should be reject\n");
exit(0);
}
/*NOTREACHED*/
}
}
while ((wpid = wait(&status)) > 0)
{
printf("Exit status of %d was %d (%s)\n", (int)wpid, status,
(status > 0) ? "accept" : "reject");
}
return 0;
}
Example output (MacOS X 10.6.3):
parent_pid = 15820
i = 0
i = 1
In child process (pid = 15821)
Should be accept
i = 2
In child process (pid = 15822)
Should be reject
In child process (pid = 15823)
Should be accept
Exit status of 15823 was 256 (accept)
Exit status of 15822 was 0 (reject)
Exit status of 15821 was 256 (accept)
This registry fix worked like a charm on my Windows 7 x64 setup: http://codearetoy.wordpress.com/2010/12/23/jdk-not-found-on-installing-android-sdk/
Try this if the above solution aren't working, worked for me
Cut the whole contents in the worksheet using "Ctrl + A" followed by "Ctrl + X" and paste it to a new sheet. Your reference to formulas will remain intact when you cut paste.
In SSMS:
Now, this will drop everything, including the database. Make sure to remove the code for the items you don't want dropped. Alternatively, in the "Choose Objects" section, instead of selecting to script entire database just select the items you want to remove.
In javascript (node.js) this works for me:
describe('UI', function() {
describe('gets results from Bing', function() {
this.timeout(10000);
it('makes a search', function(done) {
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
driver.get('http://bing.com');
var input = driver.findElement(webdriver.By.name('q'));
input.sendKeys('something');
input.sendKeys(webdriver.Key.ENTER);
driver.wait(function() {
driver.findElement(webdriver.By.className('sb_count')).
getText().
then(function(result) {
console.log('result: ', result);
done();
});
}, 8000);
});
});
});
For tab use webdriver.Key.TAB
Today, I would recommend using Task.CompletedTask to accomplish this.
Pre .net 4.6:
Using Task.FromResult(0)
or Task.FromResult<object>(null)
will incur less overhead than creating a Task
with a no-op expression. When creating a Task
with a result pre-determined, there is no scheduling overhead involved.
You need to define the button text and have valid HTML for the button. I would also suggest using .on
for the click handler of the button
$(function () {_x000D_
$('#Add').on('click', function () {_x000D_
$('<p>Text</p>').appendTo('#Content');_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="Content">_x000D_
<button id="Add">Add Text</button>_x000D_
</div>
_x000D_
Also I would make sure the jquery is at the bottom of the page just before the closing </body>
tag. Doing so will make it so you do not have to have the whole thing wrapped in $(function
but I would still do that. Having your javascript load at the end of the page makes it so the rest of the page loads incase there is a slow down in your javascript somewhere.
There is no need to write any code, just in cmd on the console you can write:
javac myFile.java
java ClassName > a.txt
The output data is stored in the a.txt file.
In our case git
had to be installed on the Jenkins server.
Perl files are scripts, not executable programs. Therefore, for them to 'run', they are going to need an interpreter.
So, you have two choices: 1) Have the interpreter on the machine that you wish to run the script, or 2) Have the script running on a networked (or Internet) machine that you remotely connect to (ie with a browser)
Try svn revert filename
for every file you don't need and haven't yet committed. Or alternatively do svn revert -R folder
for the problematic folder and then re-do the operation with correct ignoring configuration.
you can undo any scheduling operations:
$ svn add mistake.txt whoops
A mistake.txt
A whoops
A whoops/oopsie.c
$ svn revert mistake.txt whoops
Reverted mistake.txt
Reverted whoops
Extract all gz files in current directory and its subdirectories:
find . -name "*.gz" | xargs gunzip
If you want certain element to completely loaded, Use ng-init on that element .
e.g. <div class="modal fade" id="modalFacultyInfo" role="dialog" ng-init="initModalFacultyInfo()"> ..</div>
the initModalFacultyInfo() function should exist in the controller.
Here's what I currently use. The triple comment ( / * / * / * ) is for an integration that picks out header comments from the object definition.
/*/*/*
Name: pr_ProcName
Author: Joe Smith
Written: 6/15/16
Purpose: Short description about the proc.
Edit History: 6/15/16 - Joe Smith
+ Initial creation.
6/22/16 - Jaden Smith
+ Change source to blahblah
+ Optimized JOIN
6/30/16 - Joe Smith
+ Reverted changes made by Jaden.
*/*/*/
In C++11 and beyond, you can use the back
member function:
char ch = myStr.back();
In C++03, std::string::back
is not available due to an oversight, but you can get around this by dereferencing the reverse_iterator
you get back from rbegin
:
char ch = *myStr.rbegin();
In both cases, be careful to make sure the string actually has at least one character in it! Otherwise, you'll get undefined behavior, which is a Bad Thing.
Hope this helps!
By default git diff is used to show the changes which is not added to the list of git updated files. But if you want to show the changes which is added or stagged then you need to provide extra options that will let git know that you are interested in stagged or added files diff .
$ git diff # Default Use
$ git diff --cached # Can be used to show difference after adding the files
$ git diff --staged # Same as 'git diff --cached' mostly used with latest version of git
Example
$ git diff
diff --git a/x/y/z.js b/x/y/z.js index 98fc22b..0359d84 100644
--- a/x/y/z.js
+++ b/x/y/z.js @@ -43,7 +43,7 @@ var a = function (tooltip) {
- if (a)
+ if (typeof a !== 'undefined')
res = 1;
else
res = 2;
$ git add x/y/z.js
$ git diff
$
Once you added the files , you can't use default of 'git diff' .You have to do like this:-
$ git diff --cached
diff --git a/x/y/z.js b/x/y/z.js index 98fc22b..0359d84 100644
--- a/x/y/z.js
+++ b/x/y/z.js @@ -43,7 +43,7 @@ var a = function (tooltip) {
- if (a)
+ if (typeof a !== 'undefined')
res = 1;
else
res = 2;
You cannot directly access the table with the name 'customer'. Either it should be 'user1.customer' or create a synonym 'customer' for user2 pointing to 'user1.customer'. hope this helps..
Actually, you can try to use boost library,I think std::string doesn't supply enough method to do all the common string operation.In boost,you can just use the boost::algorithm::contains
:
#include <string>
#include <boost/algorithm/string.hpp>
int main() {
std::string s("gengjiawen");
std::string t("geng");
bool b = boost::algorithm::contains(s, t);
std::cout << b << std::endl;
return 0;
}
Should the benchmark measure time/iteration or iterations/time, and why?
It depends on what you are trying to test.
If you are interested in latency, use time/iteration and if you are interested in throughput, use iterations/time.
{=FIND("cell I want to search","list of words I want to search for")}
{=SUM(FIND($A$1:$A$100&"|";A3))}
this ensures spreadsheet will compare strings like "cellvlaue|" againts "pattern1|", "pattern2|" etc. which sorts out conflicts like pattern1="newly added", pattern2="added" (sum of all cells matching "added" would be too high, including the target values for cells matching "newly added", which would be a logical error)There are many answers already, but here is the method that Laravel relies on within its Arr class:
/**
* Determines if an array is associative.
*
* An array is "associative" if it doesn't have sequential numerical keys beginning with zero.
*
* @param array $array
* @return bool
*/
public static function isAssoc(array $array)
{
$keys = array_keys($array);
return array_keys($keys) !== $keys;
}
Source: https://github.com/laravel/framework/blob/5.4/src/Illuminate/Support/Arr.php
You can delete localStorage items one by one using Firebug (a useful web development extension) or Firefox's developer console.
You can enter these commands into the console:
localStorage; // click arrow to view object's properties
localStorage.removeItem("foo");
localStorage.clear(); // remove all of localStorage's properties
Firefox now has a built in storage inspector, which you may need to manually enable. See rahilwazir's answer below.
How much data can be added in java.util.List in Java at the maximum?
This is very similar to Theoretical limit for number of keys (objects) that can be stored in a HashMap?
The documentation of java.util.List
does not explicitly documented any limit on the maximum number of elements. The documentation of List.toArray
however, states that ...
Return an array containing all of the elements in this list in proper sequence (from first to last element); would have trouble implementing certain methods faithfully, such as
... so strictly speaking it would not be possible to faithfully implement this method if the list had more than 231-1 = 2147483647 elements since that is the largest possible array.
Some will argue that the documentation of size()
...
Returns the number of elements in this list. If this list contains more than
Integer.MAX_VALUE
elements, returnsInteger.MAX_VALUE
.
...indicates that there is no upper limit, but this view leads to numerous inconsistencies. See this bug report.
Is there any default size an array list?
If you're referring to ArrayList
then I'd say that the default size is 0. The default capacity however (the number of elements you can insert, without forcing the list to reallocate memory) is 10. See the documentation of the default constructor.
The size limit of ArrayList
is Integer.MAX_VALUE
since it's backed by an ordinary array.
In Swift 2.0:
let date = NSDate()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let components = calendar.components([.Month, .Day], fromDate: date)
let (month, day) = (components.month, components.day)
With 4 lines, I import a rss to an array.
$feed = implode(file('http://yourdomains.com/feed.rss'));
$xml = simplexml_load_string($feed);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
For a more complex solution
$feed = new DOMDocument();
$feed->load('file.rss');
$json = array();
$json['title'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$json['description'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$json['link'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
$json['item'] = array();
$i = 0;
foreach($items as $key => $item) {
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
$guid = $item->getElementsByTagName('guid')->item(0)->firstChild->nodeValue;
$json['item'][$key]['title'] = $title;
$json['item'][$key]['description'] = $description;
$json['item'][$key]['pubdate'] = $pubDate;
$json['item'][$key]['guid'] = $guid;
}
echo json_encode($json);
One of my favorite lib: Apache Commons.
The EnumUtils can do that easily.
Following an example to validate an Enum with that library:
public enum MyEnum {
DIV("div"), DEPT("dept"), CLASS("class");
private final String val;
MyEnum(String val) {
this.val = val;
}
public String getVal() {
return val;
}
}
MyEnum strTypeEnum = null;
// test if String str is compatible with the enum
// e.g. if you pass str = "div", it will return false. If you pass "DIV", it will return true.
if( EnumUtils.isValidEnum(MyEnum.class, str) ){
strTypeEnum = MyEnum.valueOf(str);
}
It looks like you can also use a netmask, e.g.
GRANT ... TO 'user'@'192.168.0.0/255.255.255.0' IDENTIFIED BY ...
I've found using cmd works well as an alternative, especially when you need to pipe the output from the called application (espeically when it doesn't have built in logging, unlike msbuild)
cmd /C "$msbuild $args" >> $outputfile
That is not always true; it only works in Windows.
For interacting with terminal in putty, Linux shell,... it will be used for returning the cursor to the beginning of line.
following picture shows the usage of that:
Without '\r':
Data comes without '\r' to the putty terminal, it has just '\n'.
it means that data will be printed just in next line.
With '\r':
Data comes with '\r', i.e. string ends with '\r\n'. So the cursor in putty terminal not only will go to the next line but also at the beginning of line
The download attribute is not supported in IE (see http://caniuse.com/#search=download%20attribute).
That suggests the download attribute is only supported by firefox, chrome, opera and the latest version of blackberry's browser.
For other browsers you'll need to use more traditional methods to force download. That is server side code is necessary to set an appropriate Content-Type and Content-Disposition header to tell (or trick depending on your point of view) the browser to download the item. Headers should look like this:
Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"
(thanks to antyrat for the copy and paste of the headers)
With support for C++11 initializer lists it is very easy:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using Strings = vector<string>;
void foo( Strings const& strings )
{
for( string const& s : strings ) { cout << s << endl; }
}
auto main() -> int
{
foo( Strings{ "hi", "there" } );
}
Lacking that (e.g. for Visual C++ 10.0) you can do things like this:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef vector<string> Strings;
void foo( Strings const& strings )
{
for( auto it = begin( strings ); it != end( strings ); ++it )
{
cout << *it << endl;
}
}
template< class Elem >
vector<Elem>& r( vector<Elem>&& o ) { return o; }
template< class Elem, class Arg >
vector<Elem>& operator<<( vector<Elem>& v, Arg const& a )
{
v.push_back( a );
return v;
}
int main()
{
foo( r( Strings() ) << "hi" << "there" );
}
Maybe a little more readable?
public static class StringExtension {
private static Dictionary<string, string> _replacements = new Dictionary<string, string>();
static StringExtension() {
_replacements["&"] = "and";
_replacements[","] = "";
_replacements[" "] = " ";
// etc...
}
public static string clean(this string s) {
foreach (string to_replace in _replacements.Keys) {
s = s.Replace(to_replace, _replacements[to_replace]);
}
return s;
}
}
Also add New In Town's suggestion about StringBuilder...
I came up with a shorter solution, but it's using lodash. Works with any data, not just strings. For objects can be used:
const mostFrequent = _.maxBy(Object.values(_.groupBy(inputArr, el => el.someUniqueProp)), arr => arr.length)[0];
This is for strings:
const mostFrequent = _.maxBy(Object.values(_.groupBy(inputArr, el => el)), arr => arr.length)[0];
Just grouping data under a certain criteria, then finding the largest group.
Function pointers become easy to declare once you have the basic declarators:
ID
: ID is a*D
: D pointer toD(<parameters>)
: D function taking <
parameters>
returningWhile D is another declarator built using those same rules. In the end, somewhere, it ends with ID
(see below for an example), which is the name of the declared entity. Let's try to build a function taking a pointer to a function taking nothing and returning int, and returning a pointer to a function taking a char and returning int. With type-defs it's like this
typedef int ReturnFunction(char);
typedef int ParameterFunction(void);
ReturnFunction *f(ParameterFunction *p);
As you see, it's pretty easy to build it up using typedefs. Without typedefs, it's not hard either with the above declarator rules, applied consistently. As you see i missed out the part the pointer points to, and the thing the function returns. That's what appears at the very left of the declaration, and is not of interest: It's added at the end if one built up the declarator already. Let's do that. Building it up consistently, first wordy - showing the structure using [
and ]
:
function taking
[pointer to [function taking [void] returning [int]]]
returning
[pointer to [function taking [char] returning [int]]]
As you see, one can describe a type completely by appending declarators one after each other. Construction can be done in two ways. One is bottom-up, starting with the very right thing (leaves) and working the way through up to the identifier. The other way is top-down, starting at the identifier, working the way down to the leaves. I'll show both ways.
Construction starts with the thing at the right: The thing returned, which is the function taking char. To keep the declarators distinct, i'm going to number them:
D1(char);
Inserted the char parameter directly, since it's trivial. Adding a pointer to declarator by replacing D1
by *D2
. Note that we have to wrap parentheses around *D2
. That can be known by looking up the precedence of the *-operator
and the function-call operator ()
. Without our parentheses, the compiler would read it as *(D2(char p))
. But that would not be a plain replace of D1 by *D2
anymore, of course. Parentheses are always allowed around declarators. So you don't make anything wrong if you add too much of them, actually.
(*D2)(char);
Return type is complete! Now, let's replace D2
by the function declarator function taking <parameters>
returning, which is D3(<parameters>)
which we are at now.
(*D3(<parameters>))(char)
Note that no parentheses are needed, since we want D3
to be a function-declarator and not a pointer declarator this time. Great, only thing left is the parameters for it. The parameter is done exactly the same as we've done the return type, just with char
replaced by void
. So i'll copy it:
(*D3( (*ID1)(void)))(char)
I've replaced D2
by ID1
, since we are finished with that parameter (it's already a pointer to a function - no need for another declarator). ID1
will be the name of the parameter. Now, i told above at the end one adds the type which all those declarator modify - the one appearing at the very left of every declaration. For functions, that becomes the return type. For pointers the pointed to type etc... It's interesting when written down the type, it will appear in the opposite order, at the very right :) Anyway, substituting it yields the complete declaration. Both times int
of course.
int (*ID0(int (*ID1)(void)))(char)
I've called the identifier of the function ID0
in that example.
This starts at the identifier at the very left in the description of the type, wrapping that declarator as we walk our way through the right. Start with function taking <
parameters>
returning
ID0(<parameters>)
The next thing in the description (after "returning") was pointer to. Let's incorporate it:
*ID0(<parameters>)
Then the next thing was functon taking <
parameters>
returning. The parameter is a simple char, so we put it in right away again, since it's really trivial.
(*ID0(<parameters>))(char)
Note the parentheses we added, since we again want that the *
binds first, and then the (char)
. Otherwise it would read function taking <
parameters>
returning function .... Noes, functions returning functions aren't even allowed.
Now we just need to put <
parameters>
. I will show a short version of the deriveration, since i think you already by now have the idea how to do it.
pointer to: *ID1
... function taking void returning: (*ID1)(void)
Just put int
before the declarators like we did with bottom-up, and we are finished
int (*ID0(int (*ID1)(void)))(char)
Is bottom-up or top-down better? I'm used to bottom-up, but some people may be more comfortable with top-down. It's a matter of taste i think. Incidentally, if you apply all the operators in that declaration, you will end up getting an int:
int v = (*ID0(some_function_pointer))(some_char);
That is a nice property of declarations in C: The declaration asserts that if those operators are used in an expression using the identifier, then it yields the type on the very left. It's like that for arrays too.
Hope you liked this little tutorial! Now we can link to this when people wonder about the strange declaration syntax of functions. I tried to put as little C internals as possible. Feel free to edit/fix things in it.
Whilst this an old question, I ran into this problem myself recently and some of the answers here are now deprecated (as the comments point out). So for the benefit of others who may have stumbled here:
A term
query can be used to find the exact term specified in the reverse index:
{
"query": {
"term" : { "tags" : "a" }
}
From the documenation https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html
Alternatively you can use a terms
query, which will match all documents with any of the items specified in the given array:
{
"query": {
"terms" : { "tags" : ["a", "c"]}
}
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html
One gotcha to be aware of (which caught me out) - how you define the document also makes a difference. If the field you're searching in has been indexed as a text
type then Elasticsearch will perform a full text search (i.e using an analyzed
string).
If you've indexed the field as a keyword
then a keyword search using a 'non-analyzed' string is performed. This can have a massive practical impact as Analyzed strings are pre-processed (lowercased, punctuation dropped etc.) See (https://www.elastic.co/guide/en/elasticsearch/guide/master/term-vs-full-text.html)
To avoid these issues, the string field has split into two new types: text, which should be used for full-text search, and keyword, which should be used for keyword search. (https://www.elastic.co/blog/strings-are-dead-long-live-strings)
what are you exactly want check for login or user ? a login is created on server level and a user is created at database level so a login is unique in server
also a user is created against a login, a user without login is an orphaned user and is not useful as u cant carry out sql server login without a login
maybe u need this
check for login
select 'X' from master.dbo.syslogins where loginname=<username>
the above query return 'X' if login exists else return null
then create a login
CREATE LOGIN <username> with PASSWORD=<password>
this creates a login in sql server .but it accepts only strong passwords
create a user in each database you want to for login as
CREATE USER <username> for login <username>
assign execute rights to user
GRANT EXECUTE TO <username>
YOU MUST HAVE SYSADMIN permissions or say 'sa' for short
you can write a sql procedure for that on a database
create proc createuser
(
@username varchar(50),
@password varchar(50)
)
as
begin
if not exists(select 'X' from master.dbo.syslogins where loginname=@username)
begin
if not exists(select 'X' from sysusers where name=@username)
begin
exec('CREATE LOGIN '+@username+' WITH PASSWORD='''+@password+'''')
exec('CREATE USER '+@username+' FOR LOGIN '+@username)
exec('GRANT EXECUTE TO '+@username)
end
end
end
Sometimes it's necessary to ajax load a script but delay document ready until after the script is loaded.
jQuery supports this with the holdReady()
function.
Example usage:
$.holdReady(true); //set hold
function releaseHold() { $.holdReady(false); } //callback to release hold
$.getScript('script.js', releaseHold); //load script then release hold
The actual script loading is asynchronous (no error), but the effect is synchronous if the rest of your JavaScript runs after document ready.
This advanced feature would typically be used by dynamic script loaders that want to load additional JavaScript such as jQuery plugins before allowing the ready event to occur, even though the DOM may be ready.
Documentation:
https://api.jquery.com/jquery.holdready
From JQMIGRATE:
jQuery.holdReady() is deprecated
Cause: The
jQuery.holdReady()
method has been deprecated due to its detrimental effect on the global performance of the page. This method can prevent all the code on the page from initializing for extended lengths of time.Solution: Rewrite the page so that it does not require all jQuery ready handlers to be delayed. This might be accomplished, for example, by late-loading only the code that requires the delay when it is safe to run. Due to the complexity of this method, jQuery Migrate does not attempt to fill the functionality. If the underlying version of jQuery used with jQuery Migrate no longer contains
jQuery.holdReady()
the code will fail shortly after this warning appears.
You can try with:
display: inline-table;
For me it works fine.
Since the old accepted answer got deleted (It was a link to a Google code search results that no longer exist), I figured I could answer this question for future reference :
public static DateTime GetNetworkTime()
{
//default Windows time server
const string ntpServer = "time.windows.com";
// NTP message size - 16 bytes of the digest (RFC 2030)
var ntpData = new byte[48];
//Setting the Leap Indicator, Version Number and Mode values
ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(ntpServer).AddressList;
//The UDP port number assigned to NTP is 123
var ipEndPoint = new IPEndPoint(addresses[0], 123);
//NTP uses UDP
using(var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
socket.Connect(ipEndPoint);
//Stops code hang if NTP is blocked
socket.ReceiveTimeout = 3000;
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
}
//Offset to get to the "Transmit Timestamp" field (time at which the reply
//departed the server for the client, in 64-bit timestamp format."
const byte serverReplyTime = 40;
//Get the seconds part
ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
//Get the seconds fraction
ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
//Convert From big-endian to little-endian
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//**UTC** time
var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
return networkDateTime.ToLocalTime();
}
// stackoverflow.com/a/3294698/162671
static uint SwapEndianness(ulong x)
{
return (uint) (((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
Note: You will have to add the following namespaces
using System.Net;
using System.Net.Sockets;
In your example, the div's height is static and the image's height is static. Give the image a margin-top
value of ( div_height - image_height ) / 2
If the image is 50px, then
img {
margin-top: 25px;
}
This is the one that i've tried & it works pretty well for me
$('.mybutton').on('click', function() {
if (!$(this).data('clicked')) {
//do your stuff here if the button is not clicked
$(this).data('clicked', true);
} else {
//do your stuff here if the button is clicked
$(this).data('clicked', false);
}
});
for more reference check this link JQuery toggle click
Found the answer here - http://mytechead.wordpress.com/2014/01/30/android-create-a-file-and-write-to-external-storage/
It says,
/**
* Method to check if user has permissions to write on external storage or not
*/
public static boolean canWriteOnExternalStorage() {
// get the state of your external storage
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// if storage is mounted return true
Log.v("sTag", "Yes, can write to external storage.");
return true;
}
return false;
}
and then let’s use this code to actually write to the external storage:
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/your-dir-name/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, "My-File-Name.txt");
FileOutputStream os = outStream = new FileOutputStream(file);
String data = "This is the content of my file";
os.write(data.getBytes());
os.close();
And this is it. If now you visit your /sdcard/your-dir-name/ folder you will see a file named - My-File-Name.txt with the content as specified in the code.
PS:- You need the following permission -
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I've found out that GPS does not need Internet, BUT of course if you need to download maps, you will need a data connection or wifi.
http://androidforums.com/samsung-fascinate/288871-gps-independent-3g-wi-fi.html http://www.droidforums.net/forum/droid-applications/63145-does-google-navigation-gps-requires-3g-work.html
If I remember correctly, Bluetooth defines certain roles that devices can take. Most cell phones only support a certain number of roles. For instance, I can have a Bluetooth stereo headset that connects to my phone to receive audio, but just because my cell phone has Bluetooth does mean that it supports BEING a speaker for a different device - it doesn't advertise its capabilities of having a speaker for use by other Bluetooth devices.
I assume you want to transfer files between two iPhones? Transferring files via Bluetooth does seem like functionality that I would put in the iPhone, but I'm not Apple so I don't know for sure. In fact, yes, it seems that file transfer is not supported except in jailbroken phones:
http://gizmodo.com/5138797/iphone-bluetooth-file-transfer-coming-soon-yes
You'll probably get similar answers for Bluetooth Dial-Up Networking. I'd imagine they kept the Bluetooth commands out of the SDK for various reasons and you'll have to jailbreak your phone to get the functionality back.
A file ending in .o is an object file. The compiler creates an object file for each source file, before linking them together, into the final executable.
Did you know that JavaScript has it's built-in methods and libs to create forms and submit them?
I am seeing a lot of replies here all asking to use a 3rd party library which I think is an overkill.
I would do the following in pure Javascript:
<script>
function launchMyForm()
{
var myForm = document.createElement("FORM");
myForm.setAttribute("id","TestForm");
document.body.appendChild(myForm);
// this will create a new FORM which is mapped to the Java Object of myForm, with an id of TestForm. Equivalent to: <form id="TestForm"></form>
var myInput = document.createElement("INPUT");
myInput.setAttribute("id","MyInput");
myInput.setAttribute("type","text");
myInput.setAttribute("value","Heider");
document.getElementById("TestForm").appendChild(myInput);
// This will create an INPUT equivalent to: <INPUT id="MyInput" type="text" value="Heider" /> and then assign it to be inside the TestForm tags.
}
</script>
This way (A) you don't need to rely on 3rd parties to do the job. (B) It's all built-in to all browsers, (C) faster, (D) it works, feel free to try it out.
I hope this helps. H
<-
does assignment in the current environment.
When you're inside a function R creates a new environment for you. By default it includes everything from the environment in which it was created so you can use those variables as well but anything new you create will not get written to the global environment.
In most cases <<-
will assign to variables already in the global environment or create a variable in the global environment even if you're inside a function. However, it isn't quite as straightforward as that. What it does is checks the parent environment for a variable with the name of interest. If it doesn't find it in your parent environment it goes to the parent of the parent environment (at the time the function was created) and looks there. It continues upward to the global environment and if it isn't found in the global environment it will assign the variable in the global environment.
This might illustrate what is going on.
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
bar <- "in baz - before <<-"
bar <<- "in baz - after <<-"
print(bar)
}
print(bar)
baz()
print(bar)
}
> bar
[1] "global"
> foo()
[1] "in foo"
[1] "in baz - before <<-"
[1] "in baz - after <<-"
> bar
[1] "global"
The first time we print bar we haven't called foo
yet so it should still be global - this makes sense. The second time we print it's inside of foo
before calling baz
so the value "in foo" makes sense. The following is where we see what <<-
is actually doing. The next value printed is "in baz - before <<-" even though the print statement comes after the <<-
. This is because <<-
doesn't look in the current environment (unless you're in the global environment in which case <<-
acts like <-
). So inside of baz
the value of bar stays as "in baz - before <<-". Once we call baz
the copy of bar inside of foo
gets changed to "in baz" but as we can see the global bar
is unchanged. This is because the copy of bar
that is defined inside of foo
is in the parent environment when we created baz
so this is the first copy of bar
that <<-
sees and thus the copy it assigns to. So <<-
isn't just directly assigning to the global environment.
<<-
is tricky and I wouldn't recommend using it if you can avoid it. If you really want to assign to the global environment you can use the assign function and tell it explicitly that you want to assign globally.
Now I change the <<-
to an assign statement and we can see what effect that has:
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
assign("bar", "in baz", envir = .GlobalEnv)
}
print(bar)
baz()
print(bar)
}
bar
#[1] "global"
foo()
#[1] "in foo"
#[1] "in foo"
bar
#[1] "in baz"
So both times we print bar inside of foo
the value is "in foo" even after calling baz
. This is because assign
never even considered the copy of bar
inside of foo because we told it exactly where to look. However, this time the value of bar in the global environment was changed because we explicitly assigned there.
Now you also asked about creating local variables and you can do that fairly easily as well without creating a function... We just need to use the local
function.
bar <- "global"
# local will create a new environment for us to play in
local({
bar <- "local"
print(bar)
})
#[1] "local"
bar
#[1] "global"
One way to solve this problem, specialization of member functions is to put the specialization into another class, then inherit from that class. You may have to change the order of inheritence to get access to all of the other underlying data but this technique does work.
template< class T, bool condition> struct FooImpl;
template<class T> struct FooImpl<T, true> {
T foo() { return 10; }
};
template<class T> struct FoolImpl<T,false> {
T foo() { return 5; }
};
template< class T >
class Y : public FooImpl<T, boost::is_integer<T> > // whatever your test is goes here.
{
public:
typedef FooImpl<T, boost::is_integer<T> > inherited;
// you will need to use "inherited::" if you want to name any of the
// members of those inherited classes.
};
The disadvantage of this technique is that if you need to test a lot of different things for different member functions you'll have to make a class for each one, and chain it in the inheritence tree. This is true for accessing common data members.
Ex:
template<class T, bool condition> class Goo;
// repeat pattern above.
template<class T, bool condition>
class Foo<T, true> : public Goo<T, boost::test<T> > {
public:
typedef Goo<T, boost::test<T> > inherited:
// etc. etc.
};
If the column expanded only by contiguously added dates as in my case - I used just MAX function to get last date.
The final formula will be:
=DAYS360(A2; MAX(A2:A))
I had this problem recently where apt install wget
does not find anything. As it turns out apt update
was never run.
apt update
apt install wget
After discussing this with a coworker we mused that apt update
is likely not run in order to save both time and space in the docker image.
My solution is a bit different:
$( 'input[name="your_radio_input_name"]:radio:first' ).click();
A workaround for this I used was to include the data as a js file, that implements a function returning the raw data as a string:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<script type="text/javascript">
function loadData() {
// getData() will return the string of data...
document.getElementById('data').innerHTML = getData().replace('\n', '<br>');
}
</script>
</head>
<body onload='loadData()'>
<h1>check out the data!</h1>
<div id='data'></div>
</body>
</html>
// function wrapper, just return the string of data (csv etc)
function getData () {
return 'look at this line of data\n\
oh, look at this line'
}
See it in action here- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=preview
The downside is you have to do some preprocessing on the file to support multilines (append each line in the string with '\n\'
).
You'll have to give pthread_create
a function that matches the signature it's looking for. What you're passing won't work.
You can implement whatever static function you like to do this, and it can reference an instance of c
and execute what you want in the thread. pthread_create
is designed to take not only a function pointer, but a pointer to "context". In this case you just pass it a pointer to an instance of c
.
For instance:
static void* execute_print(void* ctx) {
c* cptr = (c*)ctx;
cptr->print();
return NULL;
}
void func() {
...
pthread_create(&t1, NULL, execute_print, &c[0]);
...
}
You can do some thing like this,
Initialize with empty array and assign the values later
String importRt = "23:43 43:34";
if(null != importRt) {
importArray = Arrays.stream(importRt.split(" "))
.map(String::trim)
.toArray(String[]::new);
}
System.out.println(Arrays.toString(exportImportArray));
Hope it helps..
I just had a similar problem, the DISTINCT keyword works magic:
INSERT INTO Table2(Id, Name) SELECT DISTINCT Id, Name FROM Table1
print_elapsed_time function is below
def print_elapsed_time(prefix=''):
e_time = time.time()
if not hasattr(print_elapsed_time, 's_time'):
print_elapsed_time.s_time = e_time
else:
print(f'{prefix} elapsed time: {e_time - print_elapsed_time.s_time:.2f} sec')
print_elapsed_time.s_time = e_time
use it in this way
print_elapsed_time()
.... heavy jobs ...
print_elapsed_time('after heavy jobs')
.... tons of jobs ...
print_elapsed_time('after tons of jobs')
result is
after heavy jobs elapsed time: 0.39 sec
after tons of jobs elapsed time: 0.60 sec
the pros and cons of this function is that you don't need to pass start time
In my case, when I run df -i it shows me that my number of inodes are full and then I have to delete some of the small files or folder. Otherwise it will not allow us to create files or folders once inodes get full.
All you have to do is delete files or folder that has not taken up full space but is responsible for filling inodes.
Just to note,
MixEdit is not completely free.
"This software is currently not licensed to any user and is running in evaluation mode. MIXEDIT may be downloaded and evaluated for free, however a license must be purchased for continued use."
Upon installation and use, a popup redirects to webpage - similar to SublimeText's unlicensed software pop-up message.
for the sake of completeness, you could use:
(DT_STR,8, 1252) (YEAR(GetDate()) * 10000 + MONTH(GetDate()) * 100 + DAY(GetDate()))
for YYYYMMDD or
RIGHT("000000" + (DT_STR,8, 1252) (DAY(GetDate()) * 1000000 + MONTH(GetDate()) * 10000 + YEAR(GetDate())), 8)
for DDMMYYYY (without hyphens). If you want / need the date as integer (e.g. for _key-columns in DWHs), just remove the DT_STR / RIGTH function and do just the math.
First install setuptools
sudo pip install setuptools
Then install mysql-connector
sudo pip install mysql-connector
If using Python3, then replace pip by pip3
This is what you want:
td {
max-height: whatever;
max-width: whatever;
overflow: hidden;
}
This should further clarify the points:
a = int(raw_input('Enter the index'))
str1 = 'Example'
leng = len(str1)
if (a < (len-1)) and (a > (-len)):
print str1[a]
else:
print('Index overflow')
Input 3 Output m
Input -3 Output p
You cannot simply add a link using CSS. CSS is used for styling.
You can style your using CSS.
If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.
You can accomplish that very easily using jQuery.
I have done a sample for you. You can refer that.
$('#link').attr('href','http://www.google.com');
This single line will do the trick.
To do it by using f-string and with control of the number of trailing digits:
print(f'A number -> {my_number:>20.5f}')
The config file is just an XML file, you can open it by:
private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
catch (Exception ex)
{
return null;
}
}
and later retrieving values by:
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");
Question -I wanted to load my css file but it was not working even though i autoload and manual laod why ? i found the solution => here is my solution : application>config>config.php $config['base_url'] = 'http://localhost/CodeIgniter/'; //paste the link to base url
question explanation:
" > i had my bootstrap.min.css file inside assets/css folder where assets is root directory which i was created.But it was not working even though when i loaded ? 1. $autoload['helper'] = array('url'); 2. $this->load->helper('url'); in my controllar then i go to my
I would suggest that u check for the jar files are properly included in your projects. There are possibility that in absence of jar files, the project will not be compiled
Are you not able to stop the service before the update (and restart after the update) using the commands below?
net stop <service name>
net start <service name>
Whenever I'm testing/deploying a service I'm able to upload files without reinstalling as long as the service is stopped. I'm not sure if the issue you are having is different.
Very simple stuff. Before returning the tableview Cell use the style property of the table view cell.
Just write this line of code before returning table view cell
cell.selectionStyle = .none
This question is very similar to:
Here is how I solved this problem, and dealt with the user hitting the X as well as Ctrl-C. Notice the use of ManualResetEvents. These will cause the main thread to sleep which frees the CPU to process other threads while waiting for either exit, or cleanup. NOTE: It is necessary to set the TerminationCompletedEvent at the end of main. Failure to do so causes unnecessary latency in termination due to the OS timing out while killing the application.
namespace CancelSample
{
using System;
using System.Threading;
using System.Runtime.InteropServices;
internal class Program
{
/// <summary>
/// Adds or removes an application-defined HandlerRoutine function from the list of handler functions for the calling process
/// </summary>
/// <param name="handler">A pointer to the application-defined HandlerRoutine function to be added or removed. This parameter can be NULL.</param>
/// <param name="add">If this parameter is TRUE, the handler is added; if it is FALSE, the handler is removed.</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(ConsoleCloseHandler handler, bool add);
/// <summary>
/// The console close handler delegate.
/// </summary>
/// <param name="closeReason">
/// The close reason.
/// </param>
/// <returns>
/// True if cleanup is complete, false to run other registered close handlers.
/// </returns>
private delegate bool ConsoleCloseHandler(int closeReason);
/// <summary>
/// Event set when the process is terminated.
/// </summary>
private static readonly ManualResetEvent TerminationRequestedEvent;
/// <summary>
/// Event set when the process terminates.
/// </summary>
private static readonly ManualResetEvent TerminationCompletedEvent;
/// <summary>
/// Static constructor
/// </summary>
static Program()
{
// Do this initialization here to avoid polluting Main() with it
// also this is a great place to initialize multiple static
// variables.
TerminationRequestedEvent = new ManualResetEvent(false);
TerminationCompletedEvent = new ManualResetEvent(false);
SetConsoleCtrlHandler(OnConsoleCloseEvent, true);
}
/// <summary>
/// The main console entry point.
/// </summary>
/// <param name="args">The commandline arguments.</param>
private static void Main(string[] args)
{
// Wait for the termination event
while (!TerminationRequestedEvent.WaitOne(0))
{
// Something to do while waiting
Console.WriteLine("Work");
}
// Sleep until termination
TerminationRequestedEvent.WaitOne();
// Print a message which represents the operation
Console.WriteLine("Cleanup");
// Set this to terminate immediately (if not set, the OS will
// eventually kill the process)
TerminationCompletedEvent.Set();
}
/// <summary>
/// Method called when the user presses Ctrl-C
/// </summary>
/// <param name="reason">The close reason</param>
private static bool OnConsoleCloseEvent(int reason)
{
// Signal termination
TerminationRequestedEvent.Set();
// Wait for cleanup
TerminationCompletedEvent.WaitOne();
// Don't run other handlers, just exit.
return true;
}
}
}