Please give a try:
\Q and \E as anchors
Put an Or condition to match either a full word or regex.
Ref Link : How to match a whole word that includes special characters in regex
Answer: From php 5.3 and >
, the var
keyword is equivalent to public
when declaring variables inside a class.
class myClass {
var $x;
}
is the same as (for php 5.3 and >
):
class myClass {
public $x;
}
History: It was previously the norm for declaring variables in classes, though later became depreciated, but later (PHP 5.3) it became un-depreciated.
Used Following Code
System.Windows.Forms.Application.Exit( )
You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","score":"30"},{"name": "name2","score":"50"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<div jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{score}}</td>
</tr>
</div>
<table>
<tbody id="tbody">
</tbody>
</table>
Had the same problem with spaces. Combination of URL and URI solved it:
URL url = new URL("file:/E:/Program Files/IBM/SDP/runtimes/base");
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
Try:
$post = $wp_query->post;
Then pass the function:
$post->ID
For how to do it in jQuery:
<select id="yourid">
<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</select>
<script src="jquery.js"></script>
<script>
$('#yourid').change(function() {
alert('The option with value ' + $(this).val() + ' and text ' + $(this).text() + ' was selected.');
});
</script>
You should also know that Javascript and jQuery are not identical. jQuery is valid JavaScript code, but not all JavaScript is jQuery. You should look up the differences and make sure you are using the appropriate one.
Jason,
This is how it works.
Localnamespace - java:comp/env is a local name space used by the application. The name that you use in it jdbc/db is just an alias. It does not refer to a physical resource.
During deployment this alias should be mapped to a physical resource (in your case a data source) that is defined on the WAS/WPS run time.
This is actually stored in ejb-bnd.xmi files. In the latest versions the XMIs are replaced with XML files. These files are referred to as the Binding files.
HTH Manglu
Have a look at my answer to a similar question:
REM del_old.bat
REM usage: del_old MM-DD-YYY
for /f "tokens=*" %%a IN ('xcopy *.* /d:%1 /L /I null') do if exist %%~nxa echo %%~nxa >> FILES_TO_KEEP.TXT
for /f "tokens=*" %%a IN ('xcopy *.* /L /I /EXCLUDE:FILES_TO_KEEP.TXT null') do if exist "%%~nxa" del "%%~nxa"
This deletes files older than a given date. I'm sure it can be modified to go back seven days from the current date.
update: I notice that HerbCSO has improved on the above script. I recommend using his version instead.
pip install --ignore-installed six
Source: 1233 thumbs up on this comment
You can also use std::list
instead of std::vector
. list
has a built-in function list::reverse for reversing elements.
Save only required cookies and reuse them.
import os
import pickle
from urllib.parse import urljoin, urlparse
login = '[email protected]'
password = 'secret'
# Assuming two cookies are used for persistent login.
# (Find it by tracing the login process)
persistentCookieNames = ['sessionId', 'profileId']
URL = 'http://example.com'
urlData = urlparse(URL)
cookieFile = urlData.netloc + '.cookie'
signinUrl = urljoin(URL, "/signin")
with requests.Session() as session:
try:
with open(cookieFile, 'rb') as f:
print("Loading cookies...")
session.cookies.update(pickle.load(f))
except Exception:
# If could not load cookies from file, get the new ones by login in
print("Login in...")
post = session.post(
signinUrl,
data={
'email': login,
'password': password,
}
)
try:
with open(cookieFile, 'wb') as f:
jar = requests.cookies.RequestsCookieJar()
for cookie in session.cookies:
if cookie.name in persistentCookieNames:
jar.set_cookie(cookie)
pickle.dump(jar, f)
except Exception as e:
os.remove(cookieFile)
raise(e)
MyPage = urljoin(URL, "/mypage")
page = session.get(MyPage)
If the object you are trying to cast from or to has properties that are also user-defined classes, and you don't want to go through reflection, you can use this.
<?php
declare(strict_types=1);
namespace Your\Namespace\Here
{
use Zend\Logger; // or your logging mechanism of choice
final class OopFunctions
{
/**
* @param object $from
* @param object $to
* @param Logger $logger
*
* @return object
*/
static function Cast($from, $to, $logger)
{
$logger->debug($from);
$fromSerialized = serialize($from);
$fromName = get_class($from);
$toName = get_class($to);
$toSerialized = str_replace($fromName, $toName, $fromSerialized);
$toSerialized = preg_replace("/O:\d*:\"([^\"]*)/", "O:" . strlen($toName) . ":\"$1", $toSerialized);
$toSerialized = preg_replace_callback(
"/s:\d*:\"[^\"]*\"/",
function ($matches)
{
$arr = explode(":", $matches[0]);
$arr[1] = mb_strlen($arr[2]) - 2;
return implode(":", $arr);
},
$toSerialized
);
$to = unserialize($toSerialized);
$logger->debug($to);
return $to;
}
}
}
You should probably set all of the cookie properties not just the value of it. setPath()
, setDomain()
... etc
If you use the library "JQuery", you can call this:
Tab:
$.tabNext();
Shift+Tab:
$.tabPrev();
<!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script>
(function($){
'use strict';
/**
* Focusses the next :focusable element. Elements with tabindex=-1 are focusable, but not tabable.
* Does not take into account that the taborder might be different as the :tabbable elements order
* (which happens when using tabindexes which are greater than 0).
*/
$.focusNext = function(){
selectNextTabbableOrFocusable(':focusable');
};
/**
* Focusses the previous :focusable element. Elements with tabindex=-1 are focusable, but not tabable.
* Does not take into account that the taborder might be different as the :tabbable elements order
* (which happens when using tabindexes which are greater than 0).
*/
$.focusPrev = function(){
selectPrevTabbableOrFocusable(':focusable');
};
/**
* Focusses the next :tabable element.
* Does not take into account that the taborder might be different as the :tabbable elements order
* (which happens when using tabindexes which are greater than 0).
*/
$.tabNext = function(){
selectNextTabbableOrFocusable(':tabbable');
};
/**
* Focusses the previous :tabbable element
* Does not take into account that the taborder might be different as the :tabbable elements order
* (which happens when using tabindexes which are greater than 0).
*/
$.tabPrev = function(){
selectPrevTabbableOrFocusable(':tabbable');
};
function tabIndexToInt(tabIndex){
var tabIndexInded = parseInt(tabIndex);
if(isNaN(tabIndexInded)){
return 0;
}else{
return tabIndexInded;
}
}
function getTabIndexList(elements){
var list = [];
for(var i=0; i<elements.length; i++){
list.push(tabIndexToInt(elements.eq(i).attr("tabIndex")));
}
return list;
}
function selectNextTabbableOrFocusable(selector){
var selectables = $(selector);
var current = $(':focus');
// Find same TabIndex of remainder element
var currentIndex = selectables.index(current);
var currentTabIndex = tabIndexToInt(current.attr("tabIndex"));
for(var i=currentIndex+1; i<selectables.length; i++){
if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === currentTabIndex){
selectables.eq(i).focus();
return;
}
}
// Check is last TabIndex
var tabIndexList = getTabIndexList(selectables).sort(function(a, b){return a-b});
if(currentTabIndex === tabIndexList[tabIndexList.length-1]){
currentTabIndex = -1;// Starting from 0
}
// Find next TabIndex of all element
var nextTabIndex = tabIndexList.find(function(element){return currentTabIndex<element;});
for(var i=0; i<selectables.length; i++){
if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === nextTabIndex){
selectables.eq(i).focus();
return;
}
}
}
function selectPrevTabbableOrFocusable(selector){
var selectables = $(selector);
var current = $(':focus');
// Find same TabIndex of remainder element
var currentIndex = selectables.index(current);
var currentTabIndex = tabIndexToInt(current.attr("tabIndex"));
for(var i=currentIndex-1; 0<=i; i--){
if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === currentTabIndex){
selectables.eq(i).focus();
return;
}
}
// Check is last TabIndex
var tabIndexList = getTabIndexList(selectables).sort(function(a, b){return b-a});
if(currentTabIndex <= tabIndexList[tabIndexList.length-1]){
currentTabIndex = tabIndexList[0]+1;// Starting from max
}
// Find prev TabIndex of all element
var prevTabIndex = tabIndexList.find(function(element){return element<currentTabIndex;});
for(var i=selectables.length-1; 0<=i; i--){
if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === prevTabIndex){
selectables.eq(i).focus();
return;
}
}
}
/**
* :focusable and :tabbable, both taken from jQuery UI Core
*/
$.extend($.expr[ ':' ], {
data: $.expr.createPseudo ?
$.expr.createPseudo(function(dataName){
return function(elem){
return !!$.data(elem, dataName);
};
}) :
// support: jQuery <1.8
function(elem, i, match){
return !!$.data(elem, match[ 3 ]);
},
focusable: function(element){
return focusable(element, !isNaN($.attr(element, 'tabindex')));
},
tabbable: function(element){
var tabIndex = $.attr(element, 'tabindex'),
isTabIndexNaN = isNaN(tabIndex);
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable(element, !isTabIndexNaN);
}
});
/**
* focussable function, taken from jQuery UI Core
* @param element
* @returns {*}
*/
function focusable(element){
var map, mapName, img,
nodeName = element.nodeName.toLowerCase(),
isTabIndexNotNaN = !isNaN($.attr(element, 'tabindex'));
if('area' === nodeName){
map = element.parentNode;
mapName = map.name;
if(!element.href || !mapName || map.nodeName.toLowerCase() !== 'map'){
return false;
}
img = $('img[usemap=#' + mapName + ']')[0];
return !!img && visible(img);
}
return ( /^(input|select|textarea|button|object)$/.test(nodeName) ?
!element.disabled :
'a' === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) &&
// the element and all of its ancestors must be visible
visible(element);
function visible(element){
return $.expr.filters.visible(element) && !$(element).parents().addBack().filter(function(){
return $.css(this, 'visibility') === 'hidden';
}).length;
}
}
})(jQuery);
</script>
<a tabindex="5">5</a><br>
<a tabindex="20">20</a><br>
<a tabindex="3">3</a><br>
<a tabindex="7">7</a><br>
<a tabindex="20">20</a><br>
<a tabindex="0">0</a><br>
<script>
var timer;
function tab(){
window.clearTimeout(timer)
timer = window.setInterval(function(){$.tabNext();}, 1000);
}
function shiftTab(){
window.clearTimeout(timer)
timer = window.setInterval(function(){$.tabPrev();}, 1000);
}
</script>
<button tabindex="-1" onclick="tab()">Tab</button>
<button tabindex="-1" onclick="shiftTab()">Shift+Tab</button>
</body>
</html>
_x000D_
I modify jquery.tabbable PlugIn to complete.
1) Using the help function
Get into the python prompt and type the following command:
>>>help("modules")
This will list all the modules installed in the system. You don't need to install any additional packages to list them, but you need to manually search or filter the required module from the list.
2) Using pip freeze
sudo apt-get install python-pip
pip freeze
Even though you need to install additional packages to use this, this method allows you to easily search or filter the result with grep
command. e.g. pip freeze | grep feed
.
You can use whichever method is convenient for you.
Additionally to what NamShubWriter has said, make sure that:
Do not do this:
@Rule
public ExpectedException expectedException;
@Before
public void setup()
{
expectedException = ExpectedException.none();
}
Finally, this blog post clearly illustrates how to assert that a certain exception is thrown.
Actually it seems like Genymotion has an issue with the newer versions of Virtual box, I had the same issue on my Mac but when I downgraded to 4.3.30 it worked like a charm.
In Python string literals, backslash is an escape character. This is also true when the interactive prompt shows you the value of a string. It will give you the literal code representation of the string. Use the print
statement to see what the string actually looks like.
This example shows the difference:
>>> '\\'
'\\'
>>> print '\\'
\
Using NLTK:
from nltk.corpus import wordnet
if not wordnet.synsets(word_to_test):
#Not an English Word
else:
#English Word
You should refer to this article if you have trouble installing wordnet or want to try other approaches.
Different ways to connect Oracle Database from Unix user are:
[oracle@OLE1 ~]$ sqlplus scott/tiger
[oracle@OLE1 ~]$ sqlplus scott/tiger@orcl
[oracle@OLE1 ~]$ sqlplus scott/[email protected]:1521/orcl
[oracle@OLE1 ~]$ sqlplus scott/tiger@//192.168.244.128:1521/orcl
[oracle@OLE1 ~]$ sqlplus "scott/tiger@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=ole1)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)))"
Please see the explanation at link: https://stackoverflow.com/a/45064809/6332029
Thanks!
Even more reliable than @mifmif :
Go to Window Menu > Preferences > General > Appearance > Colors and Fonts
then go to Basic.
This section has about 5 different fonts in it, all of which contain a size. If you go to an item in any other section (like Java > Java Editor Text Font as @mifmif suggested) the Edit Default and Go to Default buttons will be enabled. Clicking the latter takes you to the corresponding item in the Basic section. Clicking the former lets you edit that item directly.
Changing the Basic font items will handle not only Java text but just about every other text in Eclipse that can be resized, as far as I can tell.
In addition to the very great answer above I want to mention application wide events which can be very useful in an MVC setup to enable communication between controllers. (extjs4.1)
Lets say we have a controller Station (Sencha MVC examples) with a select box:
Ext.define('Pandora.controller.Station', {
extend: 'Ext.app.Controller',
...
init: function() {
this.control({
'stationslist': {
selectionchange: this.onStationSelect
},
...
});
},
...
onStationSelect: function(selModel, selection) {
this.application.fireEvent('stationstart', selection[0]);
},
...
});
When the select box triggers a change event, the function onStationSelect
is fired.
Within that function we see:
this.application.fireEvent('stationstart', selection[0]);
This creates and fires an application wide event that we can listen to from any other controller.
Thus in another controller we can now know when the station select box has been changed. This is done through listening to this.application.on
as follows:
Ext.define('Pandora.controller.Song', {
extend: 'Ext.app.Controller',
...
init: function() {
this.control({
'recentlyplayedscroller': {
selectionchange: this.onSongSelect
}
});
// Listen for an application wide event
this.application.on({
stationstart: this.onStationStart,
scope: this
});
},
....
onStationStart: function(station) {
console.info('I called to inform you that the Station controller select box just has been changed');
console.info('Now what do you want to do next?');
},
}
If the selectbox has been changed we now fire the function onStationStart
in the controller Song
also ...
From the Sencha docs:
Application events are extremely useful for events that have many controllers. Instead of listening for the same view event in each of these controllers, only one controller listens for the view event and fires an application-wide event that the others can listen for. This also allows controllers to communicate with one another without knowing about or depending on each other’s existence.
In my case: Clicking on a tree node to update data in a grid panel.
Update 2016 thanks to @gm2008 from the comments below:
In terms of firing application-wide custom events, there is a new method now after ExtJS V5.1 is published, which is using Ext.GlobalEvents
.
When you fire events, you can call: Ext.GlobalEvents.fireEvent('custom_event');
When you register a handler of the event, you call: Ext.GlobalEvents.on('custom_event', function(arguments){/* handler codes*/}, scope);
This method is not limited to controllers. Any component can handle a custom event through putting the component object as the input parameter scope.
bin/hadoop fs -get /hdfs/source/path /localfs/destination/path
bin/hadoop fs -copyToLocal /hdfs/source/path /localfs/destination/path
namenode_machine:50070
), browse to the file you intend to copy, scroll down the page and click on download the file.I was also trying to understand ABI and JesperE’s answer was very helpful.
From a very simple perspective, we may try to understand ABI by considering binary compatibility.
KDE wiki defines a library as binary compatible “if a program linked dynamically to a former version of the library continues running with newer versions of the library without the need to recompile.” For more on dynamic linking, refer Static linking vs dynamic linking
Now, let’s try to look at just the most basic aspects needed for a library to be binary compatibility (assuming there are no source code changes to the library):
Sure, there are many other details but this is mostly what the ABI also covers.
More specifically to answer your question, from the above, we can deduce:
ABI functionality: binary compatibility
existing entities: existing program/libraries/OS
consumer: libraries, OS
Hope this helps!
I have the same issue and solved it by reading this post, while solving it, I hitted a problem: auth failed
.
And I finally solved it by using a ssh key
way to authorize myself. I found the EGit offical guide very useful and I configured the ssh
way successfully by refer to the Eclipse SSH Configuration
section in the link provided.
Hope it helps.
You could also use the RANK function
=RANK(C2,$C$2:$C$7,0)
It would return data like your example:
| A | B | C
1 | name | position | points
2 | person1 | 1 | 10
3 | person2 | 2 | 9
4 | person3 | 2 | 9
5 | person4 | 2 | 9
6 | person5 | 5 | 8
7 | person6 | 6 | 7
The 'Points' column needs to be sorted into descending order.
Under res -> values ->styles.xml
Inside the style body tag paste
<item name="android:windowTranslucentStatus" tools:targetApi="kitkat">true</item>
Or, simply use the headers property introduced in 1.5:
headers: {"Authorization": "Basic xxxx"}
Reference: jQuery Ajax API
I would like to point out something a few seem to have missed: namely it is possible to have an "empty" array position in the middle of your array. Consider the following:
let arr = [0, 1, 2, 3, 4, 5]
delete arr[3]
console.log(arr) // [0, 1, 2, empty, 4, 5]
console.log(arr[3]) // undefined
The natural way to check would then be to see whether the array member is undefined, I am unsure if other ways exists
if (arr[index] === undefined) {
// member does not exist
}
For Web Applications ( ASP.NET MVC and WebForm )
/// <summary>
/// Get current user ip address.
/// </summary>
/// <returns>The IP Address</returns>
public static string GetUserIPAddress()
{
var context = System.Web.HttpContext.Current;
string ip = String.Empty;
if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
ip = context.Request.UserHostAddress;
if (ip == "::1")
ip = "127.0.0.1";
return ip;
}
For Windows Applications ( Windows Form, Console, Windows Service , ... )
static void Main(string[] args)
{
HTTPGet req = new HTTPGet();
req.Request("http://checkip.dyndns.org");
string[] a = req.ResponseBody.Split(':');
string a2 = a[1].Substring(1);
string[] a3=a2.Split('<');
string a4 = a3[0];
Console.WriteLine(a4);
Console.ReadLine();
}
If every new value for the same key name has to be overridden:
public Map < String, Choice > convertListToMap(List < Choice > choices) {
return choices.stream()
.collect(Collectors.toMap(Choice::getName,
Function.identity(),
(oldValue, newValue) - > newValue));
}
If all choices have to be grouped in a list for a name:
public Map < String, Choice > convertListToMap(List < Choice > choices) {
return choices.stream().collect(Collectors.groupingBy(Choice::getName));
}
I used this to achieve it. They fade on hover but take no space when hidden, perfect!
.child {
height: 0px;
opacity: 0;
visibility: hidden;
transition: all .5s ease-in-out;
}
.parent:hover .child {
height: auto;
opacity: 1;
visibility: visible;
}
I use this library, it's really great when you have to deal with lots of images. It downloads them asynchronously, caches them etc.
As for the OOM exceptions, using this and this class drastically reduced them for me.
I think You are trying to use the normal URL of video Like this :
Copying Direct URL from YouTube
That doesn't let you display the content on other domains.To Tackle this up , You should use the Copy Embed Code feature provided by the YouTube itself .Like this :
That would free you up from any issues .
For the above Scenario :
Go to Youtube Video
Copy Embed Code
You can achieve this with MAVEN_OPTS, for example
MAVEN_OPTS=-Dorg.slf4j.simpleLogger.defaultLogLevel=warn mvn clean
Rather than putting the system property directly on the command line. (At least for maven 3.3.1.)
Consider using ~/.mavenrc
for setting MAVEN_OPTS
if you would like logging changed for your login across all maven invocations.
The bottom line is you should almost always use EBS backed instances.
Here's why
I'm a heavy user of Amazon and switched all of my instances to EBS backed storage as soon as the technology came out of beta. I've been very happy with the result.
EBS can still fail - not a silver bullet
Keep in mind that any piece of cloud-based infrastructure can fail at any time. Plan your infrastructure accordingly. While EBS-backed instances provide certain level of durability compared to ephemeral storage instances, they can and do fail. Have an AMI from which you can launch new instances as needed in any availability zone, back up your important data (e.g. databases), and if your budget allows it, run multiple instances of servers for load balancing and redundancy (ideally in multiple availability zones).
When Not To
At some points in time, it may be cheaper to achieve faster IO on Instance Store instances. There was a time when it was certainly true. Now there are many options for EBS storage, catering to many needs. The options and their pricing evolve constantly as technology changes. If you have a significant amount of instances that are truly disposable (they don't affect your business much if they just go away), do the math on cost vs. performance. EBS-backed instances can also die at any point in time, but my practical experience is that EBS is more durable.
You need to create the project on GitHub first. After that go to the project directory and run in terminal:
git init
git remote add origin https://github.com/xxx/yyy.git
git add .
git commit -m "first commit"
git push -u origin master
Currently there is a far simpler solution than the ones already provided. When running your application you just have to pass along the threaded=True
parameter to the app.run()
call, like:
app.run(host="your.host", port=4321, threaded=True)
Another option as per what we can see in the werkzeug docs, is to use the processes
parameter, which receives a number > 1 indicating the maximum number of concurrent processes to handle:
- threaded – should the process handle each request in a separate thread?
- processes – if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes.
Something like:
app.run(host="your.host", port=4321, processes=3) #up to 3 processes
More info on the run()
method here, and the blog post that led me to find the solution and api references.
Note: on the Flask docs on the run()
methods it's indicated that using it in a Production Environment is discouraged because (quote): "While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well."
However, they do point to their Deployment Options page for the recommended ways to do this when going for production.
DEFAULT
is the value that will be inserted in the absence of an explicit value in an insert / update statement. Lets assume, your DDL did not have the NOT NULL
constraint:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT 'MyDefault'
Then you could issue these statements
-- 1. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B) VALUES (NULL, NULL);
-- 2. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, DEFAULT);
-- 3. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) DEFAULT VALUES;
-- 4. This will insert NULL into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, NULL);
Alternatively, you can also use DEFAULT
in UPDATE
statements, according to the SQL-1992 standard:
-- 5. This will update 'MyDefault' into tbl.col
UPDATE tbl SET col = DEFAULT;
-- 6. This will update NULL into tbl.col
UPDATE tbl SET col = NULL;
Note, not all databases support all of these SQL standard syntaxes. Adding the NOT NULL
constraint will cause an error with statements 4, 6
, while 1-3, 5
are still valid statements. So to answer your question: No, they're not redundant.
I ended up making my own, I find that it works better the other solutions that were around.
You simply need to start mysql
and feed it with the content of db.sql
:
mysql -u user -p < db.sql
It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==
, the following should work:
byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);
This will output: YWJjZGVmPT0=
which is abcdef==
encoded in Base64.
Edit:
To decode a Base64 string, simply use Convert.FromBase64String()
. E.g.
string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);
At this point, bytes
will be a byte[]
(not a string
). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
This will output the original input string, abcdef==
in this case.
Another way would be to use two Cubic Bezier Curves. That's for iOS folks using pocketSVG which doesn't recognize svg arc parameter.
C x1 y1, x2 y2, x y (or c dx1 dy1, dx2 dy2, dx dy)
The last set of coordinates here (x,y) are where you want the line to end. The other two are control points. (x1,y1) is the control point for the start of your curve, and (x2,y2) for the end point of your curve.
<path d="M25,0 C60,0, 60,50, 25,50 C-10,50, -10,0, 25,0" />
I had the same issue too and this worked for me try:
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res) => {
let resSTR = JSON.stringify(res);
let resJSON = JSON.parse(resStr);
console.log(resJSON._body);
})
if your using php for the backend maybe you can use this code.
// Validate image file size
if (($_FILES["file-input"]["size"] > 2000000)) {
$msg = "Image File Size is Greater than 2MB.";
header("Location: ../product.php?error=$msg");
exit();
}
You can customize Facebook share dialog box by using asynchronous JavaScript SDK provided by Facebook and setting up its parameter values
Have a look at the following code:
<script type="text/javascript">
$(document).ready(function(){
$('#share_button').click(function(e){
e.preventDefault();
FB.ui(
{
method: 'feed',
name: 'This is the content of the "name" field.',
link: 'URL which you would like to share ',
picture: ‘URL of the image which is going to appear as thumbnail image in share dialogbox’,
caption: 'Caption like which appear as title of the dialog box',
description: 'Small description of the post',
message: ''
}
);
});
});
</script>
Before copying and pasting the below code you must first initialize the SDK and set up jQuery library. Please click here to know a step by step how to set information on the same.
It's too late to answer for this question. But if someone is searching for this answer now I've made it to run with no errors.
First of all make sure to download and add maven to path. [ mvn --version
] will give you version specifications of it if you have added to the path correctly.
Now , add following code to the maven project [ pom.xml
] , in the following code replace with your own main file entry point for eg [ com.example.test.Test ].
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<mainClass>
your_package_to_class_that_contains_main_file .MainFileName</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
Now go to the command line [CMD
] in your project and type mvn package
and it will generate a jar file as something like ProjectName-0.0.1-SNAPSHOT.jar
under target
directory.
Now navigate to the target directory by cd target
.
Finally type java -jar jar-file-name.jar
and yes this should work successfully if you don't have any errors in your program.
For mysql8
and python 3.7
on windows, I find previous solutions seems not work for me.
Here is what worked for me:
pip install wheel
pip install mysqlclient-1.4.2-cp37-cp37m-win_amd64.whl
python -m pip install mysql-connector-python
python -m pip install SQLAlchemy
Reference: https://mysql.wisborg.dk/2019/03/03/using-sqlalchemy-with-mysql-8/
/* Helper function */
function download_file(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
var filename = fileURL.substring(fileURL.lastIndexOf('/')+1);
save.download = fileName || filename;
if ( navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) && navigator.userAgent.search("Chrome") < 0) {
document.location = save.href;
// window event not working here
}else{
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
How to use?
download_file(fileURL, fileName); //call function
Source: convertplug.com/plus/docs/download-pdf-file-forcefully-instead-opening-browser-using-js/
USE urllib.request.urlretrieve() AND PIL.Image.open() TO DOWNLOAD AND READ IMAGE DATA :
import requests
import urllib.request
import PIL
urllib.request.urlretrieve("https://i.imgur.com/ExdKOOz.png", "sample.png")
img = PIL.Image.open("sample.png")
img.show()
or Call requests.get(url) with url as the address of the object file to download via a GET request. Call io.BytesIO(obj) with obj as the content of the response to load the raw data as a bytes object. To load the image data, call PIL.Image.open(bytes_obj) with bytes_obj as the bytes object:
import io
response = requests.get("https://i.imgur.com/ExdKOOz.png")
image_bytes = io.BytesIO(response.content)
img = PIL.Image.open(image_bytes)
img.show()
What about using the a
option?
According to the docs:
'a+' - Open file for reading and appending. The file is created if it does not exist.
It seems to work perfectly with createWriteStream
Just tested it myself and here's how I approached it. Pretty straight forward, let me know if you need any clarification
HTML
<div id="map_canvas" style="width:700px; height:500px; margin-left:80px;" ></div>
<button onclick="displayMap()">Show Map</button>
CSS
<style type="text/css">
#map_canvas {display:none;}
</style>
Javascript
<script>
function displayMap()
{
document.getElementById( 'map_canvas' ).style.display = "block";
initialize();
}
function initialize()
{
// create the map
var myOptions = {
zoom: 14,
center: new google.maps.LatLng( 0.0, 0.0 ),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map( document.getElementById( "map_canvas" ),myOptions );
}
</script>
Is this possible to assign a NaN to a double or float in C ...?
Yes, since C99, (C++11) <math.h>
offers the below functions:
#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);
which are like their strtod("NAN(n-char-sequence)",0)
counterparts and NAN
for assignments.
// Sample C code
uint64_t u64;
double x;
x = nan("0x12345");
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = -strtod("NAN(6789A)",0);
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = NAN;
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
Sample output: (Implementation dependent)
(7ff8000000012345)
(fff000000006789a)
(7ff8000000000000)
Another option would be using flexbox.
While it's not supported by IE8 and IE9, you could consider:
Despite some additional browser-specific style prefixing would be necessary for full cross-browser support, you can see the basic usage either on this fiddle and on the following snippet:
html {_x000D_
height: 100%;_x000D_
}_x000D_
html body {_x000D_
height: 100%;_x000D_
overflow: hidden;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
width: 100%;_x000D_
overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
background-color: #4C4;_x000D_
min-height: 50px;_x000D_
width: 100%;_x000D_
}_x000D_
footer {_x000D_
background-color: #4C4;_x000D_
min-height: 30px;_x000D_
width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
it is php version the problem, had the same issue upgraded my php version to 5.6 solved the problem
Just tell the file
-input to automatically submit the form on any change:
<form action="http://example.com">_x000D_
<input type="file" onchange="form.submit()" />_x000D_
</form>
_x000D_
This solution works like this:
onchange
makes the input element execute the following script, whenever the value
is modifiedform
references the form, that this input element is part ofsubmit()
causes the form to send all data to the URL, as specified in action
Advantages of this solution:
id
s. It makes life easier, if you have several forms in one html page.I came here with similar error:
System.InvalidOperationException: 'The entity type 'MyType' requires a primary key to be defined.'
After reading answer by hvd, realized I had simply forgotten to make my key property 'public'. This..
namespace MyApp.Models.Schedule
{
public class MyType
{
[Key]
int Id { get; set; }
// ...
Should be this..
namespace MyApp.Models.Schedule
{
public class MyType
{
[Key]
public int Id { get; set; } // must be public!
// ...
If you want to pass data between two actions during a redirect without include any data in the query string, put the model in the TempData object.
ACTION
TempData["datacontainer"] = modelData;
VIEW
var modelData= TempData["datacontainer"] as ModelDataType;
TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only! Since TempData works this way, you need to know for sure what the next request will be, and redirecting to another view is the only time you can guarantee this.
Therefore, the only scenario where using TempData will reliably work is when you are redirecting.
Using Thread.currentThread()
:
private class MyTask implements Runnable {
public void run() {
long threadId = Thread.currentThread().getId();
logger.debug("Thread # " + threadId + " is doing this task");
}
}
I prefer to use ToString()
and IFormatProvider
.
double value = 100000.3
Console.WriteLine(value.ToString("0,0.00", new CultureInfo("en-US", false)));
Output: 10,000.30
This questions seems a little bit outdated but here is my solution.
I assume that you have already downloaded GlassFish on your hard drive and unzipped the files on a directory.
The first thing as it is said on previous answers, you have to downloaded GlassFish Tools from eclipse marketplace;
Help -> EclipseMarket Place
And install GlassFish on the screen below;
Open Server View, if it is not visible on the bottom of the eclipse, then;
Window -> Show View -> Servers
As the server view is visible, simply click "No servers are available. Click this link to create a new server..." as shown below;
On the New Server window, select GlassFish as shown below. On my experience, there is only one GlassFish option that I can select, instead of several GlassFish options with versions as you can see down below;
Enter the exact GlassFish location and also Java location as you can see below;
On the last step of this configuration, just leave everything as it is. For simplicity, I don't define an admin password;
Now everything is all set, hope that this helps!
A quite common usage for '&&' is compiling software with autotools. For example:
./configure --prefix=/usr && make && sudo make install
Basically if the configure succeeds, make is run to compile, and if that succeeds, make is run as root to install the program. I use this when I am mostly sure that things will work, and it allows me to do other important things like look at stackoverflow an not 'monitor' the progress.
Sometimes I get really carried away...
tar xf package.tar.gz && ( cd package; ./configure && make && sudo make install ) && rm package -rf
I do this when for example making a linux from scratch box.
In the Developer Tools in Chrome, there is a bar along the top, called the Execution Context Selector
(h/t felipe-sabino), just under the Elements, Network, Sources... tabs, that changes depending on the context of the current tab. When in the Console tab there is a dropdown in that bar that allows you to select the frame context in which the Console will operate. Select your frame in this drop down and you will find yourself in the appropriate frame context. :D
Chrome v59
Chrome v33
Chrome v32 & lower
I found a very easy way to do this and it's what I'm using in my app.
Let's say you have the dates in Time objects (or whatever, we just need the milliseconds):
Time date1 = initializeDate1(); //get the date from somewhere
Time date2 = initializeDate2(); //get the date from somewhere
long millis1 = date1.toMillis(true);
long millis2 = date2.toMillis(true);
long difference = millis2 - millis1 ;
//now get the days from the difference and that's it
long days = TimeUnit.MILLISECONDS.toDays(difference);
//now you can do something like
if(days == 7)
{
//do whatever when there's a week of difference
}
if(days >= 30)
{
//do whatever when it's been a month or more
}
The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.
Task.Factory.StartNew(x=>
throw new Exception("I didn't account for this");
)
However, if we do this, at least the application does not crash.
Task.Factory.StartNew(x=>
try {
throw new Exception("I didn't account for this");
}
catch(Exception ex) {
//Log ex
}
)
How (and why) to use display: table-cell (CSS)
I just wanted to mention, since I don't think any of the other answers did directly, that the answer to "why" is: there is no good reason, and you should probably never do this.
In my over a decade of experience in web development, I can't think of a single time I would have been better served to have a bunch of <div>
s with display
styles than to just have table elements.
The only hypothetical I could come up with is if you have tabular data stored in some sort of non-HTML-table format (eg. a CSV file). In a very specific version of this case it might be easier to just add <div>
tags around everything and then add descendent-based styles, instead of adding actual table tags.
But that's an extremely contrived example, and in all real cases I know of simply using table tags would be better.
For Android 2.0 or later you can use the startForeground()
method to start your Service in the foreground.
The documentation says the following:
A started service can use the
startForeground(int, Notification)
API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)
The is primarily intended for when killing the service would be disruptive to the user, e.g. killing a music player service would stop music playing.
You'll need to supply a Notification
to the method which is displayed in the Notifications Bar in the Ongoing section.
first thing first, all shards failed exception is not as dramatic as it sounds, it means shards were failed while serving a request(query or index), and there could be multiple reasons for it like
In order to fix the issue, you need to filter it in one of the above category and based on that appropriate fix is required.
The one mentioned in the question, is clearly in the first bucket as cluster health is RED, means one or more primary shards are missing, and my this SO answer will help you fix RED cluster issue, which will fix the all shards exception in this case.
You'll want to use a udf as below
from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf
def func(fruit1, fruit2):
if fruit1 == None or fruit2 == None:
return 3
if fruit1 == fruit2:
return 1
return 0
func_udf = udf(func, IntegerType())
df = df.withColumn('new_column',func_udf(df['fruit1'], df['fruit2']))
$("#myTable").offset().top;
This will give you the computed offset (relative to document) of any object.
Using command-line
:
docker run -it --name <WHATEVER> -p <LOCAL_PORT>:<CONTAINER_PORT> -v <LOCAL_PATH>:<CONTAINER_PATH> -d <IMAGE>:<TAG>
Using docker-compose.yaml
:
version: '2'
services:
cms:
image: <IMAGE>:<TAG>
ports:
- <LOCAL_PORT>:<CONTAINER_PORT>
volumes:
- <LOCAL_PATH>:<CONTAINER_PATH>
Assume :
Examples :
$ mkdir -p /volume-to-mount
version: '2'
services:
cms:
image: ghost-cms:latest
ports:
- 8080:8080
volumes:
- /volume-to-mount:/mnt
docker exec -it CONTAINER_ID ls -la /mnt
From the release news of ggplot 2.2.0
: "The main plot title is now left-aligned to better work better with a subtitle". See also the plot.title
argument in ?theme
: "left-aligned by default".
As pointed out by @J_F, you may add theme(plot.title = element_text(hjust = 0.5))
to center the title.
ggplot() +
ggtitle("Default in 2.2.0 is left-aligned")
ggplot() +
ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") +
theme(plot.title = element_text(hjust = 0.5))
Simple, standard library only. Gives timezone-aware datetime, unlike datetime.utcnow()
.
from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)
This is what i just used, i like how clean it is :-)
$('select').val(function(){
var nextOption = $(this).children(':selected').next();
return $(nextOption).val();
}).change();
usually the user name resides under git config
git config --global user.name "first last"
although if you still see above doesn't work you could edit .gitconfig under your user directory of mac and update
[user]
name = gitusername
email = [email protected]
Python really tries hard to intelligently set sys.path
. How it is
set can get really complicated. The following guide is a watered-down,
somewhat-incomplete, somewhat-wrong, but hopefully-useful guide
for the rank-and-file python programmer of what happens when python
figures out what to use as the initial values of sys.path
,
sys.executable
, sys.exec_prefix
, and sys.prefix
on a normal
python installation.
First, python does its level best to figure out its actual physical
location on the filesystem based on what the operating system tells
it. If the OS just says "python" is running, it finds itself in $PATH.
It resolves any symbolic links. Once it has done this, the path of
the executable that it finds is used as the value for sys.executable
, no ifs,
ands, or buts.
Next, it determines the initial values for sys.exec_prefix
and
sys.prefix
.
If there is a file called pyvenv.cfg
in the same directory as
sys.executable
or one directory up, python looks at it. Different
OSes do different things with this file.
One of the values in this config file that python looks for is
the configuration option home = <DIRECTORY>
. Python will use this directory instead of the directory containing sys.executable
when it dynamically sets the initial value of sys.prefix
later. If the applocal = true
setting appears in the
pyvenv.cfg
file on Windows, but not the home = <DIRECTORY>
setting,
then sys.prefix
will be set to the directory containing sys.executable
.
Next, the PYTHONHOME
environment variable is examined. On Linux and Mac,
sys.prefix
and sys.exec_prefix
are set to the PYTHONHOME
environment variable, if
it exists, superseding any home = <DIRECTORY>
setting in pyvenv.cfg
. On Windows,
sys.prefix
and sys.exec_prefix
is set to the PYTHONHOME
environment variable,
if it exists, unless a home = <DIRECTORY>
setting is present in pyvenv.cfg
,
which is used instead.
Otherwise, these sys.prefix
and sys.exec_prefix
are found by walking backwards
from the location of sys.executable
, or the home
directory given by pyvenv.cfg
if any.
If the file lib/python<version>/dyn-load
is found in that directory
or any of its parent directories, that directory is set to be to be
sys.exec_prefix
on Linux or Mac. If the file
lib/python<version>/os.py
is is found in the directory or any of its
subdirectories, that directory is set to be sys.prefix
on Linux,
Mac, and Windows, with sys.exec_prefix
set to the same value as
sys.prefix
on Windows. This entire step is skipped on Windows if
applocal = true
is set. Either the directory of sys.executable
is
used or, if home
is set in pyvenv.cfg
, that is used instead for
the initial value of sys.prefix
.
If it can't find these "landmark" files or sys.prefix
hasn't been
found yet, then python sets sys.prefix
to a "fallback"
value. Linux and Mac, for example, use pre-compiled defaults as the
values of sys.prefix
and sys.exec_prefix
. Windows waits
until sys.path
is fully figured out to set a fallback value for
sys.prefix
.
Then, (what you've all been waiting for,) python determines the initial values
that are to be contained in sys.path
.
sys.path
.
On Windows, this is always the empty string, which tells python to
use the full path where the script is located instead.sys.path
, unless you're
on Windows and applocal
is set to true in pyvenv.cfg
.<prefix>/lib/python35.zip
on Linux/Mac and
os.path.join(os.dirname(sys.executable), "python.zip")
on Windows, is added to sys.path
.applocal = true
was set in pyvenv.cfg
, then the contents of the subkeys of the registry key
HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
are added, if any.applocal = true
was set in pyvenv.cfg
, and sys.prefix
could not be found,
then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
is added, if it exists;applocal = true
was set in pyvenv.cfg
, then the contents of the subkeys of the registry key
HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\
are added, if any.applocal = true
was set in pyvenv.cfg
, and sys.prefix
could not be found,
then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
is added, if it exists;sys.prefix
.sys.exec_prefix
is added. On Windows, the directory
which was used (or would have been used) to search dynamically for sys.prefix
is
added.At this stage on Windows, if no prefix was found, then python will try to
determine it by searching all the directories in sys.path
for the landmark files,
as it tried to do with the directory of sys.executable
previously, until it finds something.
If it doesn't, sys.prefix
is left blank.
Finally, after all this, Python loads the site
module, which adds stuff yet further to sys.path
:
It starts by constructing up to four directories from a head and a tail part. For the head part, it uses
sys.prefix
andsys.exec_prefix
; empty heads are skipped. For the tail part, it uses the empty string and thenlib/site-packages
(on Windows) orlib/pythonX.Y/site-packages
and thenlib/site-python
(on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.
Or you can access root terminal by typing sudo -s
I know this is already answered, but none of the current answers make any mention of namespacing and how it affects constants and defines.
As of PHP 5.3, consts and defines are similar in most respects. There are still, however, some important differences:
const FOO = 4 * 3;
doesn't work, but define('CONST', 4 * 3);
does. define
must include the namespace to be defined within that namespace.The code below should illustrate the differences.
namespace foo
{
const BAR = 1;
define('BAZ', 2);
define(__NAMESPACE__ . '\\BAZ', 3);
}
namespace {
var_dump(get_defined_constants(true));
}
The content of the user sub-array will be ['foo\\BAR' => 1, 'BAZ' => 2, 'foo\\BAZ' => 3]
.
=== UPDATE ===
The upcoming PHP 5.6 will allow a bit more flexibility with const
. You will now be able to define consts in terms of expressions, provided that those expressions are made up of other consts or of literals. This means the following should be valid as of 5.6:
const FOOBAR = 'foo ' . 'bar';
const FORTY_TWO = 6 * 9; // For future editors: THIS IS DELIBERATE! Read the answer comments below for more details
const ULTIMATE_ANSWER = 'The ultimate answer to life, the universe and everything is ' . FORTY_TWO;
You still won't be able to define consts in terms of variables or function returns though, so
const RND = mt_rand();
const CONSTVAR = $var;
will still be out.
I stated the following earlier:
The common problem is using the singular form $arg
, which is incorrect. It should always be plural as $args
.
The problem is not that. In fact, $arg
can be anything else. The problem was the use of the comma and the parentheses.
I run the following code that worked and the output follows:
Code:
Function Test([string]$var1, [string]$var2)
{
Write-Host "`$var1 value: $var1"
Write-Host "`$var2 value: $var2"
}
Test "ABC" "DEF"
Output:
$var1 value: ABC
$var2 value: DEF
You need to provide the name of a branch (or other commit identifier), not the name of a remote to git rebase
.
E.g.:
git rebase origin/master
not:
git rebase origin
Note, although origin
should resolve to the the ref origin/HEAD
when used as an argument where a commit reference is required, it seems that not every repository gains such a reference so it may not (and in your case doesn't) work. It pays to be explicit.
Use the CSS
property list-style-position
to position the bullet:
list-style-position:inside /* or outside */;
Jit stands for just in time compiler jit is a program that turns java byte code into instruction that can be sent directly to the processor.
Using the java just in time compiler (really a second compiler) at the particular system platform complies the bytecode into particular system code,once the code has been re-compiled by the jit complier ,it will usually run more quickly in the computer.
The just-in-time compiler comes with the virtual machine and is used optionally. It compiles the bytecode into platform-specific executable code that is immediately executed.
I was able to fix this on Windows 7 64-bit running Python 3.4.3 by running the set
command at a command prompt to determine the existing Visual Studio tools environment variable; in my case it was VS140COMNTOOLS
for Visual Studio Community 2015.
Then run the following (substituting the variable on the right-hand side if yours has a different name):
set VS100COMNTOOLS=%VS140COMNTOOLS%
This allowed me to install the PyCrypto module that was previously giving me the same error as the OP.
For a more permanent solution, add this environment variable to your Windows environment via Control Panel ("Edit the system environment variables"), though you might need to use the actual path instead of the variable substitution.
To remove duplicates from a single column
Sub removeDuplicate()
'removeDuplicate Macro
Columns("A:A").Select
ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _
Header:=xlNo
Range("A1").Select
End Sub
if you have header then use Header:=xlYes
Increase your range as per your requirement.
you can make it to 1000 like this :
ActiveSheet.Range("$A$1:$A$1000")
More info here here
Functions are not exported by default to be made available in subshells. I'd recommend you do:
source ~/anaconda3/etc/profile.d/conda.sh
conda activate my_env
In the commands above, replace ~/anaconda3/ with the path to your miniconda / anaconda installation.
Try This Code Here I created a table for get primary key column in oracle which is called test and then query
create table test
(
id int,
name varchar2(20),
city varchar2(20),
phone int,
constraint pk_id_name_city primary key (id,name,city)
);
SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = 'TEST' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner ORDER BY cols.table_name, cols.position;
If the method accepts non-primitive data type then the following method can be used to invoke a private method of any class:
public static Object genericInvokeMethod(Object obj, String methodName,
Object... params) {
int paramCount = params.length;
Method method;
Object requiredObj = null;
Class<?>[] classArray = new Class<?>[paramCount];
for (int i = 0; i < paramCount; i++) {
classArray[i] = params[i].getClass();
}
try {
method = obj.getClass().getDeclaredMethod(methodName, classArray);
method.setAccessible(true);
requiredObj = method.invoke(obj, params);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return requiredObj;
}
The Parameter accepted are obj, methodName and the parameters. For example
public class Test {
private String concatString(String a, String b) {
return (a+b);
}
}
Method concatString can be invoked as
Test t = new Test();
String str = (String) genericInvokeMethod(t, "concatString", "Hello", "Mr.x");
I found using jQuery was my best solution.
$( "#my_number_field" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
output = new ByteArrayOutputStream();
...
input = new ByteArrayInputStream( output.toByteArray() )
You can use jQuery toggle
to show and hide the div. The script will be like this
<script type="text/javascript">
jQuery(function(){
jQuery("#music").click(function () {
jQuery("#musicinfo").toggle("slow");
});
});
</script>
You should not rely on [NSDate date]
for timing purposes since it can over- or under-report the elapsed time. There are even cases where your computer will seemingly time-travel since the elapsed time will be negative! (E.g. if the clock moved backwards during timing.)
According to Aria Haghighi in the "Advanced iOS Gesture Recognition" lecture of the Winter 2013 Stanford iOS course (34:00), you should use CACurrentMediaTime()
if you need an accurate time interval.
Objective-C:
#import <QuartzCore/QuartzCore.h>
CFTimeInterval startTime = CACurrentMediaTime();
// perform some action
CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
Swift:
let startTime = CACurrentMediaTime()
// perform some action
let elapsedTime = CACurrentMediaTime() - startTime
The reason is that [NSDate date]
syncs on the server, so it could lead to "time-sync hiccups" which can lead to very difficult-to-track bugs. CACurrentMediaTime()
, on the other hand, is a device time that doesn't change with these network syncs.
You will need to add the QuartzCore framework to your target's settings.
For openSUSE Linux distribution:
sudo zypper install <package>
For example:
sudo zypper install git
Method overloading occurs when two or more methods with same method name but different number of parameters in single class. PHP does not support method overloading. Method overriding means two methods with same method name and same number of parameters in two different classes means parent class and child class.
<RatingBar
android:rating="3.5"
android:stepSize="0.5"
android:numStars="5"
style = "?android:attr/ratingBarStyleSmall"
android:theme="@style/RatingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
// if you want to style
<style name="RatingBar" parent="Theme.AppCompat">
<item name="colorControlNormal">@color/colorPrimary</item>
<item name="colorControlActivated">@color/colorAccent</item>
</style>
// add these line for small rating bar
style = "?android:attr/ratingBarStyleSmall"
What about:
char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;
copying to e to preserve the original string, I suppose if you don't care you could just operate over *string
userInfos.GroupBy(userInfo => userInfo.metric)
.OrderBy(group => group.Key)
.Select(group => Tuple.Create(group.Key, group.Count()));
In my case after trying to set the SSH timeout on the command line and in the local server settings. @Ljubitel solution solved the issue form me.
One point to note is that in Workbench 6.2 the setting is now under advanced
OID's are still in use for Postgres with large objects (though some people would argue large objects are not generally useful anyway). They are also used extensively by system tables. They are used for instance by TOAST which stores larger than 8KB BYTEA's (etc.) off to a separate storage area (transparently) which is used by default by all tables. Their direct use associated with "normal" user tables is basically deprecated.
The oid type is currently implemented as an unsigned four-byte integer. Therefore, it is not large enough to provide database-wide uniqueness in large databases, or even in large individual tables. So, using a user-created table's OID column as a primary key is discouraged. OIDs are best used only for references to system tables.
Apparently the OID sequence "does" wrap if it exceeds 4B 6. So in essence it's a global counter that can wrap. If it does wrap, some slowdown may start occurring when it's used and "searched" for unique values, etc.
See also https://wiki.postgresql.org/wiki/FAQ#What_is_an_OID.3F
The 'keyof' solution mentioned above works. But if the variable is used only once e.g looping through an object etc, you can also typecast it.
for (const key in someObject) {
sampleObject[key] = someObject[key as keyof ISomeObject];
}
Its really helped me to dynamically generate ids of showDetailItem
for the below code.
<af:forEach id="fe1" items="#{viewScope.bean.tranTypeList}" var="ttf" varStatus="ttfVs" >
<af:showDetailItem id ="divIDNo${ttfVs.count}" text="#{ttf.trandef}"......>
if you execute this line <af:outputText value="#{ttfVs}"/>
prints the below:
{index=3, count=4, last=false, first=false, end=8, step=1, begin=0}
In C, memcpy is only foolishly risky. As long as you get all three parameters exactly right, none of the struct members are pointers (or, you explicitly intend to do a shallow copy) and there aren't large alignment gaps in the struct that memcpy is going to waste time looping through (or performance never matters), then by all means, memcpy. You gain nothing except code that is harder to read, fragile to future changes and has to be hand-verified in code reviews (because the compiler can't), but hey yeah sure why not.
In C++, we advance to the ludicrously risky. You may have members of types which are not safely memcpyable, like std::string, which will cause your receiving struct to become a dangerous weapon, randomly corrupting memory whenever used. You may get surprises involving virtual functions when emulating slice-copies. The optimizer, which can do wondrous things for you because it has a guarantee of full type knowledge when it compiles =, can do nothing for your memcpy call.
In C++ there's a rule of thumb - if you see memcpy or memset, something's wrong. There are rare cases when this is not true, but they do not involve structs. You use memcpy when, and only when, you have reason to blindly copy bytes.
Assignment on the other hand is simple to read, checks correctness at compile time and then intelligently moves values at runtime. There is no downside.
I can't cite a reference, but by design the List
and Set
implementations of the Collection
interface are basically extendable Array
s. As Collections
by default offer methods to dynamically add and remove elements at any point -- which Array
s don't -- insertion order might not be preserved.
Thus, as there are more methods for content manipulation, there is a need for special implementations that do preserve order.
Another point is performance, as the most well performing Collection
might not be that, which preserves its insertion order. I'm however not sure, how exactly Collections
manage their content for performance increases.
So, in short, the two major reasons I can think of why there are order-preserving Collection
implementations are:
That's JSON, or JavaScript Object Notation. It's a quick way of describing an object, or a hash map. The thing before the colon is the property name, and the thing after the colon is its value. So in this example, there's a property "r", whose value is whatever's in the variable r. Same for t.
Right click on project >> Click on properties >> Java Build Path >> Source >> Add Folder
Create a base class for your ViewModels
with the following constructor code which will apply the DefaultValueAttributes
when any inheriting model is created.
public abstract class BaseViewModel
{
protected BaseViewModel()
{
// apply any DefaultValueAttribute settings to their properties
var propertyInfos = this.GetType().GetProperties();
foreach (var propertyInfo in propertyInfos)
{
var attributes = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true);
if (attributes.Any())
{
var attribute = (DefaultValueAttribute) attributes[0];
propertyInfo.SetValue(this, attribute.Value, null);
}
}
}
}
And inherit from this in your ViewModels:
public class SearchModel : BaseViewModel
{
[DefaultValue(true)]
public bool IsMale { get; set; }
[DefaultValue(true)]
public bool IsFemale { get; set; }
}
You could use startOf('day')
method to compare just the date
Example :
var dateToCompare = moment("06/04/2015 18:30:00");
var today = moment(new Date());
dateToCompare.startOf('day').isSame(today.startOf('day'));
Posting my answer to help someone, the top rated answer didn't solve my qualm.
When I implemented the following [from the top answer], my vertical scroll animation just jittered back and forth:
$(function () {
$("#first").animate({
width: '200px'
}, { duration: 200, queue: false });
$("#second").animate({
width: '600px'
}, { duration: 200, queue: false });
});
I referred to: W3 Schools Set Interval and it solved my issue, namely the 'Syntax' section:
setInterval(function, milliseconds, param1, param2, ...)
Having my parameters of the form { duration: 200, queue: false }
forced a duration of zero and it only looked at the parameters for guidance.
The long and short, here's my code, if you want to understand why it works, read the link or analyse the interval expected parameters:
var $scrollDiv = '#mytestdiv';
var $scrollSpeed = 1000;
var $interval = 800;
function configureRepeats() {
window.setInterval(function () {
autoScroll($scrollDiv, $scrollSpeed);
}, $interval, { queue: false });
};
Where 'autoScroll' is:
$($scrollDiv).animate({
scrollTop: $($scrollDiv).get(0).scrollHeight
}, { duration: $scrollSpeed });
//Scroll to top immediately
$($scrollDiv).animate({
scrollTop: 0
}, 0);
Happy coding!
First set a custom attribute into your option for example nameid
(you can set non-standardized attribute of an HTML element, it's allowed):
'<option nameid= "' + n.id + "' value="' + i + '">' + n.names + '</option>'
then you can easily get attribute value using jquery .attr()
:
$('option:selected').attr("nameid")
For Example:
<select id="jobSel" class="longcombo" onchange="GetNameId">
<option nameid="32" value="1">test1</option>
<option nameid="67" value="1">test2</option>
<option nameid="45" value="1">test3</option>
</select>
Jquery:
function GetNameId(){
alert($('#jobSel option:selected').attr("nameid"));
}
See https://stackoverflow.com/a/15662720/687315. As a workaround, you can listen for the afterPrint
event on the window (Firefox and IE) and listen for mouse movement on the document (indicating that the user has closed the print dialog and returned to the page) after the window.mediaMatch
API indicates that the media no longer matches "print" (Firefox and Chrome).
Keep in mind that the user may or may not have actually printed the document. Also, if you call window.print()
too often in Chrome, the user may not have even been prompted to print.
INSERT INTO def (field_1, field_2, field3)
VALUES
('$field_1', (SELECT id_user from user_table where name = 'jhon'), '$field3')
You can solve this problem using this code:
if(!empty($_GET['variable from which you get']))
{
$_SESSION['something']= $_GET['variable from which you get'];
}
So you get the variable from a GET form, you will store in the $_SESSION['whatever']
variable just once when $_GET['variable from which you get']
is set and if it is empty $_SESSION['something']
will store the old parameter
Try BatToExe converter. It will convert your batch file to an executable, and allow you to set an icon for it.
I use taskinfo for history graph of CPU/RAM/IO speed. http://www.iarsn.com/taskinfo.html
But bursts of unresponsiveness, sounds more like interrupt time due to a falty HD/SS drive.
By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.
So just set it to:
<style name="AppTheme" parent="android:Theme.Holo" />
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
No, you can not do this efficiently without looking in all the keys and checking all their values. So you will need O(n)
time to do this. If you need to do a lot of such lookups you will need to do this efficiently by constructing a reversed dictionary (can be done also in O(n)
) and then making a search inside of this reversed dictionary (each search will take on average O(1)
).
Here is an example of how to construct a reversed dictionary (which will be able to do one to many mapping) from a normal dictionary:
for i in h_normal:
for j in h_normal[i]:
if j not in h_reversed:
h_reversed[j] = set([i])
else:
h_reversed[j].add(i)
For example if your
h_normal = {
1: set([3]),
2: set([5, 7]),
3: set([]),
4: set([7]),
5: set([1, 4]),
6: set([1, 7]),
7: set([1]),
8: set([2, 5, 6])
}
your h_reversed
will be
{
1: set([5, 6, 7]),
2: set([8]),
3: set([1]),
4: set([5]),
5: set([8, 2]),
6: set([8]),
7: set([2, 4, 6])
}
An IDE is an integrated development environment - a suped-up text editor with additional support for developing (such as forms designers, resource editors, etc), compiling and debugging applications. e.g Eclipse, Visual Studio.
A Library is a chunk of code that you can call from your own code, to help you do things more quickly/easily. For example, a Bitmap Processing library will provide facilities for loading and manipulating bitmap images, saving you having to write all that code for yourself. Typically a library will only offer one area of functionality (processing images or operating on zip files)
An API (application programming interface) is a term meaning the functions/methods in a library that you can call to ask it to do things for you - the interface to the library.
An SDK (software development kit) is a library or group of libraries (often with extra tool applications, data files and sample code) that aid you in developing code that uses a particular system (e.g. extension code for using features of an operating system (Windows SDK), drawing 3D graphics via a particular system (DirectX SDK), writing add-ins to extend other applications (Office SDK), or writing code to make a device like an Arduino or a mobile phone do what you want). An SDK will still usually have a single focus.
A toolkit is like an SDK - it's a group of tools (and often code libraries) that you can use to make it easier to access a device or system... Though perhaps with more focus on providing tools and applications than on just code libraries.
A framework is a big library or group of libraries that provides many services (rather than perhaps only one focussed ability as most libraries/SDKs do). For example, .NET provides an application framework - it makes it easier to use most (if not all) of the disparate services you need (e.g. Windows, graphics, printing, communications, etc) to write a vast range of applications - so one "library" provides support for pretty much everything you need to do. Often a framework supplies a complete base on which you build your own code, rather than you building an application that consumes library code to do parts of its work.
There are of course many examples in the wild that won't exactly match these descriptions though.
Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.
So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.
The only way to add headers to a request from inside a browser is use the XmlHttpRequest setRequestHeader method.
Using this with "GET" request will download the resource. The trick then is to access the resource in the intended way. Ostensibly you should be able to allow the GET response to be cacheable for a short period, hence navigation to a new URL or the creation of an IMG tag with a src url should use the cached response from the previous "GET". However that is quite likely to fail especially in IE which can be a bit of a law unto itself where the cache is concerned.
Ultimately I agree with Mehrdad, use of query string is easiest and most reliable method.
Another quirky alternative is use an XHR to make a request to a URL that indicates your intent to access a resource. It could respond with a session cookie which will be carried by the subsequent request for the image or link.
You can just use sum(people$Weight)
.
sum
sums up a vector, and people$Weight
retrieves the weight column from your data frame.
Note - you can get built-in help by using ?sum
, ?colSums
, etc. (by the way, colSums
will give you the sum for each column).
Remove apache from Control Panel and delete the apache folder from Program Files and restart the machine, then install apache again. This will solve the problem; if not do the following: Install IIS if not installed, then start IIS and stop it ... Using services start apache service... enjoy apache.
Change it to this:
var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
This is a regular expression literal that is passed the i
flag which means to be case insensitive.
Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.
Also simple and easy:
Start-Sleep 10
in addition to a watchpoint nested inside a breakpoint you can also set a single breakpoint on the 'filename:line_number' and use a condition. I find it sometimes easier.
(gdb) break iter.c:6 if i == 5
Breakpoint 2 at 0x4004dc: file iter.c, line 6.
(gdb) c
Continuing.
0
1
2
3
4
Breakpoint 2, main () at iter.c:6
6 printf("%d\n", i);
If like me you get tired of line numbers changing, you can add a label then set the breakpoint on the label like so:
#include <stdio.h>
main()
{
int i = 0;
for(i=0;i<7;++i) {
looping:
printf("%d\n", i);
}
return 0;
}
(gdb) break main:looping if i == 5
To repeat 7 times, try to use a an array with length=7, then track it by $index:
<span ng-repeat="a in (((b=[]).length=7)&&b) track by $index" ng-bind="$index + 1 + ', '"></span>
b=[]
create an empty Array «b»,
.length=7
set it's size to «7»,
&&b
let the new Array «b» be available to ng-repeat,
track by $index
where «$index» is the position of iteration.
ng-bind="$index + 1"
display starting at 1.
To repeat X times:
just replace 7 by X.
I had the same problem, got it working by "binding" de service with the service behaviour by doing this :
Gave a name to the behaviour
<serviceBehaviors> <behavior name="YourBehaviourNameHere">
And making a reference to your behaviour in your service
<services>
<service name="WCFTradeLibrary.TradeService" behaviorConfiguration="YourBehaviourNameHere">
The whole thing would be :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicHttp" allowCookies="true"
maxReceivedMessageSize="20000000"
maxBufferSize="20000000"
maxBufferPoolSize="20000000">
<readerQuotas maxDepth="32"
maxArrayLength="200000000"
maxStringContentLength="200000000"/>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="WCFTradeLibrary.TradeService" behaviourConfiguration="YourBehaviourNameHere">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttp" contract="WCFTradeLibrary.ITradeService">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="YourBehaviourNameHere">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faul`enter code here`ts for debugging purposes,
set the value below to true. Set to false before deployment
to avoid disclosing exception info`enter code here`rmation -->
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
With Eclipse Collections you can use detectIndex
along with remove(int)
on any java.util.List.
List<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int index = Iterate.detectIndex(integers, i -> i > 2);
if (index > -1) {
integers.remove(index);
}
Assert.assertEquals(Lists.mutable.with(1, 2, 4, 5), integers);
If you use the MutableList
type from Eclipse Collections, you can call the detectIndex
method directly on the list.
MutableList<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int index = integers.detectIndex(i -> i > 2);
if (index > -1) {
integers.remove(index);
}
Assert.assertEquals(Lists.mutable.with(1, 2, 4, 5), integers);
Note: I am a committer for Eclipse Collections
The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):
VARCHAR(65535)
However, note that the limit is lower if you use a multi-byte character set:
VARCHAR(21844) CHARACTER SET utf8
Here are some examples:
The maximum row size is 65535, but a varchar also includes a byte or two to encode the length of a given string. So you actually can't declare a varchar of the maximum row size, even if it's the only column in the table.
mysql> CREATE TABLE foo ( v VARCHAR(65534) );
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
But if we try decreasing lengths, we find the greatest length that works:
mysql> CREATE TABLE foo ( v VARCHAR(65532) );
Query OK, 0 rows affected (0.01 sec)
Now if we try to use a multibyte charset at the table level, we find that it counts each character as multiple bytes. UTF8 strings don't necessarily use multiple bytes per string, but MySQL can't assume you'll restrict all your future inserts to single-byte characters.
mysql> CREATE TABLE foo ( v VARCHAR(65532) ) CHARSET=utf8;
ERROR 1074 (42000): Column length too big for column 'v' (max = 21845); use BLOB or TEXT instead
In spite of what the last error told us, InnoDB still doesn't like a length of 21845.
mysql> CREATE TABLE foo ( v VARCHAR(21845) ) CHARSET=utf8;
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
This makes perfect sense, if you calculate that 21845*3 = 65535, which wouldn't have worked anyway. Whereas 21844*3 = 65532, which does work.
mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8;
Query OK, 0 rows affected (0.32 sec)
(Just in case anyone lands here) If you have sudo rights one option is to synchronize the system time
sudo date -s "$(wget -qSO- --max-redirect=0 google.com 2>&1 | grep Date: | cut -d' ' -f5-8)Z"
I would move the function handle change and add an index parameter
handleChange: function (index) {
var items = this.state.items;
items[index].name = 'newName';
this.setState({items: items});
},
to the Dynamic form component and pass it to the PopulateAtCheckboxes component as a prop. As you loop over your items you can include an additional counter (called index in the code below) to be passed along to the handle change as shown below
{ Object.keys(this.state.items).map(function (key, index) {
var item = _this.state.items[key];
var boundHandleChange = _this.handleChange.bind(_this, index);
return (
<div>
<PopulateAtCheckboxes this={this}
checked={item.populate_at} id={key}
handleChange={boundHandleChange}
populate_at={data.populate_at} />
</div>
);
}, this)}
Finally you can call your change listener as shown below here
<input type="radio" name={'populate_at'+this.props.id} value={value} onChange={this.props.handleChange} checked={this.props.checked == value} ref="populate-at"/>
<style>
body {
--imgid: 1025; /* optional default img */
}
.shoes {
--imgid: 21;
}
.bridge {
--imgid: 84;
}
img {
--src: "//i.picsum.photos/id/"var(--imgid)"/180/180.jpg"
}
</style>
<script>
function loadIMG(img) {
img.src = getComputedStyle(img) // compute style for img
.getPropertyValue("--src") // get css property
.replace(/[" ]/g, ""); // strip quotes and space
}
</script>
<img src onerror=loadIMG(this) class=bridge>
<img src onerror=loadIMG(this) class=shoes>
<img src onerror=loadIMG(this)>
_x000D_
src
definition on an <IMG> triggers the onerror handler: loadIMG functionYou mean fast enumeration? You question is very unclear.
A normal for loop would look a bit like this:
unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{
// do loop stuff
id someObject = [someArray objectAtIndex:i];
}
And a loop with fast enumeration, which is optimized by the compiler, would look like this:
for(id someObject in someArray)
{
// do stuff with object
}
Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration
I tried this. This will help -
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar should be called after setSupportActionBar, thus setting the toolbar, otherwise, NullpointerException because there is no toolbar set. Hope this helps
app.js
$("button").click( function() {
$.getJSON( "article.json", function(obj) {
$.each(obj, function(key, value) {
$("ul").append("<li>"+value.name+"'s age is : "+value.age+"</li>");
});
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tax Calulator</title>
<script src="jquery-3.2.0.min.js" type="text/javascript"></script>
</head>
<body>
<ul></ul>
<button>Users</button>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
article.json
{
"a": {
"name": "Abra",
"age": 125,
"company": "Dabra"
},
"b": {
"name": "Tudak tudak",
"age": 228,
"company": "Dhidak dhidak"
}
}
server.js
var http = require('http');
var fs = require('fs');
function onRequest(request,response){
if(request.method == 'GET' && request.url == '/') {
response.writeHead(200,{"Content-Type":"text/html"});
fs.createReadStream("./index.html").pipe(response);
} else if(request.method == 'GET' && request.url == '/jquery-3.2.0.min.js') {
response.writeHead(200,{"Content-Type":"text/javascript"});
fs.createReadStream("./jquery-3.2.0.min.js").pipe(response);
} else if(request.method == 'GET' && request.url == '/app.js') {
response.writeHead(200,{"Content-Type":"text/javascript"});
fs.createReadStream("./app.js").pipe(response);
}
else if(request.method == 'GET' && request.url == '/article.json') {
response.writeHead(200,{"Content-Type":"text/json"});
fs.createReadStream("./article.json").pipe(response);
}
}
http.createServer(onRequest).listen(2341);
console.log("Server is running ....");
Server.js will run a simple node http server in your local to process the data.
Note don't forget toa dd jQuery library in your folder structure and change the version number accordingly in server.js and index.html
This is my running one https://github.com/surya4/jquery-json.
The solution seems to be to add multiple @font-face
rules, for example:
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans.ttf");
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Bold.ttf");
font-weight: bold;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Oblique.ttf");
font-style: italic, oblique;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-BoldOblique.ttf");
font-weight: bold;
font-style: italic, oblique;
}
By the way, it would seem Google Chrome doesn't know about the format("ttf")
argument, so you might want to skip that.
(This answer was correct for the CSS 2 specification. CSS3 only allows for one font-style rather than a comma-separated list.)
Please use regex to remove anything before |
example
dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds
Use find and replace in notepad++
find: .+(\|)
replace: \1
output
| fdfsfsf
|gfghhghg
|dfdsfsds
As per Pylint documentation, the easiest is to use this chart:
So one can use:
pylint -j 0 --disable=I,E,R,W,C,F YOUR_FILES_LOC
Hope this useful for you.
$(document).click(function(e){
if ($('#news_gallery').on('clicked')) {
var article = $('#news-article .news-article');
}
});
The accepted answer generally covers it all, but I'd like to add something,
just incase you are planning to work with the model in a way like updating, and you are retrieving a single record(whose id
you do not know), Then find_by
is the way to go, because it retrieves the record and does not put it in an array
irb(main):037:0> @kit = Kit.find_by(number: "3456")
Kit Load (0.9ms) SELECT "kits".* FROM "kits" WHERE "kits"."number" =
'3456' LIMIT 1
=> #<Kit id: 1, number: "3456", created_at: "2015-05-12 06:10:56",
updated_at: "2015-05-12 06:10:56", job_id: nil>
irb(main):038:0> @kit.update(job_id: 2)
(0.2ms) BEGIN Kit Exists (0.4ms) SELECT 1 AS one FROM "kits" WHERE
("kits"."number" = '3456' AND "kits"."id" != 1) LIMIT 1 SQL (0.5ms)
UPDATE "kits" SET "job_id" = $1, "updated_at" = $2 WHERE "kits"."id" =
1 [["job_id", 2], ["updated_at", Tue, 12 May 2015 07:16:58 UTC +00:00]]
(0.6ms) COMMIT => true
but if you use where
then you can not update it directly
irb(main):039:0> @kit = Kit.where(number: "3456")
Kit Load (1.2ms) SELECT "kits".* FROM "kits" WHERE "kits"."number" =
'3456' => #<ActiveRecord::Relation [#<Kit id: 1, number: "3456",
created_at: "2015-05-12 06:10:56", updated_at: "2015-05-12 07:16:58",
job_id: 2>]>
irb(main):040:0> @kit.update(job_id: 3)
ArgumentError: wrong number of arguments (1 for 2)
in such a case you would have to specify it like this
irb(main):043:0> @kit[0].update(job_id: 3)
(0.2ms) BEGIN Kit Exists (0.6ms) SELECT 1 AS one FROM "kits" WHERE
("kits"."number" = '3456' AND "kits"."id" != 1) LIMIT 1 SQL (0.6ms)
UPDATE "kits" SET "job_id" = $1, "updated_at" = $2 WHERE "kits"."id" = 1
[["job_id", 3], ["updated_at", Tue, 12 May 2015 07:28:04 UTC +00:00]]
(0.5ms) COMMIT => true
Simply do
SELECT birthdate, (YEAR(CURDATE())-YEAR(birthdate)) AS age FROM `member`
birthdate is field name that keep birthdate name take CURDATE() turn to year by YEAR() command minus with YEAR() from the birthdate field
The possible vales of
[[UIDevice currentDevice] model];
are iPod touch
, iPhone
, iPhone Simulator
, iPad
, iPad Simulator
If you want to know which hardware iOS
is ruining on like iPhone3
, iPhone4
, iPhone5
etc below is the code for that
NOTE: The below code may not contain all device's string, I'm with other guys are maintaining the same code on GitHub so please take the latest code from there
Objective-C : GitHub/DeviceUtil
Swift : GitHub/DeviceGuru
#include <sys/types.h>
#include <sys/sysctl.h>
- (NSString*)hardwareDescription {
NSString *hardware = [self hardwareString];
if ([hardware isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
if ([hardware isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
if ([hardware isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
if ([hardware isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([hardware isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
if ([hardware isEqualToString:@"iPod1,1"]) return @"iPodTouch 1G";
if ([hardware isEqualToString:@"iPod2,1"]) return @"iPodTouch 2G";
if ([hardware isEqualToString:@"iPad1,1"]) return @"iPad";
if ([hardware isEqualToString:@"iPad2,6"]) return @"iPad Mini";
if ([hardware isEqualToString:@"iPad4,1"]) return @"iPad Air WIFI";
//there are lots of other strings too, checkout the github repo
//link is given at the top of this answer
if ([hardware isEqualToString:@"i386"]) return @"Simulator";
if ([hardware isEqualToString:@"x86_64"]) return @"Simulator";
return nil;
}
- (NSString*)hardwareString {
size_t size = 100;
char *hw_machine = malloc(size);
int name[] = {CTL_HW,HW_MACHINE};
sysctl(name, 2, hw_machine, &size, NULL, 0);
NSString *hardware = [NSString stringWithUTF8String:hw_machine];
free(hw_machine);
return hardware;
}
This is an old question, but one that is frequently visited and clear recommendations are now available from RFC 7303 which obsoletes RFC3023. In a nutshell (section 9.2):
The registration information for text/xml is in all respects the same
as that given for application/xml above (Section 9.1), except that
the "Type name" is "text".
Yes there is retainAll
check out this
Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);
You should use window.history
and return a false so that the href
is not navigated by the browser ( the default behavior ).
<a href="www.mypage.com" onclick="window.history.go(-1); return false;"> Link </a>
Try adding a semi colon to the end of your structure:
struct sotrudnik {
string name;
string speciality;
string razread;
int zarplata;
} //Semi colon here
MD5 is a hashing algorithm, you can not revert the hash value.
You should add "change password feature", where the user gives another password, calculates the hash and store it as a new password.
For some reason, I have to use
element.find('.fc-event-inner').empty();
to make it work, i guess i'm in day view.
>>> import os
>>> os.system('cd c:\mydir')
In fact, os.system()
can execute any command that windows command prompt can execute, not just change dir.
On MVC 5 is quite similar
@Html.ActionLink("LinkText", "ActionName", new { id = "id" })
If you are trying to capitalize the first letter of each word in an array you can simply put this:
array_name.map(&:capitalize)
Exact Audio Copy works this way on Windows XP. The standard file open dialog is shown, but the filename field contains the text "Filename will be ignored".
Just guessing here, but I suspect the string is injected into the combo box edit control every time a significant change is made to the dialog. As long as the field isn't blank, and the dialog flags are set to not check the existence of the file, the dialog can be closed normally.
Edit: this is much easier than I thought. Here's the code in C++/MFC, you can translate it to the environment of your choice.
CFileDialog dlg(true, NULL, "Filename will be ignored", OFN_HIDEREADONLY | OFN_NOVALIDATE | OFN_PATHMUSTEXIST | OFN_READONLY, NULL, this);
dlg.DoModal();
Edit 2: This should be the translation to C#, but I'm not fluent in C# so don't shoot me if it doesn't work.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.FileName = "Filename will be ignored";
openFileDialog1.CheckPathExists = true;
openFileDialog1.ShowReadOnly = false;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.CheckFileExists = false;
openFileDialog1.ValidateNames = false;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
// openFileDialog1.FileName should contain the folder and a dummy filename
}
Edit 3: Finally looked at the actual dialog in question, in Visual Studio 2005 (I didn't have access to it earlier). It is not the standard file open dialog! If you inspect the windows in Spy++ and compare them to a standard file open, you'll see that the structure and class names don't match. When you look closely, you can also spot some differences between the contents of the dialogs. My conclusion is that Microsoft completely replaced the standard dialog in Visual Studio to give it this capability. My solution or something similar will be as close as you can get, unless you're willing to code your own from scratch.
As @Ming mentioned:
pip install -r file.txt
Here's a simple line to force update all dependencies:
while read -r package; do pip install --upgrade --force-reinstall $package;done < pipfreeze.txt
Leaving alone any debates over when (if ever) it should be done, @functions is how you do it.
@functions {
// Add code here.
}
Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:
angular.module('myApp', ['myApp.directives', 'myApp.services']);
plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview
A few principles:
you have a std::exception base class, you should have your exceptions derive from it. That way general exception handler still have some information.
Don't throw pointers but object, that way memory is handled for you.
Example:
struct MyException : public std::exception
{
std::string s;
MyException(std::string ss) : s(ss) {}
~MyException() throw () {} // Updated
const char* what() const throw() { return s.c_str(); }
};
And then use it in your code:
void Foo::Bar(){
if(!QueryPerformanceTimer(&m_baz)){
throw MyException("it's the end of the world!");
}
}
void Foo::Caller(){
try{
this->Bar();// should throw
}catch(MyException& caught){
std::cout<<"Got "<<caught.what()<<std::endl;
}
}
Thanks to the answer by @Nulu, it works for pyspark with minimal tweaking
from pyspark.sql.types import LongType, StringType, StructField, StructType, BooleanType, ArrayType, IntegerType
customSchema = StructType(Array(
StructField("project", StringType, true),
StructField("article", StringType, true),
StructField("requests", IntegerType, true),
StructField("bytes_served", DoubleType, true)))
pagecount = sc.read.format("com.databricks.spark.csv")
.option("delimiter"," ")
.option("quote","")
.option("header", "false")
.schema(customSchema)
.load("dbfs:/databricks-datasets/wikipedia-datasets/data-001/pagecounts/sample/pagecounts-20151124-170000")
npm was failing for me at scandir
for:
npm install -g webpack
...which might be caused by npm attempting to "modify" files that were potentially locked by other processes as mentioned here and in few other github threads. After force cleaning the cache, verifying cache, running as admin, disabling the AV, etc the solution that actually worked for me was closing any thing that might be placing a lock the files (i.e. restarting my computer).
I hope this helps someone struggling.
There's also:
find directory_name -type f -print0 | xargs -0 grep -li word
but that might be a bit much for a beginner.
find
is a general purpose directory walker/lister, -type f
means "look for plain files rather than directories and named pipes and what have you", -print0
means "print them on the standard output using null characters as delimiters". The output from find
is sent to xargs -0
and that grabs its standard input in chunks (to avoid command line length limitations) using null characters as a record separator (rather than the standard newline) and the applies grep -li word
to each set of files. On the grep
, -l
means "list the files that match" and -i
means "case insensitive"; you can usually combine single character options so you'll see -li
more often than -l -i
.
If you don't use -print0
and -0
then you'll run into problems with file names that contain spaces so using them is a good habit.
its easy . Just add !important at the end of your css line :
tr:hover { background: #000 !important; }
Error 127
means one of two things:
$PATH
, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.file -L
on /bin/sh
(to get your default/native format) and on the compiler itself (to see what format it is).if the problem is (2), then you can solve it in a few diff ways:
Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.
Check out this angular-table directive.
The short answer is:
snprintf( str, size, "%d", x );
The longer is: first you need to find out sufficient size. snprintf
tells you length if you call it with NULL, 0
as first parameters:
snprintf( NULL, 0, "%d", x );
Allocate one character more for null-terminator.
#include <stdio.h>
#include <stdlib.h>
int x = -42;
int length = snprintf( NULL, 0, "%d", x );
char* str = malloc( length + 1 );
snprintf( str, length + 1, "%d", x );
...
free(str);
If works for every format string, so you can convert float or double to string by using "%g"
, you can convert int to hex using "%x"
, and so on.
It looks like window.open
will take a Data URI as the location parameter.
So you can open it like this from the question: Opening PDF String in new window with javascript:
window.open("data:application/pdf;base64, " + base64EncodedPDF);
Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.
Then on the server, you can convert the byte array to base64 encoding like this:
string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);
NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.
Here's an updated example that is using NSURLConnection +sendAsynchronousRequest: (10.7+, iOS 5+), The "Post" request remains the same as with the accepted answer and is omitted here for the sake of clarity:
NSURL *apiURL = [NSURL URLWithString:
[NSString stringWithFormat:@"http://www.myserver.com/api/api.php?request=%@", @"someRequest"]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data.length) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
NSLog(@"%@", responseString);
}
}
}];
You did syntax declaration error, use proper setTimeout declaration
message:() => {
setTimeout(() => {this.setState({opened:false})},3000);
return 'Thanks for your time, have a nice day !
}
I tried most of the answers and unfortunately, none of them worked in completion.
Here is what worked for me. There are 3 things to do to the site you want PUT for (select the site) :
Open WebDav Authoring Rules
and then select Disable WebDAV
option present on the right bar.
Select Modules
, find the WebDAV Module
and remove it.
Select HandlerMapping
, find the WebDAVHandler
and remove it.
Restart IIS.
This seems to work moderately well in a terminal emulator window. It loops until there's a connection then stops.
#!/bin/bash
# ping in a loop until the net is up
declare -i s=0
declare -i m=0
while ! ping -c1 -w2 8.8.8.8 &> /dev/null ;
do
echo "down" $m:$s
sleep 10
s=s+10
if test $s -ge 60; then
s=0
m=m+1;
fi
done
echo -e "--------->> UP! (connect a speaker) <<--------" \\a
The \a at the end is trying to get a bel char on connect. I've been trying to do this in LXDE/lxpanel but everything halts until I have a network connection again. Having a time started out as a progress indicator because if you look at a window with just "down" on every line you can't even tell it's moving.
At ANDROID STUDIO do the following steps:
You will be able to see the signature at the bottom of IDE
There are optimizations the compiler can't do because they only work for a reduced set of inputs.
Below there is c++ sample code that can do a faster division doing a 64bits "Multiplication by the reciprocal". Both numerator and denominator must be below certain threshold. Note that it must be compiled to use 64 bits instructions to be actually faster than normal division.
#include <stdio.h>
#include <chrono>
static const unsigned s_bc = 32;
static const unsigned long long s_p = 1ULL << s_bc;
static const unsigned long long s_hp = s_p / 2;
static unsigned long long s_f;
static unsigned long long s_fr;
static void fastDivInitialize(const unsigned d)
{
s_f = s_p / d;
s_fr = s_f * (s_p - (s_f * d));
}
static unsigned fastDiv(const unsigned n)
{
return (s_f * n + ((s_fr * n + s_hp) >> s_bc)) >> s_bc;
}
static bool fastDivCheck(const unsigned n, const unsigned d)
{
// 32 to 64 cycles latency on modern cpus
const unsigned expected = n / d;
// At least 10 cycles latency on modern cpus
const unsigned result = fastDiv(n);
if (result != expected)
{
printf("Failed for: %u/%u != %u\n", n, d, expected);
return false;
}
return true;
}
int main()
{
unsigned result = 0;
// Make sure to verify it works for your expected set of inputs
const unsigned MAX_N = 65535;
const unsigned MAX_D = 40000;
const double ONE_SECOND_COUNT = 1000000000.0;
auto t0 = std::chrono::steady_clock::now();
unsigned count = 0;
printf("Verifying...\n");
for (unsigned d = 1; d <= MAX_D; ++d)
{
fastDivInitialize(d);
for (unsigned n = 0; n <= MAX_N; ++n)
{
count += !fastDivCheck(n, d);
}
}
auto t1 = std::chrono::steady_clock::now();
printf("Errors: %u / %u (%.4fs)\n", count, MAX_D * (MAX_N + 1), (t1 - t0).count() / ONE_SECOND_COUNT);
t0 = t1;
for (unsigned d = 1; d <= MAX_D; ++d)
{
fastDivInitialize(d);
for (unsigned n = 0; n <= MAX_N; ++n)
{
result += fastDiv(n);
}
}
t1 = std::chrono::steady_clock::now();
printf("Fast division time: %.4fs\n", (t1 - t0).count() / ONE_SECOND_COUNT);
t0 = t1;
count = 0;
for (unsigned d = 1; d <= MAX_D; ++d)
{
for (unsigned n = 0; n <= MAX_N; ++n)
{
result += n / d;
}
}
t1 = std::chrono::steady_clock::now();
printf("Normal division time: %.4fs\n", (t1 - t0).count() / ONE_SECOND_COUNT);
getchar();
return result;
}
With the help of xpath locator also, you can achieve the same.
Your statement would be:
driver.findElement(By.xpath(".//a[contains(@href,'long')]")).click();
And for clicking all the links contains long in the URL, you can use:-
List<WebElement> linksList = driver.findElements(By.xpath(".//a[contains(@href,'long')]"));
for (WebElement webElement : linksList){
webElement.click();
}
As you can read before, the ?v=1
ensures that your browser gets the version 1 of the file. When you have a new version, you just have to append a different version number and the browser will forget about the old version and loads the new one.
There is a gulp plugin which takes care of version your files during the build phase, so you don't have to do it manually. It's handy and you can easily integrate it in you build process. Here's the link: gulp-annotate
Here's another way to do it in VBA.
Function ConvertToArray(ByVal value As String)
value = StrConv(value, vbUnicode)
ConvertToArray = Split(Left(value, Len(value) - 1), vbNullChar)
End Function
Sub example()
Dim originalString As String
originalString = "hi there"
Dim myArray() As String
myArray = ConvertToArray(originalString)
End Sub
Check your Elastic version.
I had these problem because I was looking at the incorrect version's documentation.
Here is some code that as far as I can best tell does the same thing as the accepted answer but with less code:
public static bool IsFileLocked(string file)
{
try
{
using (var stream = File.OpenRead(file))
return false;
}
catch (IOException)
{
return true;
}
}
However I think it is more robust to do it in the following manner:
public static void TryToDoWithFileStream(string file, Action<FileStream> action,
int count, int msecTimeOut)
{
FileStream stream = null;
for (var i = 0; i < count; ++i)
{
try
{
stream = File.OpenRead(file);
break;
}
catch (IOException)
{
Thread.Sleep(msecTimeOut);
}
}
action(stream);
}
I must use templates for a internal APP and it works for me:
'DIRS': [os.path.join(BASE_DIR + '/THE_APP_NAME', 'templates')],
If you are using Ubuntu and PHP 7.2, use this...
sudo apt-get update
sudo apt-get install zip unzip php7.2-zip
This answer provide interesting commands based on git am
and presented using examples, step by step.
git log --pretty=email -p --reverse --full-index --binary
git am
Example: Extract history of file3
, file4
and file5
my_repo
+-- dirA
¦ +-- file1
¦ +-- file2
+-- dirB ^
¦ +-- subdir | To be moved
¦ ¦ +-- file3 | with history
¦ ¦ +-- file4 |
¦ +-- file5 v
+-- dirC
+-- file6
+-- file7
Clean the temporary directory destination
export historydir=/tmp/mail/dir # Absolute path
rm -rf "$historydir" # Caution when cleaning
Clean your the repo source
git commit ... # Commit your working files
rm .gitignore # Disable gitignore
git clean -n # Simulate removal
git clean -f # Remove untracked file
git checkout .gitignore # Restore gitignore
Extract history of each file in email format
cd my_repo/dirB
find -name .git -prune -o -type d -o -exec bash -c 'mkdir -p "$historydir/${0%/*}" && git log --pretty=email -p --stat --reverse --full-index --binary -- "$0" > "$historydir/$0"' {} ';'
Unfortunately option --follow
or --find-copies-harder
cannot be combined with --reverse
. This is why history is cut when file is renamed (or when a parent directory is renamed).
After: Temporary history in email format
/tmp/mail/dir
+-- subdir
¦ +-- file3
¦ +-- file4
+-- file5
Suppose you want to move these three files in this other repo (can be the same repo).
my_other_repo
+-- dirF
¦ +-- file55
¦ +-- file56
+-- dirB # New tree
¦ +-- dirB1 # was subdir
¦ ¦ +-- file33 # was file3
¦ ¦ +-- file44 # was file4
¦ +-- dirB2 # new dir
¦ +-- file5 # = file5
+-- dirH
+-- file77
Therefore reorganize your files:
cd /tmp/mail/dir
mkdir dirB
mv subdir dirB/dirB1
mv dirB/dirB1/file3 dirB/dirB1/file33
mv dirB/dirB1/file4 dirB/dirB1/file44
mkdir dirB/dirB2
mv file5 dirB/dirB2
Your temporary history is now:
/tmp/mail/dir
+-- dirB
+-- dirB1
¦ +-- file33
¦ +-- file44
+-- dirB2
+-- file5
Change also filenames within the history:
cd "$historydir"
find * -type f -exec bash -c 'sed "/^diff --git a\|^--- a\|^+++ b/s:\( [ab]\)/[^ ]*:\1/$0:g" -i "$0"' {} ';'
Note: This rewrites the history to reflect the change of path and filename.
(i.e. the change of the new location/name within the new repo)
Your other repo is:
my_other_repo
+-- dirF
¦ +-- file55
¦ +-- file56
+-- dirH
+-- file77
Apply commits from temporary history files:
cd my_other_repo
find "$historydir" -type f -exec cat {} + | git am
Your other repo is now:
my_other_repo
+-- dirF
¦ +-- file55
¦ +-- file56
+-- dirB ^
¦ +-- dirB1 | New files
¦ ¦ +-- file33 | with
¦ ¦ +-- file44 | history
¦ +-- dirB2 | kept
¦ +-- file5 v
+-- dirH
+-- file77
Use git status
to see amount of commits ready to be pushed :-)
Note: As the history has been rewritten to reflect the path and filename change:
(i.e. compared to the location/name within the previous repo)
git mv
to change the location/filename.git log --follow
to access full history.To list the files having been renamed:
find -name .git -prune -o -exec git log --pretty=tformat:'' --numstat --follow {} ';' | grep '=>'
More customizations: You can complete the command git log
using options --find-copies-harder
or --reverse
. You can also remove the first two columns using cut -f3-
and grepping complete pattern '{.* => .*}'.
find -name .git -prune -o -exec git log --pretty=tformat:'' --numstat --follow --find-copies-harder --reverse {} ';' | cut -f3- | grep '{.* => .*}'
Hope below Oracle query will work.
Select First_column,LISTAGG(second_column,',')
WITHIN GROUP (ORDER BY second_column) as Sec_column,
LISTAGG(third_column,',')
WITHIN GROUP (ORDER BY second_column) as thrd_column
FROM tablename
GROUP BY first_column
Forgive the flippancy, but if you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE.
Update (Jul 3 '14):
The HTTP spec intentionally does not define what is returned from POST or DELETE. The spec only defines what needs to be defined. The rest is left up to the implementer to choose.
Problem
The upstream server is timing out and I don't what is happening.
Where to Look first before increasing read or write timeout if your server is connecting to a database
Server is connecting to a database and that connection is working just fine and within sane response time, and its not the one causing this delay in server response time.
make sure that connection state is not causing a cascading failure on your upstream
Then you can move to look at the read and write timeout configurations of the server and proxy.
For me error was in file info.plist
, field Bundle identifier
. Somehow it was modified to
com.myCompany.${PRODUCT_NAME:rfc1034identifier}
from
com.myCompany.${PRODUCT_NAME}
Try this:
... = new ArrayList<Something>(EnumSet.allOf(Something.class));
as ArrayList
has a constructor with Collection<? extends E>
. But use this method only if you really want to use EnumSet
.
All enums have access to the method values()
. It returns an array of all enum values:
... = Arrays.asList(Something.values());
Depends on whether or not your array is holding a null-terminated string. If so, then
if(text[0] == '\0') {}
should be sufficient.
Edit: Another method would be...
if (strcmp(text, "") == 0)
which is potentially less efficient but clearly expresses your intent.
I encountered this problem on Windows 8.1, VirtualBox 5.1.18 and Vagrant 1.9.3.
Deleting the VirtualBox Hosts-only Ethernet Adapter from VirtualBox Preferences (Network --> Hosts-only networks) fixed this for me, and vagrant up
could continue and start the VM.
application
because .js
-Files aren't something a user wants to read but something that should get executed.
From another search. Worked for me!
"You can use Visual Studio 2010 and it does support it, provided your OS supports .NET 4.5.
Right click on your solution to add a reference (as you do). When the dialog box shows, select browse, then navigate to the following folder:
C:\Program Files(x86)\Reference Assemblies\Microsoft\Framework\.Net Framework\4.5
You will find it there."
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
If you append this to user.js
:
exports.User = User;
then in server.js
you can do:
var userFile = require('./user.js');
var User = userFile.User;
http://nodejs.org/docs/v0.4.10/api/globals.html#require
Another way is:
global.User = User;
then this would be enough in server.js
:
require('./user.js');
Networking code is notoriously difficult to write, test and debug.
You often have lots of things to consider such as:
what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.
are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive
how does congestion in the real world which causes delays in the stream affect your reading/writing logic
If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).
Here are several different ways to handle the exchange:
have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"
use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"
use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.
have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)
Each approach has its pros and cons for "correctness".
The code below uses the "timeout" method, as that seems to be the one you want.
See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream
on the TCPClient
so you can change the ReadTimeout
.
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
// Set a 250 millisecond timeout for reading (instead of Infinite the default)
stm.ReadTimeout = 250;
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
int bytesread = stm.Read(resp, 0, resp.Length);
while (bytesread > 0)
{
memStream.Write(resp, 0, bytesread);
bytesread = stm.Read(resp, 0, resp.Length);
}
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
As a footnote for other variations on this writing network code...when doing a Read
where you want to avoid a "block", you can check the DataAvailable
flag and then ONLY read what is in the buffer checking the .Length
property e.g. stm.Read(resp, 0, stm.Length);
When you are using foreach loop within view for binded model ... Your model is supposed to be in listed format.
i.e
@model IEnumerable<ViewModels.MyViewModels>
@{
if (Model.Count() > 0)
{
@Html.DisplayFor(modelItem => Model.Theme.FirstOrDefault().name)
@foreach (var theme in Model.Theme)
{
@Html.DisplayFor(modelItem => theme.name)
@foreach(var product in theme.Products)
{
@Html.DisplayFor(modelItem => product.name)
@foreach(var order in product.Orders)
{
@Html.TextBoxFor(modelItem => order.Quantity)
@Html.TextAreaFor(modelItem => order.Note)
@Html.EditorFor(modelItem => order.DateRequestedDeliveryFor)
}
}
}
}else{
<span>No Theam avaiable</span>
}
}
https://developer.mozilla.org/en/CSS/Media_queries#-moz-device-pixel-ratio
-moz-device-pixel-ratio
Gives the number of device pixels per CSS pixel.
this is almost self-explaining. the number describes the ratio of how much "real" pixels (physical pixerls of the screen) are used to display one "virtual" pixel (size set in CSS).
Or you can do that with ES6 template literal:
<a :href="`/job/${r.id}`"
I used the a similar approach as @iod07, but as an extension. Also, I added some explanations in the comments to understand how it works.
Basically, just add this at the top or bottom of your view controller.
extension NSString {
class func convertFormatOfDate(date: String, originalFormat: String, destinationFormat: String) -> String! {
// Orginal format :
let dateOriginalFormat = NSDateFormatter()
dateOriginalFormat.dateFormat = originalFormat // in the example it'll take "yy MM dd" (from our call)
// Destination format :
let dateDestinationFormat = NSDateFormatter()
dateDestinationFormat.dateFormat = destinationFormat // in the example it'll take "EEEE dd MMMM yyyy" (from our call)
// Convert current String Date to NSDate
let dateFromString = dateOriginalFormat.dateFromString(date)
// Convert new NSDate created above to String with the good format
let dateFormated = dateDestinationFormat.stringFromDate(dateFromString!)
return dateFormated
}
}
Example
Let's say you want to convert "16 05 05"
to "Thursday 05 May 2016"
and your date is declared as follow let date = "16 06 05"
Then simply call call it with :
let newDate = NSString.convertFormatOfDate(date, originalFormat: "yy MM dd", destinationFormat: "EEEE dd MMMM yyyy")
Hope it helps !
You can use the extension method AsEnumerable in Assembly System.Core and System.Linq namespace :
List<Book> list = new List<Book>();
return list.AsEnumerable();
This will, as said on this MSDN link change the type of the List in compile-time. This will give you the benefits also to only enumerate your collection we needed (see MSDN example for this).
This is really a long thread, and probably because the answers albeit correct are not resolving the fundamental question. I came across this site: Version & Build Numbers that provided a clear overview of what is what in the Microsoft Windows world.
Since my interest is to know which exact windows OS I am dealing with, I left aside the entire version rainbow and instead focused on the BuildNumber. The build number may be attained either by:
([Environment]::OSVersion.Version).Build
or by:
(Get-CimInstance Win32_OperatingSystem).buildNumber
the choice is yours which ever way you prefer it. So from there I could do something along the lines of:
switch ((Get-CimInstance Win32_OperatingSystem).BuildNumber)
{
6001 {$OS = "W2K8"}
7600 {$OS = "W2K8R2"}
7601 {$OS = "W2K8R2SP1"}
9200 {$OS = "W2K12"}
9600 {$OS = "W2K12R2"}
14393 {$OS = "W2K16v1607"}
16229 {$OS = "W2K16v1709"}
default { $OS = "Not Listed"}
}
Write-Host "Server system: $OS" -foregroundcolor Green
Note: As you can see I used the above just for server systems, however it could easily be applied to workstations or even cleverly extended to support both... but I'll leave that to you.
Enjoy, & have fun!
You're already doing it correctly, it just that the <h4>Facebook</h4>
tag is taking too much vertical margin. You can remove it by using the style margin:0px
on the <h4>
tag.
For your future convenience, you can put border (border:1px solid black
) on your elements to see which part you actually get it wrong.