There are three streaming protocols / technology in HTML5:
Live streaming, low latency - WebRTC - Websocket
VOD and Live streaming, high latency - HLS
1. WebRTC
In fact WebRTC is SRTP(secure RTP protocol). Thus we can say that video tag supports RTP(SRTP) indirectly via WebRTC.
Therefore to get RTP stream on your Chrome, Firefox or another HTML5 browser, you need a WebRTC server which will deliver the SRTP stream to browser.
2. Websocket
It is TCP based, but with lower latency than HLS. Again you need a Websocket server.
3. HLS
Most popular high-latency streaming protocol for VOD(pre-recorded video).
You are getting something wrong... RTSP is a realtime streaming protocol. Meaning, you can stream whatever you want in real time. So you can use it to stream LIVE content (no matter what it is, video, audio, text, presentation...). RTP is a transport protocol which is used to transport media data which is negotiated over RTSP.
You use RTSP to control media transmission over RTP. You use it to setup, play, pause, teardown the stream...
So, if you want your server to just start streaming when the URL is requested, you can implement some sort of RTP-only server. But if you want more control and if you are streaming live video, you must use RTSP, because it transmits SDP and other important decoding data.
Read the documents I linked here, they are a good starting point.
In JavaScript you cannot have the direct access to the filesystem.
However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace
method with your Base64String and replace "image/png"
with "image/octet-stream"
:
"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");
Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:
Probably, you will find them useful in a way...
Here is a refactored version of what I understand you need:
window.addEventListener('DOMContentLoaded', () => {_x000D_
const img = document.getElementById('embedImage');_x000D_
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
'9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
_x000D_
const button = document.getElementById('saveImage');_x000D_
button.addEventListener('click', () => {_x000D_
window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<img id="embedImage" alt="Red dot" />_x000D_
<button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
In my case, I had a very similar problem. I was updating my view inside a function that was being called by a parent component, and in my parent component I forgot to use @ViewChild(NameOfMyChieldComponent). I lost at least 3 hours just for this stupid mistake. i.e: I didn't need to use any of those methods:
emulator -writable-system
For people using an Emulator: Another possibility is that you need to start the emulator with -writable-system. That was the only thing that worked for me when using the standard emulator packaged with android studio with a 4.1 image. Check here: https://stackoverflow.com/a/41332316/4962858
In case you just want to know if you scroll up or down using a pointer device (mouse or track pad) you can use the deltaY property of the wheel
event.
$('.container').on('wheel', function(event) {_x000D_
if (event.originalEvent.deltaY > 0) {_x000D_
$('.result').append('Scrolled down!<br>');_x000D_
} else {_x000D_
$('.result').append('Scrolled up!<br>');_x000D_
}_x000D_
});
_x000D_
.container {_x000D_
height: 200px;_x000D_
width: 400px;_x000D_
margin: 20px;_x000D_
border: 1px solid black;_x000D_
overflow-y: auto;_x000D_
}_x000D_
.content {_x000D_
height: 300px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="content">_x000D_
Scroll me!_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="result">_x000D_
<p>Action:</p>_x000D_
</div>
_x000D_
var mongoose = require('mongoose');
var _id = mongoose.mongo.ObjectId("4eb6e7e7e9b7f4194e000001");
This is a swiss-armyknife function you can use:
function table.find(t, val, recursive, metatables, keys, returnBool)
if (type(t) ~= "table") then
return nil
end
local checked = {}
local _findInTable
local _checkValue
_checkValue = function(v)
if (not checked[v]) then
if (v == val) then
return v
end
if (recursive and type(v) == "table") then
local r = _findInTable(v)
if (r ~= nil) then
return r
end
end
if (metatables) then
local r = _checkValue(getmetatable(v))
if (r ~= nil) then
return r
end
end
checked[v] = true
end
return nil
end
_findInTable = function(t)
for k,v in pairs(t) do
local r = _checkValue(t, v)
if (r ~= nil) then
return r
end
if (keys) then
r = _checkValue(t, k)
if (r ~= nil) then
return r
end
end
end
return nil
end
local r = _findInTable(t)
if (returnBool) then
return r ~= nil
end
return r
end
You can use it to check if a value exists:
local myFruit = "apple"
if (table.find({"apple", "pear", "berry"}, myFruit)) then
print(table.find({"apple", "pear", "berry"}, myFruit)) -- 1
You can use it to find the key:
local fruits = {
apple = {color="red"},
pear = {color="green"},
}
local myFruit = fruits.apple
local fruitName = table.find(fruits, myFruit)
print(fruitName) -- "apple"
I hope the recursive
parameter speaks for itself.
The metatables
parameter allows you to search metatables as well.
The keys
parameter makes the function look for keys in the list. Of course that would be useless in Lua (you can just do fruits[key]
) but together with recursive
and metatables
, it becomes handy.
The returnBool
parameter is a safe-guard for when you have tables that have false
as a key in a table (Yes that's possible: fruits = {false="apple"}
)
I couldn't get the selected answer to work but after a bit of research, I found that the horizontal scrolling div must have white-space: nowrap
in the css.
Here's complete working code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Something</title>
<style type="text/css">
#scrolly{
width: 1000px;
height: 190px;
overflow: auto;
overflow-y: hidden;
margin: 0 auto;
white-space: nowrap
}
img{
width: 300px;
height: 150px;
margin: 20px 10px;
display: inline;
}
</style>
</head>
<body>
<div id='scrolly'>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
</div>
</body>
</html>
You can use these functions:
function shareOnFB(){
var url = "https://www.facebook.com/sharer/sharer.php?u=https://yoururl.com&t=your message";
window.open(url, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');
return false;
}
function shareOntwitter(){
var url = 'https://twitter.com/intent/tweet?url=URL_HERE&via=getboldify&text=yourtext';
TwitterWindow = window.open(url, 'TwitterWindow',width=600,height=300);
return false;
}
function shareOnGoogle(){
var url = "https://plus.google.com/share?url=https://yoururl.com";
window.open(url, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=350,width=480');
return false;
}
<a onClick="shareOnFB()"> Facebook </a>
<a onClick="shareOntwitter()"> Twitter </a>
<a onClick="shareOnGoogle()"> Google </a>
From the documentation, you do it like:
<div class="row">
<div class="col-md-6">left</div>
<div class="col-md-push-6">content needs to be right aligned</div>
</div>
~(5.5) // => -6
~(-6) // => 5
~~5.5 // => 5 (same as Math.floor(5.5))
~~(-5.5) // => -5 (NOT the same as Math.floor(-5.5), which would give -6 )
For more info, see:
Android Studio:
Eclipse:
Find the MissingTranslation
line, and set it to Warning
as seen below:
<h4>Order List</h4>
<ul>
<li ng-repeat="val in filter_option.order">
<span>
<input title="{{filter_option.order_name[$index]}}" type="radio" ng-model="filter_param.order_option" ng-value="'{{val}}'" />
{{filter_option.order_name[$index]}}
</span>
<select title="" ng-model="filter_param[val]">
<option value="asc">Asc</option>
<option value="desc">Desc</option>
</select>
</li>
</ul>
if you have a given Date string with date and time .
for e.g String givenDateString = pojoModel.getDate()/* Format dd-MMM-yyyy hh:mm:ss */
use the following code to add an event with date and time to the calendar
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss").parse(givenDateString));
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime",cal.getTimeInMillis() + 60 * 60 * 1000);
intent.putExtra("title", " Test Title");
startActivity(intent);
Take a look at ?legend
and try this:
legend('topright', names(a)[-1] ,
lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
select sum(counts) from (
select count(1) as counts from foo
union all
select count(1) as counts from bar)
You can disable caching globally using $.ajaxSetup()
, for example:
$.ajaxSetup({ cache: false });
This appends a timestamp to the querystring when making the request. To turn cache off for a particular $.ajax()
call, set cache: false
on it locally, like this:
$.ajax({
cache: false,
//other options...
});
You can set it directly as the useEffect
callback:
useEffect(fetchBusinesses, [])
It will trigger only once, so make sure all the function's dependencies are correctly set (same as using componentDidMount/componentWillMount...
)
Edit 02/21/2020
Just for completeness:
useEffect
callback (as above)useEffect(fetchBusinesses, [])
useEffect()
useEffect(() => {
function fetchBusinesses() {
...
}
fetchBusinesses()
}, [])
useCallback()
In this case, if you have dependencies in your function, you will have to include them in the useCallback
dependencies array and this will trigger the useEffect
again if the function's params change. Besides, it is a lot of boilerplate... So just pass the function directly to useEffect
as in 1. useEffect(fetchBusinesses, [])
.
const fetchBusinesses = useCallback(() => {
...
}, [])
useEffect(() => {
fetchBusinesses()
}, [fetchBusinesses])
useEffect(() => {
fetchBusinesses()
}, []) // eslint-disable-line react-hooks/exhaustive-deps
Simplest way I did this. Not the best way but simplest way I know how.
import "fmt"
func main() {
fmt.Print(addTwoNumbers(5, 6))
}
func addTwoNumbers(val1 interface{}, val2 interface{}) int {
op1, _ := val1.(int)
op2, _ := val2.(int)
return op1 + op2
}
As per comments, First you need to install an instance of SQL Server if you don't already have one - https://msdn.microsoft.com/en-us/library/ms143219.aspx
Once this is installed you must connect to this instance (server) and then you can create a database here - https://msdn.microsoft.com/en-US/library/ms186312.aspx
I build a module that allows do this kind of tests. But it is focused not only in repeat. But in guarantee that some piece of code is Thread safe.
https://github.com/anderson-marques/concurrent-testing
Maven dependency:
<dependency>
<groupId>org.lite</groupId>
<artifactId>concurrent-testing</artifactId>
<version>1.0.0</version>
</dependency>
Example of use:
package org.lite.concurrent.testing;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import ConcurrentTest;
import ConcurrentTestsRule;
/**
* Concurrent tests examples
*/
public class ExampleTest {
/**
* Create a new TestRule that will be applied to all tests
*/
@Rule
public ConcurrentTestsRule ct = ConcurrentTestsRule.silentTests();
/**
* Tests using 10 threads and make 20 requests. This means until 10 simultaneous requests.
*/
@Test
@ConcurrentTest(requests = 20, threads = 10)
public void testConcurrentExecutionSuccess(){
Assert.assertTrue(true);
}
/**
* Tests using 10 threads and make 20 requests. This means until 10 simultaneous requests.
*/
@Test
@ConcurrentTest(requests = 200, threads = 10, timeoutMillis = 100)
public void testConcurrentExecutionSuccessWaitOnly100Millissecond(){
}
@Test(expected = RuntimeException.class)
@ConcurrentTest(requests = 3)
public void testConcurrentExecutionFail(){
throw new RuntimeException("Fail");
}
}
This is a open source project. Feel free to improve.
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames. In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.
An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.
EDIT: Firefox does support the DEFER attribute since version 3.6.
Sources:
To build once a day between say 4PM to 6PM you can use
H H(15-17) * * *
Perhaps try this:
function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
var CCSstyle = undefined, rules;
for(var m in document.styleSheets){
if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
for(var n in rules){
if(rules[n].selectorText == selectorText){
CCSstyle = rules[n].style;
break;
}
}
break;
}
}
if(value == undefined)
return CCSstyle[style]
else
return CCSstyle[style] = value
}
Try using type
:
type foobar
For example:
$ type ls
ls is aliased to `ls --color=auto'
$ type foobar
-bash: type: foobar: not found
This is preferable to which
for a few reasons:
The default which
implementations only support the -a
option that shows all options, so you have to find an alternative version to support aliases
type
will tell you exactly what you are looking at (be it a Bash function or an alias or a proper binary).
type
doesn't require a subprocess
type
cannot be masked by a binary (for example, on a Linux box, if you create a program called which
which appears in path before the real which
, things hit the fan. type
, on the other hand, is a shell built-in (yes, a subordinate inadvertently did this once).
Doing the following in a command prompt works for me, also adding to my User environment variables worked fine as well:
set PATH=%PATH%;C:\Program Files\7-Zip\
echo %PATH%
7z
You should see as output (or something similar - as this is on my laptop running Windows 7):
C:\Users\Phillip>set PATH=%PATH%;C:\Program Files\7-Zip\
C:\Users\Phillip>echo %PATH%
C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Wi
ndows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\
WirelessCommon\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\To
ols\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Fil
es (x86)\QuickTime\QTSystem\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Notepad+
+;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\7-Zip\
C:\Users\Phillip>7z
7-Zip [64] 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18
Usage: 7z <command> [<switches>...] <archive_name> [<file_names>...]
[<@listfiles...>]
<Commands>
a: Add files to archive
b: Benchmark
d: Delete files from archive
e: Extract files from archive (without using directory names)
l: List contents of archive
t: Test integrity of archive
u: Update files to archive
x: eXtract files with full paths
<Switches>
-ai[r[-|0]]{@listfile|!wildcard}: Include archives
-ax[r[-|0]]{@listfile|!wildcard}: eXclude archives
-bd: Disable percentage indicator
-i[r[-|0]]{@listfile|!wildcard}: Include filenames
-m{Parameters}: set compression Method
-o{Directory}: set Output directory
-p{Password}: set Password
-r[-|0]: Recurse subdirectories
-scs{UTF-8 | WIN | DOS}: set charset for list files
-sfx[{name}]: Create SFX archive
-si[{name}]: read data from stdin
-slt: show technical information for l (List) command
-so: write data to stdout
-ssc[-]: set sensitive case mode
-ssw: compress shared files
-t{Type}: Set type of archive
-u[-][p#][q#][r#][x#][y#][z#][!newArchiveName]: Update options
-v{Size}[b|k|m|g]: Create volumes
-w[{path}]: assign Work directory. Empty path means a temporary directory
-x[r[-|0]]]{@listfile|!wildcard}: eXclude filenames
-y: assume Yes on all queries
You can do it by following way.
ALTER TABLE tableName drop column if exists columnName;
ALTER TABLE tableName ADD COLUMN columnName character varying(8);
So it will drop the column if it is already exists. And then add the column to particular table.
Slightly changed to David Murdoch's code for generic library
Function HasByName(cSheetName As String, _
Optional oWorkBook As Excel.Workbook) As Boolean
HasByName = False
Dim wb
If oWorkBook Is Nothing Then
Set oWorkBook = ThisWorkbook
End If
For Each wb In oWorkBook.Worksheets
If wb.Name = cSheetName Then
HasByName = True
Exit Function
End If
Next wb
End Function
Maybe you could use String#split
To answer your comment:
I'm not sure if there can be more than one . in a filename, but whatever, even if there are more dots you can use the split. Consider e.g. that:
String input = "boo.and.foo";
String[] result = input.split(".");
This will return an array containing:
{ "boo", "and", "foo" }
So you will know that the last index in the array is the extension and all others are the base.
from __future__ import print_function
import csv
import MySQLdb
print("Enter File To Be Export")
conn = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db="database")
cursor = conn.cursor()
#sql = 'CREATE DATABASE test1'
sql ='''DROP TABLE IF EXISTS `test1`; CREATE TABLE test1 (policyID int, statecode varchar(255), county varchar(255))'''
cursor.execute(sql)
with open('C:/Users/Desktop/Code/python/sample.csv') as csvfile:
reader = csv.DictReader(csvfile, delimiter = ',')
for row in reader:
print(row['policyID'], row['statecode'], row['county'])
# insert
conn = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db="database")
sql_statement = "INSERT INTO test1(policyID ,statecode,county) VALUES (%s,%s,%s)"
cur = conn.cursor()
cur.executemany(sql_statement,[(row['policyID'], row['statecode'], row['county'])])
conn.escape_string(sql_statement)
conn.commit()
A simple working command:
root/dspace# grep -r --exclude-dir={log,assetstore} "creativecommons.org"
Above I grep for text "creativecommons.org" in current directory "dspace" and exclude dirs {log,assetstore}.
Done.
You can simply type Q:
and that should solve your problem.
I noticed that the Chrome developer tool sometimes only underlines the first element in swiggly red even if it is correctly set up with a name. This threw me off for a while.
One must be sure to add a name to every element on the form that contains ngModel regardless of which one is squiggly underlined.
For anyone using Python 3.8 or newer I recommend using "Assignment Expressions" as described in PEP 572 -- Assignment Expressions.
if any((match := i) > 3 for i in range(10)):
print(match)
By default git push
updates all the remote branches. But you can configure git to update only the current branch to it's upstream.
git config push.default upstream
It means git will update only the current (checked out) branch when you do git push.
Other valid options are:
nothing
: Do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.matching
: Push all branches having the same name on both ends. (default option prior to Ver 1.7.11) upstream
: Push the current branch to its upstream
branch. This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow). No need to have the same name for local and remote branch.tracking
: Deprecated, use upstream
instead.current
: Push the current branch to the remote branch of the same name on the receiving end. Works in both central and non-central workflows.simple
: [available since Ver 1.7.11] in centralized workflow, work like upstream
with an added safety to refuse to push if the upstream branch’s name is different from the local one. When pushing to a remote that is different from the remote you normally pull from, work as current
. This is the safest option and is suited for beginners. This mode has become the default in Git 2.0.There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.
string formatted = date.ToString("dd-MM-yyyy");
will do it.
Here is a good reference for different formats.
You need to use MM
as mm
stands for minutes.
There are two ways of producing month pattern.
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); //outputs month in numeric way, 2013-02-01
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy"); // Outputs months as follows, 2013-Feb-01
Full coding snippet:
String startDate="01-Feb-2013"; // Input String
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); // New Pattern
java.util.Date date = sdf1.parse(startDate); // Returns a Date format object with the pattern
java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
System.out.println(sqlStartDate); // Outputs : 2013-02-01
*Not as far as i know there isn't what i do normally in this kind of circumstances is create a block beneath with a bigger size((bordersize*2)+originalsize) and make it transparent using
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
here is an example
#main{
width:400px;
overflow:hidden;
position:relative;
}
.border{
width:100%;
position:absolute;
height:100%;
background-color:#F00;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
.content{
margin:15px;/*size of border*/
background-color:black;
}
<div id="main">
<div class="border">
</div>
<div class="content">
testing
</div>
</div>
Update:
This answer is outdated, since after all this question is more than 8 years old. Today all up to date browsers support rgba, box shadows and so on. But this is a decent example how it was 8+ years ago.
Here is how to do this on Windows without third-party tools:
Import certificate to the certificate store. In Windows Explorer select "Install Certificate" in context menu. Follow the wizard and accept default options "Local User" and "Automatically".
Find your certificate in certificate store. On Windows 10 run the "Manage User Certificates" MMC. On Windows 2013 the MMC is called "Certificates". On Windows 10 by default your certificate should be under "Personal"->"Certificates" node.
Export Certificate. In context menu select "Export..." menu:
Select "Yes, export the private key":
You will see that .PFX option is enabled in this case:
Specify password for private key.
No, a comma-separated list is what you want in this case.
Consider using a subquery:
from p in context.ParentTable
let cCount =
(
from c in context.ChildTable
where p.ParentId == c.ChildParentId
select c
).Count()
select new { ParentId = p.Key, Count = cCount } ;
If the query types are connected by an association, this simplifies to:
from p in context.ParentTable
let cCount = p.Children.Count()
select new { ParentId = p.Key, Count = cCount } ;
Many of the existing answers already touch the copy constructor, assignment operator and destructor. However, in post C++11, the introduction of move semantic may expand this beyond 3.
Recently Michael Claisse gave a talk that touches this topic: http://channel9.msdn.com/events/CPP/C-PP-Con-2014/The-Canonical-Class
This code here you give a list of strings of keys that you don't want to delete, then it filters those from all the keys in local storage then deletes the others.
const allKeys = Object.keys(localStorage);
const toBeDeleted = allKeys.filter(value => {
return !this.doNotDeleteList.includes(value);
});
toBeDeleted.forEach(value => {
localStorage.removeItem(value);
});
Python's built-in float
type has double precision (it's a C double
in CPython, a Java double
in Jython). If you need more precision, get NumPy and use its numpy.float128
.
Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.
openssl pkcs12 -in file.pfx -out file.pem -nodes
Then you can configure HAProxy to use the file.pem file.
This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.
openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
Then you can configure HAProxy to use the file.combo.pem file.
The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.
I went through this post and everything didnt want to work correctly and eventually pieced the bits together from a few answers so I have a 100% working demo and will paste it here for reference - paste this into a php file and make sure includes are in the right place.
<?php if (isset($_GET['typeahead'])){
die(json_encode(array('options' => array('like','spike','dike','ikelalcdass'))));
}
?>
<link href="bootstrap.css" rel="stylesheet">
<input type="text" class='typeahead'>
<script src="jquery-1.10.2.js"></script>
<script src="bootstrap.min.js"></script>
<script>
$('.typeahead').typeahead({
source: function (query, process) {
return $.get('index.php?typeahead', { query: query }, function (data) {
return process(JSON.parse(data).options);
});
}
});
</script>
To convert the Keys to a List of their own:
listNumber = dicNumber.Select(kvp => kvp.Key).ToList();
Or you can shorten it up and not even bother using select:
listNumber = dicNumber.Keys.ToList();
Building on other posted answers.
Both of these will produce the right values:
select distributor_id,
count(*) total,
sum(case when level = 'exec' then 1 else 0 end) ExecCount,
sum(case when level = 'personal' then 1 else 0 end) PersonalCount
from yourtable
group by distributor_id
SELECT a.distributor_id,
(SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
(SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
(SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM myTable a ;
However, the performance is quite different, which will obviously be more relevant as the quantity of data grows.
I found that, assuming no indexes were defined on the table, the query using the SUMs would do a single table scan, while the query with the COUNTs would do multiple table scans.
As an example, run the following script:
IF OBJECT_ID (N't1', N'U') IS NOT NULL
drop table t1
create table t1 (f1 int)
insert into t1 values (1)
insert into t1 values (1)
insert into t1 values (2)
insert into t1 values (2)
insert into t1 values (2)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
SELECT SUM(CASE WHEN f1 = 1 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 2 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 3 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 4 THEN 1 else 0 end)
from t1
SELECT
(select COUNT(*) from t1 where f1 = 1),
(select COUNT(*) from t1 where f1 = 2),
(select COUNT(*) from t1 where f1 = 3),
(select COUNT(*) from t1 where f1 = 4)
Highlight the 2 SELECT statements and click on the Display Estimated Execution Plan icon. You will see that the first statement will do one table scan and the second will do 4. Obviously one table scan is better than 4.
Adding a clustered index is also interesting. E.g.
Create clustered index t1f1 on t1(f1);
Update Statistics t1;
The first SELECT above will do a single Clustered Index Scan. The second SELECT will do 4 Clustered Index Seeks, but they are still more expensive than a single Clustered Index Scan. I tried the same thing on a table with 8 million rows and the second SELECT was still a lot more expensive.
You should put it into command line in windows.
mysqladmin -u [username] -p flush-hosts
**** [MySQL password]
or
mysqladmin flush-hosts -u [username] -p
**** [MySQL password]
For network login use the following command:
mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts
you can permanently solution your problem by editing my.ini file[Mysql configuration file] change variables max_connections = 10000;
or
login into MySQL using command line -
mysql -u [username] -p
**** [MySQL password]
put the below command into MySQL window
SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;
check veritable using command-
show variables like "max_connections";
show variables like "max_connect_errors";
Using ".h" method is better But if you really want to include the .cpp file then make foo(int) static in foo.cpp
Yes, you could make an indexer on your Record class that maps from the property name to the correct property. This would keep all the binding from property name to property in one place eg:
public class Record
{
public string ItemType { get; set; }
public string this[string propertyName]
{
set
{
switch (propertyName)
{
case "itemType":
ItemType = value;
break;
// etc
}
}
}
}
Alternatively, as others have mentioned, use reflection.
//String to Date Convert
var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)
//CONVERT FROM NSDate to String
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
Follow below steps:
1) First go to Server Explorer in Visual Studio, check if the ".mdf" Data Connections for this project are connected, if so, right click and delete.
2 )Go to Solution Explorer, click show All Files icon.
3) Go to App_Data, right click and delete all ".mdf" files for this project.
4) Delete Migrations folder by right click and delete.
5) Go to SQL Server Management Studio, make sure the DB for this project is not there, otherwise delete it.
6) Go to Package Manager Console in Visual Studio and type:
Enable-Migrations -Force
Add-Migration init
Update-Database
7) Run your application
Note: In step 6 part 3, if you get an error "Cannot attach the file...", it is possibly because you didn't delete the database files completely in SQL Server.
Verify what are you attempting to write. I was having the same issue, but I realized i was trying to write a byte array with length of 0.
It doesn't make sense to me, but I get: "Access to the path "
Note: if you upgrade from spring boot 1 to spring boot 2 there is a ResponseStatusException
which has a Http error code and a description.
So, you can effectively use generics they way it is intended.
The only case which is a bit challenging for me, is the response type for a status 204 (ok with no body). I tend to mark those methods as ResponseEntity<?>
, because ResponseEntity<Void>
is less predictive.
If you are using a framework like Ruby on Rails or Spring MVC you may need to use divs with square braces or other chars, that are not allowed you can use document.getElementById
and this solution still works if you have multiple inputs with the same type.
var div = document.getElementById(divID);
$(div).find('input:text, input:password, input:file, select, textarea')
.each(function() {
$(this).val('');
});
$(div).find('input:radio, input:checkbox').each(function() {
$(this).removeAttr('checked');
$(this).removeAttr('selected');
});
This examples shows how to clear the inputs, for you example you'll need to change it.
UILabel *helpLabel = [[UILabel alloc] init];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:label];
helpLabel.attributedText = attrString;
// helpLabel.text = label;
helpLabel.textAlignment = NSTextAlignmentCenter;
helpLabel.lineBreakMode = NSLineBreakByWordWrapping;
helpLabel.numberOfLines = 0;
For some reasons its not working for me in iOS 6 not sure why. Tried it with and without attributed text. Any suggestions.
try to fix type="JavaScript"
to type="text/javascript"
in you vue.js srcipt tag, or just remove it.
Modern browsers will take script tag as javascript as default.
You may use these...
Parameters:
%date:~4,2% -- month
%date:~7,2% -- days
%date:~10,4% -- years
%time:~1,1% -- hours
%time:~3,2% -- minutes
%time:~6,2% -- seconds
%time:~9,2% -- mili-seconds
%date:~4,2%%date:~7,2%%date:~10,4% : MMDDYYYY
%date:~7,2%%date:~4,2%%date:~10,4% : DDMMYYYY
%date:~10,4%%date:~4,2%%date:~7,2% : YYYYMMDD
Swift 5 Answer
I found this thread because I needed a Swift version of this question. As nobody has answered with the solution, here's mine:
extension UIColor {
var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return (red, green, blue, alpha)
}
func isSimilar(to colorB: UIColor) -> Bool {
let rgbA = self.rgba
let rgbB = colorB.rgba
let diffRed = abs(CGFloat(rgbA.red) - CGFloat(rgbB.red))
let diffGreen = abs(rgbA.green - rgbB.green)
let diffBlue = abs(rgbA.blue - rgbB.blue)
let pctRed = diffRed
let pctGreen = diffGreen
let pctBlue = diffBlue
let pct = (pctRed + pctGreen + pctBlue) / 3 * 100
return pct < 10 ? true : false
}
}
Usage:
let black: UIColor = UIColor.black
let white: UIColor = UIColor.white
let similar: Bool = black.isSimilar(to: white)
I set less than 10% difference to return similar colours, but you can customise this yourself.
Given an OnTouchListener
private View.OnTouchListener handleTouch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("TAG", "touched down");
break;
case MotionEvent.ACTION_MOVE:
Log.i("TAG", "moving: (" + x + ", " + y + ")");
break;
case MotionEvent.ACTION_UP:
Log.i("TAG", "touched up");
break;
}
return true;
}
};
set on some view:
myView.setOnTouchListener(handleTouch);
This gives you the touch event coordinates relative to the view that has the touch listener assigned to it. The top left corner of the view is (0, 0)
. If you move your finger above the view, then y
will be negative. If you move your finger left of the view, then x
will be negative.
int x = (int)event.getX();
int y = (int)event.getY();
If you want the coordinates relative to the top left corner of the device screen, then use the raw values.
int x = (int)event.getRawX();
int y = (int)event.getRawY();
There is a simple shell command "ascii",
if you use Ubuntu,just
sudo apt install ascii
then:
ascii 0x5a
will output:
ASCII 5/10 is decimal 090, hex 5a, octal 132, bits 01011010: prints as `Z'
Official name: Majuscule Z
Other names: Capital Z, Uppercase Z
Initializing a vector having struct, class or Union can be done this way
std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);
To show both string.Split
and Regex
usage:
string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
string[] parts2 = Regex.Split(input, @"\]\[");
I had a similar problem with phpmyAdmin. The column count in the file to be imported matched the columns in the target database table. I tried importing files in both .csv and .ods format to no avail, getting a variety of errors including one arguing that the column count was wrong.
Both the .csv and .ods files were created with LibreOffice 5.204. Based on a bit of experience with import issues in years past, I decided to remake the files with the gnumeric spreadsheet, exporting the .ods in compliance with the "strict" format standard. Voila! No more import problem. While I haven't had time to investigate the issue further, I suspect that something has changed in the internal structure of LibreOffice's file output.
While I like the class decorator from Oz123, you could also do the following, which uses an explicit class wrapper and __new__ with a class Factory method returning the class within a closure:
class B(object):
def __new__(cls, val):
return cls.factory(val)
@classmethod
def factory(cls, val):
private = {'var': 'test'}
class InnerB(object):
def __init__(self):
self.variable = val
pass
@property
def var(self):
return private['var']
return InnerB()
List membersList = Arrays.asList(membersArray);
returns immutable list, what you need to do is
new ArrayList<>(Arrays.asList(membersArray)); to make it mutable
Adding this late answer to show a case most people will come across. If you only need to see what is the last item in the list, use the last
key word:
<div *ngFor="let item of devcaseFeedback.reviewItems; let last = last">
<divider *ngIf="!last"></divider>
</div>
This will add the divider component to every item except the last.
Because of the comment below, I will add the rest of the ngFor
exported values that can be aliased to local variables (As are shown in the docs):
The URLs are passed in the request: request.getRequestURL()
.
If you mean other sites that are linking to you? You want to capture the HTTP Referrer, which you can do by calling:
request.getHeader("referer");
Use the timestamp you get by calling valueOf
on the date object:
var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours
I like daggett answer but there is another solution you can get try if your file is not big enough.
$file = __FILE__; // Let's take the current file just as an example.
$start_line = __LINE__ -1; // The same with the line what we look for. Take the line number where $line variable is declared as the start.
$lines_to_display = 5; // The number of lines to display. Displays only the $start_line if set to 1. If $lines_to_display argument is omitted displays all lines starting from the $start_line.
echo implode('', array_slice(file($file), $start_line, lines_to_display));
If you are using Query builder then you may use a blow
DB::table(Newsletter Subscription)
->select('*')
->whereIn('id', $send_users_list)
->get()
If you are working with Eloquent then you can use as below
$sendUsersList = Newsletter Subscription:: select ('*')
->whereIn('id', $send_users_list)
->get();
As @Hutch pointed out, one of the major limitations of sp_who2
is that it does not take any parameters so you cannot sort or filter it by default. You can save the results into a temp table, but then the you have to declare all the types ahead of time (and remember to DROP TABLE
).
Instead, you can just go directly to the source on master.dbo.sysprocesses
I've constructed this to output almost exactly the same thing that sp_who2
generates, except that you can easily add ORDER BY
and WHERE
clauses to get meaningful output.
SELECT spid,
sp.[status],
loginame [Login],
hostname,
blocked BlkBy,
sd.name DBName,
cmd Command,
cpu CPUTime,
physical_io DiskIO,
last_batch LastBatch,
[program_name] ProgramName
FROM master.dbo.sysprocesses sp
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
ORDER BY spid
Use ng-click
in place of onclick
. and its as simple as that:
<a href="www.mysite.com" ng-click="return theFunction();">Item</a>
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow
// the`href` property to follow through or not
}
</script>
Hemnath
If your variable is the percentage:
var myWidth = 70;
$('div#somediv').width(myWidth + '%');
If your variable is in pixels, and you want the percentage it take up of the parent:
var myWidth = 140;
var myPercentage = (myWidth / $('div#somediv').parent().width()) * 100;
$('div#somediv').width(myPercentage + '%');
Regarding building a DLL using MinGW, here are some very brief instructions.
First, you need to mark your functions for export, so they can be used by callers of the DLL. To do this, modify them so they look like (for example)
__declspec( dllexport ) int add2(int num){
return num + 2;
}
then, assuming your functions are in a file called funcs.c, you can compile them:
gcc -shared -o mylib.dll funcs.c
The -shared flag tells gcc to create a DLL.
To check if the DLL has actually exported the functions, get hold of the free Dependency Walker tool and use it to examine the DLL.
For a free IDE which will automate all the flags etc. needed to build DLLs, take a look at the excellent Code::Blocks, which works very well with MinGW.
Edit: For more details on this subject, see the article Creating a MinGW DLL for Use with Visual Basic on the MinGW Wiki.
EDIT: Consider looking at and upvoting Malvineous's answer on this page. Netmasks are a much more elegant solution.
Simply use a percent sign as a wildcard in the IP address.
From http://dev.mysql.com/doc/refman/5.1/en/grant.html
You can specify wildcards in the host name. For example,
user_name@'%.example.com'
applies touser_name
for any host in theexample.com
domain, anduser_name@'192.168.1.%'
applies touser_name
for any host in the192.168.1
class C subnet.
milliseconds = x
total = 0
while (milliseconds >= 1000) {
milliseconds = (milliseconds - 1000)
total = total + 1
}
hr = 0
min = 0
while (total >= 60) {
total = total - 60
min = min + 1
if (min >= 60) hr = hr + 1
if (min == 60) min = 0
}
sec = total
This is on groovy, but I thing that this is not problem for you. Method work perfect.
Nowadays people tend to use website builders (CMS like Wordpress) instead of coding their own blog from scratch. Even professional web developers do it because it's faster.
It would be nice if you could mention the advantages and things to keep in mind when coding your own blog in real life, for example:
Anyways, you can use css/css3 or JavaScript for making interactive webpage. Even you can upload your all sort of code into a server formatting the default blog theme.
You can use the built-in class XAttribute, which handles the encoding automatically:
using System.Xml.Linq;
XDocument doc = new XDocument();
List<XAttribute> attributes = new List<XAttribute>();
attributes.Add(new XAttribute("key1", "val1&val11"));
attributes.Add(new XAttribute("key2", "val2"));
XElement elem = new XElement("test", attributes.ToArray());
doc.Add(elem);
string xmlStr = doc.ToString();
Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.
Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people.
Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it.
I could see a situation like this making a detectable difference:
inline int aplusb_pow2(int a, int b) {
return (a + b)*(a + b) ;
}
for(int a = 0; a < 900000; ++a)
for(int b = 0; b < 900000; ++b)
aplusb_pow2(a, b);
Below a script that I used to remove all data from an SQL Server database
------------------------------------------------------------
/* Use database */
-------------------------------------------------------------
use somedatabase;
GO
------------------------------------------------------------------
/* Script to delete an repopulate the base [init database] */
------------------------------------------------------------------
-------------------------------------------------------------
/* Procedure delete all constraints */
-------------------------------------------------------------
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = 'sp_DeleteAllConstraints' AND type = 'P')
DROP PROCEDURE dbo.sp_DeleteAllConstraints
GO
CREATE PROCEDURE sp_DeleteAllConstraints
AS
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL'
GO
-----------------------------------------------------
/* Procedure delete all data from the database */
-----------------------------------------------------
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = 'sp_DeleteAllData' AND type = 'P')
DROP PROCEDURE dbo.sp_DeleteAllData
GO
CREATE PROCEDURE sp_DeleteAllData
AS
EXEC sp_MSForEachTable 'DELETE FROM ?'
GO
-----------------------------------------------
/* Procedure enable all constraints */
-----------------------------------------------
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = 'sp_EnableAllConstraints' AND type = 'P')
DROP PROCEDURE dbo.sp_EnableAllConstraints
GO
-- ....
-- ....
-- ....
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b><centre>Redirecting to Google<br>");
response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url after 5 seconds
pw.close();
}
}
First get the instance of SharedPreferences using
SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
Now to save the values in the SharedPreferences
Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();
Above lines will write username and password to preference
Now to to retrieve saved values from preference, you can follow below lines of code
String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");
(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)
Is the snippet you posted just a sample to show what you are trying to do?
The reason I ask is that you've named a method increment
, but you seem to be using that to set the value of a text label, rather than incrementing a value.
If you are trying to do something more complicated - such as setting an integer value and having the label display this value, you could consider using bindings. e.g
You declare a property count
and your increment
action sets this value to whatever, and then in IB, you bind the label's text to the value of count
. As long as you follow Key Value Coding (KVC) with count
, you don't have to write any code to update the label's display. And from a design perspective you've got looser coupling.
In my case, I found that I set the post method as private mistakenly. after changing private to public.
[HttpPost]
private async Task<ActionResult> OnPostRemoveForecasting(){}
change to
[HttpPost]
public async Task<ActionResult> OnPostRemoveForecasting(){}
Now works fine.
1.) Storage of database passwords Use some kind of hash with a salt and then alter the hash, obfuscate it, for example add a distinct value for each byte. That way your passwords a super secured against dictionary attacks and rainbow tables.
2.) To check if the password matches, create your hash for the password the user put in. Then perform a query against the database for the username and just check if the two password hashes are identical. If they are, give the user an authentication token.
The query should then look like this:
select hashedPassword from users where username=?
Then compare the password to the input.
Further questions?
AskTom is probably the single most helpful resource on best practices on Oracle DBs. (I usually just type "asktom" as the first word of a google query on a particular topic)
I don't think it's really appropriate to speak of design patterns with relational databases. Relational databases are already the application of a "design pattern" to a problem (the problem being "how to represent, store and work with data while maintaining its integrity", and the design being the relational model). Other approches (generally considered obsolete) are the Navigational and Hierarchical models (and I'm nure many others exist).
Having said that, you might consider "Data Warehousing" as a somewhat separate "pattern" or approach in database design. In particular, you might be interested in reading about the Star schema.
If you want to use FragmentStatePagerAdapter, please take a look at https://code.google.com/p/android/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&groupby=&sort=&id=37990. There are issues with FragmentStatePagerAdapter that may or may not trouble your use case.
Also, link has few solutions too..few may suit to your requirement.
import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
print 'matched'
You can execute it just as you select a table using SELECT
clause. In addition you can provide parameters within parentheses.
Try with below syntax:
SELECT * FROM yourFunctionName(parameter1, parameter2)
Perhaps you can try to BeginInvoke a delegate pointing to your method like so:
delegate string SynchOperation(string value);
class Program
{
static void Main(string[] args)
{
BeginTheSynchronousOperation(CallbackOperation, "my value");
Console.ReadLine();
}
static void BeginTheSynchronousOperation(AsyncCallback callback, string value)
{
SynchOperation op = new SynchOperation(SynchronousOperation);
op.BeginInvoke(value, callback, op);
}
static string SynchronousOperation(string value)
{
Thread.Sleep(10000);
return value;
}
static void CallbackOperation(IAsyncResult result)
{
// get your delegate
var ar = result.AsyncState as SynchOperation;
// end invoke and get value
var returned = ar.EndInvoke(result);
Console.WriteLine(returned);
}
}
Then use the value in the method you sent as AsyncCallback to continue..
Use <br>
tags
<div class="container">
<div class="row" id="a">
<img src="http://placehold.it/300">
</div>
<br><br> <!--insert one, two, or more here-->
<div class="row" id="b">
<button>Hello</button>
</div>
</div>
If you want to compare with a particular date , You can directly write it like :
select * from `table_name` where timestamp >= '2018-07-07';
// here the timestamp is the name of the column having type as timestamp
or
For fetching today date , CURDATE() function is available , so :
select * from `table_name` where timestamp >= CURDATE();
I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.
Bootstrap requires a specific file structure to work. I see from your code you have this:
<link href="bootstrap.css" rel="stylesheet" media="screen">
Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.
But first, let me recommend you setup your folder structure like so:
/css <-- Bootstrap.css here
/fonts <-- Bootstrap fonts here
/img
/js <-- Bootstrap JavaScript here
index.html
If you notice, this is also how Bootstrap structures its files in its download ZIP.
You then include your Bootstrap file like so:
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">
Depending on your server structure or what you're going for.
The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).
The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.
So, why do this?
Bootstrap.css has this specific line for Glyphfonts:
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
What you can see is that that Glyphfonts are loaded by going up one directory ../
and then looking for a folder called /fonts
and THEN loading the font file.
The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:
/fonts
Bootstrap.css
index.html
The CSS file is going one level deeper than looking for a /fonts
folder.
So, let's say the actual location of these files are:
C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html
The CSS file would technically be looking for a folder at:
C:\fonts
but your folder is actually in:
C:\www\fonts
So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.
When you get that fixed, your HTML should simply be:
<span class="glyphicon glyphicon-comment"></span>
Note, you need both classes. The first class glyphicon
sets up the basic styles while glyphicon-comment
sets the specific image.
If you want to do it typed:
class Something {
areas: Area[][];
constructor() {
this.areas = new Array<Array<Area>>();
for (let y = 0; y <= 100; y++) {
let row:Area[] = new Array<Area>();
for (let x = 0; x <=100; x++){
row.push(new Area(x, y));
}
this.areas.push(row);
}
}
}
css
.table:nth-child(2n+1) {
background-color: whatever color !important;
}
html
<ion-row class="nameClass" justify-content-center align-items-center style='height: 100%'>
<ion-col>
<div>
<strong>name</strong>
</div>
</ion-col>
<ion-col>
<div>
<strong>name</strong>
</div>
</ion-col>
<ion-col>
<div>
<strong>name</strong>
</div>
</ion-col>
<ion-col>
<div>
<strong>name</strong>
</div>
</ion-col>
<ion-col>
<div text-center>
<strong>name</strong>
</div>
</ion-col>
</ion-row>
row 2
<ion-col >
<div>
name
</div>
</ion-col>
<ion-col >
<div>
name
</div>
</ion-col>
<ion-col >
<div>
name
</div>
</ion-col>
<ion-col>
<div>
name
</div>
</ion-col>
<ion-col>
<div>
<button>name</button>
</div>
</ion-col>
Are you using the Team Synchronise view? If so that's the problem. Conflict resolution in the Team Synchronise view doesn't work with EGit. Instead you need to use the Git Repository view.
Open the Git perspective. In the Git Repository view, go to on Branches ? Local ? master and right click ? Merge...
It should auto select Remote Tracking ? origin/master
. Press Merge.
It should show result:conflict
.
Open the conflicting files. They should have an old sk000l >>>> ===== <<<< style merge conflict in the files. Edit the file to resolve the conflict, and save.
Now in the 'Git Staging' view, it should show the changed file in 'Unstaged Changes'. Right click and 'Add to Index'
Repeat for any remaining files.
Now from the 'git staging' view, commit and push. As Git/Eclipse now knows that you have merged the remote origin changes into your master, you should avoid the non-fast-forward error.
I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)
Thanks!
Change
var trainindIdArray = traingIds.split(',');
to
var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');
That will basically remove [
and ]
and then split the string
#include<iostream>
int main()
{//initialize variables
int limit;
int num;
int sum=0;
int counter=0;
cout<<"Enter limit of numbers you wish to see"<<" ";
cin>>limit;
cout<<endl;
while(counter<limit)
{
cout<<"Enter number "<<endl;
cin>>num;
sum=sum+num;
counter++;
}
cout<<"The sum of numbers is "<<" "<<endl
return 0;
}
So I was looking at all the answers.. didn't like most.. took some from a few.. made this:
const resolveRoutes = (stack) => {
return stack.map(function (layer) {
if (layer.route && layer.route.path.isString()) {
let methods = Object.keys(layer.route.methods);
if (methods.length > 20)
methods = ["ALL"];
return {methods: methods, path: layer.route.path};
}
if (layer.name === 'router') // router middleware
return resolveRoutes(layer.handle.stack);
}).filter(route => route);
};
const routes = resolveRoutes(express._router.stack);
const printRoute = (route) => {
if (Array.isArray(route))
return route.forEach(route => printRoute(route));
console.log(JSON.stringify(route.methods) + " " + route.path);
};
printRoute(routes);
not the prettiest.. but nested, and does the trick
also note the 20 there... I just assume there will not be a normal route with 20 methods.. so I deduce it is all..
The referenced column must be an index of a single column or the first column in multi column index, and the same type and the same collation.
My two tables have the different collations. It can be shown by issuing show table status like table_name
and collation can be changed by issuing alter table table_name
convert to character set utf8.
In c++11 you can use:
for ( auto iter : table ) {
key=iter->first;
value=iter->second;
}
The concept of a HOME directory seems to be a bit vague when it comes to Windows. If the environment variables (HOMEDRIVE/HOMEPATH/USERPROFILE) aren't enough, you may have to resort to using native functions via JNI or JNA. SHGetFolderPath allows you to retrieve special folders, like My Documents (CSIDL_PERSONAL) or Local Settings\Application Data (CSIDL_LOCAL_APPDATA).
Sample JNA code:
public class PrintAppDataDir {
public static void main(String[] args) {
if (com.sun.jna.Platform.isWindows()) {
HWND hwndOwner = null;
int nFolder = Shell32.CSIDL_LOCAL_APPDATA;
HANDLE hToken = null;
int dwFlags = Shell32.SHGFP_TYPE_CURRENT;
char[] pszPath = new char[Shell32.MAX_PATH];
int hResult = Shell32.INSTANCE.SHGetFolderPath(hwndOwner, nFolder,
hToken, dwFlags, pszPath);
if (Shell32.S_OK == hResult) {
String path = new String(pszPath);
int len = path.indexOf('\0');
path = path.substring(0, len);
System.out.println(path);
} else {
System.err.println("Error: " + hResult);
}
}
}
private static Map<String, Object> OPTIONS = new HashMap<String, Object>();
static {
OPTIONS.put(Library.OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);
OPTIONS.put(Library.OPTION_FUNCTION_MAPPER,
W32APIFunctionMapper.UNICODE);
}
static class HANDLE extends PointerType implements NativeMapped {
}
static class HWND extends HANDLE {
}
static interface Shell32 extends Library {
public static final int MAX_PATH = 260;
public static final int CSIDL_LOCAL_APPDATA = 0x001c;
public static final int SHGFP_TYPE_CURRENT = 0;
public static final int SHGFP_TYPE_DEFAULT = 1;
public static final int S_OK = 0;
static Shell32 INSTANCE = (Shell32) Native.loadLibrary("shell32",
Shell32.class, OPTIONS);
/**
* see http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx
*
* HRESULT SHGetFolderPath( HWND hwndOwner, int nFolder, HANDLE hToken,
* DWORD dwFlags, LPTSTR pszPath);
*/
public int SHGetFolderPath(HWND hwndOwner, int nFolder, HANDLE hToken,
int dwFlags, char[] pszPath);
}
}
You can't directly control this, because it's an option controlled by Internet Explorer users.
Opening pages using Window.open with a different window name will open in a new browser window like a popup, OR open in a new tab, if the user configured the browser to do so.
EDIT:
A more detailed explanation:
1. In modern browsers, window.open will open in a new tab rather than a popup.
2. You can force a browser to use a new window (‘popup’) by specifying options in the 3rd parameter
3. If the window.open call was not part of a user-initiated event, it’ll open in a new window.
4. A “user initiated event” does not have to the same function call – but it must originate in the function invoked by a user click
5. If a user initiated event delegates or defers a function call (in an event listener or delegate not bound to the click event, or by using setTimeout for example), it loses it’s status as “user initiated”
6. Some popup blockers will allow windows opened from user initiated events, but not those opened otherwise.
7. If any popup is blocked, those normally allowed by a blocker (via user initiated events) will sometimes also be blocked. Some examples…
Forcing a window to open in a new browser instance, instead of a new tab:
window.open('page.php', '', 'width=1000');
The following would qualify as a user-initiated event, even though it calls another function:
function o(){
window.open('page.php');
}
$('button').addEvent('click', o);
The following would not qualify as a user-initiated event, since the setTimeout defers it:
function g(){
setTimeout(o, 1);
}
function o(){
window.open('page.php');
}
$('button').addEvent('click', g);
In his paper, Memory Optimization, Christer Ericson says that while restrict
is not part of the C++ standard yet, that it is supported by many compilers and he recommends it's usage when available:
restrict keyword
! New to 1999 ANSI/ISO C standard
! Not in C++ standard yet, but supported by many C++ compilers
! A hint only, so may do nothing and still be conforming
A restrict-qualified pointer (or reference)...
! ...is basically a promise to the compiler that for the scope of the pointer, the target of the pointer will only be accessed through that pointer (and pointers copied from it).
In C++ compilers that support it it should probably behave the same as in C.
See this SO post for details: Realistic usage of the C99 ‘restrict’ keyword?
Take half an hour to skim through Ericson's paper, it's interesting and worth the time.
Edit
I also found that IBM's AIX C/C++ compiler supports the __restrict__
keyword.
g++ also seems to support this as the following program compiles cleanly on g++:
#include <stdio.h>
int foo(int * __restrict__ a, int * __restrict__ b) {
return *a + *b;
}
int main(void) {
int a = 1, b = 1, c;
c = foo(&a, &b);
printf("c == %d\n", c);
return 0;
}
I also found a nice article on the use of restrict
:
Demystifying The Restrict Keyword
Edit2
I ran across an article which specifically discusses the use of restrict in C++ programs:
Load-hit-stores and the __restrict keyword
Also, Microsoft Visual C++ also supports the __restrict
keyword.
Use StringBuilder
class. It is more efficient at what you are trying to do.
Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times
According to your requirement :
1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD
I tried
Document.getElementsByClassName('option0')
Which resulted in the error: Uncaught TypeError: Document.getElementsByClass is not a function
After that I tried:
document.getElementsByClassName('option0')
And it works!
This has worked for me in the past and it will even expand environment variables in the file if it can.
for /F "delims=" %%a in (LogName.txt) do (
echo %%a>>MyDestination.txt
)
First to answer your question, you set a variable to true or false by assigning True
or False
to it:
myFirstVar = True
myOtherVar = False
If you have a condition that is basically like this though:
if <condition>:
var = True
else:
var = False
then it is much easier to simply assign the result of the condition directly:
var = <condition>
In your case:
match_var = a == b
Swift 4:
extension String {
/// the length of the string
var length: Int {
return self.characters.count
}
/// Get substring, e.g. "ABCDE".substring(index: 2, length: 3) -> "CDE"
///
/// - parameter index: the start index
/// - parameter length: the length of the substring
///
/// - returns: the substring
public func substring(index: Int, length: Int) -> String {
if self.length <= index {
return ""
}
let leftIndex = self.index(self.startIndex, offsetBy: index)
if self.length <= index + length {
return self.substring(from: leftIndex)
}
let rightIndex = self.index(self.endIndex, offsetBy: -(self.length - index - length))
return self.substring(with: leftIndex..<rightIndex)
}
/// Get substring, e.g. -> "ABCDE".substring(left: 0, right: 2) -> "ABC"
///
/// - parameter left: the start index
/// - parameter right: the end index
///
/// - returns: the substring
public func substring(left: Int, right: Int) -> String {
if length <= left {
return ""
}
let leftIndex = self.index(self.startIndex, offsetBy: left)
if length <= right {
return self.substring(from: leftIndex)
}
else {
let rightIndex = self.index(self.endIndex, offsetBy: -self.length + right + 1)
return self.substring(with: leftIndex..<rightIndex)
}
}
}
you can test it as follows:
print("test: " + String("ABCDE".substring(index: 2, length: 3) == "CDE"))
print("test: " + String("ABCDE".substring(index: 0, length: 3) == "ABC"))
print("test: " + String("ABCDE".substring(index: 2, length: 1000) == "CDE"))
print("test: " + String("ABCDE".substring(left: 0, right: 2) == "ABC"))
print("test: " + String("ABCDE".substring(left: 1, right: 3) == "BCD"))
print("test: " + String("ABCDE".substring(left: 3, right: 1000) == "DE"))
Check https://gitlab.com/seriyvolk83/SwiftEx library. It contains these and other helpful methods.
Use toString
when you need to display the name to the user.
Use name
when you need the name for your program itself, e.g. to identify and differentiate between different enum values.
Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.
So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.
In my case,
IIS can load everything with localhost
, but could not load my template files app.tag
from 192.168.0.123
because the .tag
extension was not in the list.
One should be clear about definitions. As used here:
The hostname is subject to the restrictions of RFC 952 and the slight relaxation of RFC 1123
RFC 2181 makes clear that there is a difference between a domain name and a hostname:
...[the fact that] any binary label can have an MX record does not imply that any binary name can be used as the host part of an e-mail address...
So underscores in hostnames are a no-no, underscores in domain names are a-ok.
In practice, one may well see hostnames with underscores. As the Robustness Principle says: "Be conservative in what you send, liberal in what you accept".
In the 21st century, it turns out that hostnames as well as domain names may be internationalized! This means resorting to encodings in case of labels that contain characters that are outside the allowed set.
In particular, it allows one to encode the _
in hostnames (Update 2017-07: This is doubtful, see comments. The _
still cannot be used in hostnames. Indeed, it cannot even be used in internationalized labels.)
The first RFC for internationalization was RFC 3490 of March 2003, "Internationalizing Domain Names in Applications (IDNA)". Today, we have:
You may also want to check the Wikipedia Entry
RFC 5890 introduces the term LDH (Letter-Digit-Hypen) label for labels used in hostnames and says:
This is the classical label form used, albeit with some additional restrictions, in hostnames (RFC 952). Its syntax is identical to that described as the "preferred name syntax" in Section 3.5 of RFC 1034 as modified by RFC 1123. Briefly, it is a string consisting of ASCII letters, digits, and the hyphen with the further restriction that the hyphen cannot appear at the beginning or end of the string. Like all DNS labels, its total length must not exceed 63 octets.
Going back to simpler times, this Internet draft is an early proposal for hostname internationalization. Hostnames with international characters may be encoded using, for example, 'RACE' encoding.
The author of the 'RACE encoding' proposal notes:
According to RFC 1035, host parts must be case-insensitive, start and end with a letter or digit, and contain only letters, digits, and the hyphen character ("-"). This, of course, excludes any internationalized characters, as well as many other characters in the ASCII character repertoire. Further, domain name parts must be 63 octets or shorter in length.... All post-converted name parts that contain internationalized characters begin with the string "bq--". (...) The string "bq--" was chosen because it is extremely unlikely to exist in host parts before this specification was produced.
The problem might be the following: SVN ignores .a files because of its global config, which means someone didn't commit the libGoogleAnalytics.a to SVN, because it didn't show up in SVN. So now you try to check out the project from SVN which now misses the libGoogleAnalytics.a (since it was ignored and was not committed). Of course the build fails.
You might want to change the global ignore config from SVN to stop ignoring *.a files.
Or just add the one missing libGoogleAnalytics.a file manually to your SVN working copy instead of changing SVNs global ignore config.
Then re-add libGoogleAnalytics.a to your XCode project and commit it to SVN.
You can do it from code by placing the following code in Window Loaded
event handler, for example:
yourComboBox.ItemsSource = Enum.GetValues(typeof(EffectStyle)).Cast<EffectStyle>();
If you need to bind it in XAML you need to use ObjectDataProvider
to create object available as binding source:
<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects">
<Window.Resources>
<ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="StyleAlias:EffectStyle"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
SelectedItem="{Binding Path=CurrentEffectStyle}" />
</Grid>
</Window>
Draw attention on the next code:
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects"
Guide how to map namespace and assembly you can read on MSDN.
console.log
works.
By default on iOS, it logs to the debug pane inside Xcode.
From the IOS simulator press (?+D) and press Remote JS Debugging. This will open a resource, http://localhost:8081/debugger-ui on localhost. From there use Chrome Developer tools javascript console to view console.log
CREATE TABLE target_table SELECT * FROM source_table;
It just create a new table with same structure as of source table and also copy all rows from source_table into target_table.
CREATE TABLE target_table SELECT * FROM source_table WHERE condition;
If you need some rows to be copied into target_table, then apply a condition inside where clause
to remove your current version you could just run:
sudo gem uninstall cocoapods
you can install a specific version of cocoa pods via the following command:
sudo gem install cocoapods -v 0.25.0
You can use older installed versions with following command:
pod _0.25.0_ setup
A return in a lambda equals a continue in a for-each, but there is no equivalent to a break. You can just do a return to continue:
someObjects.forEach(obj -> {
if (some_condition_met) {
return;
}
})
The problem happens because in same hibernate session you are trying to save two objects with same identifier.There are two solutions:-
This is happening because you have not configured your mapping.xml file correctly for id fields as below:-
<id name="id">
<column name="id" sql-type="bigint" not-null="true"/>
<generator class="hibernateGeneratorClass"</generator>
</id>
Overload the getsession method to accept a Parameter like isSessionClear, and clear the session before returning the current session like below
public static Session getSession(boolean isSessionClear) {
if (session.isOpen() && isSessionClear) {
session.clear();
return session;
} else if (session.isOpen()) {
return session;
} else {
return sessionFactory.openSession();
}
}
This will cause existing session objects to be cleared and even if hibernate doesn't generate a unique identifier ,assuming you have configured your database properly for a primary key using something like Auto_Increment,it should work for you.
The easiest way I've found to place objects on the left is using FlowLayout.
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
adding a component normally to this panel will place it on the left
If the project came with a Visual Studio project file, then that should already be configured to find the headers for you. If not, you'll have to add the include file directory to the project settings by right-clicking the project and selecting Properties, clicking on "C/C++", and adding the directory containing the include files to the "Additional Include Directories" edit box.
Knowledge of high level programming languages (C/C++, Java, PHP, Python, Perl, etc.) would suggest to the layman that Bourne Again Shell (Bash) functions should work like they do in those other languages.
Instead, Bash functions work like shell commands and expect arguments to be passed to them in the same way one might pass an option to a shell command (e.g. ls -l
). In effect, function arguments in Bash are treated as positional parameters ($1, $2..$9, ${10}, ${11}
, and so on). This is no surprise considering how getopts
works. Do not use parentheses to call a function in Bash.
(Note: I happen to be working on OpenSolaris at the moment.)
# Bash style declaration for all you PHP/JavaScript junkies. :-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
function backupWebRoot ()
{
tar -cvf - "$1" | zip -n .jpg:.gif:.png "$2" - 2>> $errorlog &&
echo -e "\nTarball created!\n"
}
# sh style declaration for the purist in you. ;-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
backupWebRoot ()
{
tar -cvf - "$1" | zip -n .jpg:.gif:.png "$2" - 2>> $errorlog &&
echo -e "\nTarball created!\n"
}
# In the actual shell script
# $0 $1 $2
backupWebRoot ~/public/www/ webSite.tar.zip
Want to use names for variables? Just do something this.
local filename=$1 # The keyword declare can be used, but local is semantically more specific.
Be careful, though. If an argument to a function has a space in it, you may want to do this instead! Otherwise, $1
might not be what you think it is.
local filename="$1" # Just to be on the safe side. Although, if $1 was an integer, then what? Is that even possible? Humm.
Want to pass an array to a function?
callingSomeFunction "${someArray[@]}" # Expands to all array elements.
Inside the function, handle the arguments like this.
function callingSomeFunction ()
{
for value in "$@" # You want to use "$@" here, not "$*" !!!!!
do
:
done
}
Need to pass a value and an array, but still use "$@" inside the function?
function linearSearch ()
{
local myVar="$1"
shift 1 # Removes $1 from the parameter list
for value in "$@" # Represents the remaining parameters.
do
if [[ $value == $myVar ]]
then
echo -e "Found it!\t... after a while."
return 0
fi
done
return 1
}
linearSearch $someStringValue "${someArray[@]}"
pip list
shows ALL installed packages.
pip freeze
shows packages YOU installed via pip
(or pipenv
if using that tool) command in a requirements format.
Remark below that setuptools, pip, wheel are installed when pipenv shell
creates my virtual envelope. These packages were NOT installed by me using pip
:
test1 % pipenv shell
Creating a virtualenv for this project…
Pipfile: /Users/terrence/Development/Python/Projects/test1/Pipfile
Using /usr/local/Cellar/pipenv/2018.11.26_3/libexec/bin/python3.8 (3.8.1) to create virtualenv…
? Creating virtual environment...
<SNIP>
Installing setuptools, pip, wheel...
done.
? Successfully created virtual environment!
<SNIP>
Now review & compare the output of the respective commands where I've only installed cool-lib and sampleproject (of which peppercorn is a dependency):
test1 % pip freeze <== Packages I'VE installed w/ pip
-e git+https://github.com/gdamjan/hello-world-python-package.git@10<snip>71#egg=cool_lib
peppercorn==0.6
sampleproject==1.3.1
test1 % pip list <== All packages, incl. ones I've NOT installed w/ pip
Package Version Location
------------- ------- --------------------------------------------------------------------------
cool-lib 0.1 /Users/terrence/.local/share/virtualenvs/test1-y2Zgz1D2/src/cool-lib <== Installed w/ `pip` command
peppercorn 0.6 <== Dependency of "sampleproject"
pip 20.0.2
sampleproject 1.3.1 <== Installed w/ `pip` command
setuptools 45.1.0
wheel 0.34.2
ORDER BY: sort the data in ascending or descending order.
Consider the CUSTOMERS table:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would sort the result in ascending order by NAME:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME;
This would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
GROUP BY: arrange identical data into groups.
Now, CUSTOMERS table has the following records with duplicate names:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
if you want to group identical names into single name, then GROUP BY query would be as follows:
SQL> SELECT * FROM CUSTOMERS
GROUP BY NAME;
This would produce the following result: (for identical names it would pick the last one and finally sort the column in ascending order)
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
+----+----------+-----+-----------+----------+
as you have inferred that it is of no use without SQL functions like sum,avg etc..
so go through this definition to understand the proper use of GROUP BY:
A GROUP BY clause works on the rows returned by a query by summarizing identical rows into a single/distinct group and returns a single row with the summary for each group, by using appropriate Aggregate function in the SELECT list, like COUNT(), SUM(), MIN(), MAX(), AVG(), etc.
Now, if you want to know the total amount of salary on each customer(name), then GROUP BY query would be as follows:
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;
This would produce the following result: (sum of the salaries of identical names and sort the NAME column after removing identical names)
+---------+-------------+
| NAME | SUM(SALARY) |
+---------+-------------+
| Hardik | 8500.00 |
| kaushik | 8500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 3500.00 |
+---------+-------------+
Simply replace it with nothing:
var string = 'F0123456'; // just an example
string.replace(/^F0+/i, ''); '123456'
ImageView
: setImageResource()
(standard method, aspect ratio is kept)
View
: setBackgroundResource()
(image is stretched)
Both
My fuller answer is here.
I am new to Rust, but this solution seems to work:
#[macro_use]
extern crate lazy_static;
use std::sync::{Arc, Mutex};
lazy_static! {
static ref GLOBAL: Arc<Mutex<GlobalType> =
Arc::new(Mutex::new(GlobalType::new()));
}
Another solution is to declare a crossbeam channel tx/rx pair as an immutable global variable. The channel should be bounded and can only hold 1 element. When you initialize the global variable, push the global instance into the channel. When using the global variable, pop the channel to acquire it and push it back when done using it.
Both solutions should provide a safe approach to using global variables.
The question, is the provided example just an "example" or exact what you looking for? There are many mixed answers here, and I dont understand the complexibility of the accepted one.
To find out if ANY content of the array of needles exists in the string, and quickly return true or false:
$string = 'abcdefg';
if(str_replace(array('a', 'c', 'd'), '', $string) != $string){
echo 'at least one of the needles where found';
};
If, so, please give @Leon credit for that.
To find out if ALL values of the array of needles exists in the string, as in this case, all three 'a', 'b'
and 'c'
MUST be present, like you mention as your "for example"
echo 'All the letters are found in the string!';
Many answers here is out of that context, but I doubt that the intension of the question as you marked as resolved. E.g. The accepted answer is a needle of
$array = array('burger', 'melon', 'cheese', 'milk');
What if all those words MUST be found in the string?
Then you try out some "not accepted answers"
on this page.
in Jquery "data" doesn't refresh by default :
alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data("myval","20"); //setter
alert($('#outer').html());
You'd use "attr" instead for live update:
alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());
Try This:
myint.ToString().Length
Does that work ?
Try this:
INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';
I suggest you do some experiments using "make". Here is a simple demo, showing the difference between =
and :=
.
/* Filename: Makefile*/
x := foo
y := $(x) bar
x := later
a = foo
b = $(a) bar
a = later
test:
@echo x - $(x)
@echo y - $(y)
@echo a - $(a)
@echo b - $(b)
make test
prints:
x - later
y - foo bar
a - later
b - later bar
It may means that you forgot include a header file that define this struct/union. For example:
foo.h file:
typedef union
{
struct
{
uint8_t FIFO_BYTES_AVAILABLE : 4;
uint8_t STATE : 3;
uint8_t CHIP_RDY : 1;
};
uint8_t status;
} RF_CHIP_STATUS_t;
RF_CHIP_STATUS_t getStatus();
main.c file:
.
.
.
if (getStatus().CHIP_RDY) /* This will generate the error, you must add the #include "foo.h" */
.
.
.
To understand how a docker image was built, use the
docker history --no-trunc
command.
You can build a docker file from an image, but it will not contain everything you would want to fully understand how the image was generated. Reasonably what you can extract is the MAINTAINER, ENV, EXPOSE, VOLUME, WORKDIR, ENTRYPOINT, CMD, and ONBUILD parts of the dockerfile.
The following script should work for you:
#!/bin/bash
docker history --no-trunc "$1" | \
sed -n -e 's,.*/bin/sh -c #(nop) \(MAINTAINER .*[^ ]\) *0 B,\1,p' | \
head -1
docker inspect --format='{{range $e := .Config.Env}}
ENV {{$e}}
{{end}}{{range $e,$v := .Config.ExposedPorts}}
EXPOSE {{$e}}
{{end}}{{range $e,$v := .Config.Volumes}}
VOLUME {{$e}}
{{end}}{{with .Config.User}}USER {{.}}{{end}}
{{with .Config.WorkingDir}}WORKDIR {{.}}{{end}}
{{with .Config.Entrypoint}}ENTRYPOINT {{json .}}{{end}}
{{with .Config.Cmd}}CMD {{json .}}{{end}}
{{with .Config.OnBuild}}ONBUILD {{json .}}{{end}}' "$1"
I use this as part of a script to rebuild running containers as images: https://github.com/docbill/docker-scripts/blob/master/docker-rebase
The Dockerfile is mainly useful if you want to be able to repackage an image.
The thing to keep in mind, is a docker image can actually just be the tar backup of a real or virtual machine. I have made several docker images this way. Even the build history shows me importing a huge tar file as the first step in creating the image...
Redirection of program output is performed by the shell.
grep ... > output.txt
grep
has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1)
man page for details, specifically the -C
and --color
options.
When you don't give a prototype for the function before using it, C assumes that it takes any number of parameters and returns an int. So when you first try to use do_something, that's the type of function the compiler is looking for. Doing this should produce a warning about an "implicit function declaration".
So in your case, when you actually do declare the function later on, C doesn't allow function overloading, so it gets pissy because to it you've declared two functions with different prototypes but with the same name.
Short answer: declare the function before trying to use it.
I hate to post my own answer, but some answers recently have ignored the solution I posted in my own question, suggesting approaches that are nothing short of foolhardy.
In short - you do not need to edit any Windows user account privileges at all. Doing so only introduces risk. The process is entirely managed in IIS using inherited privileges.
Right-click the domain when it appears under the Sites list, and choose Edit Permissions
Under the Security tab, you will see MACHINE_NAME\IIS_IUSRS
is listed. This means that IIS automatically has read-only permission on the directory (e.g. to run ASP.Net in the site). You do not need to edit this entry.
Click the Edit button, then Add...
In the text box, type IIS AppPool\MyApplicationPoolName
, substituting MyApplicationPoolName
with your domain name or whatever application pool is accessing your site, e.g. IIS AppPool\mydomain.com
Press the Check Names button. The text you typed will transform (notice the underline):
Press OK to add the user
With the new user (your domain) selected, now you can safely provide any Modify or Write permissions
Mine is that if you set MASM listing file option some extra selection, it will give you this error.
Just use
Enable Assembler Generated Code Listing Yes/Sg
Assembled Code Listing $(ProjectName).lst
it is fine.
But any extra you have issue.
Please use parenthesis () to access the list elements list_name(index)
Another late answer, but I was playing with this and came up with a general purpose Sass solution that I found useful and many others might as well. To give an overview, this introduces new classes that can modify the column count of a .card-columns
element in very similar ways to columns with .col-4
or .col-lg-3
:
@import "bootstrap";
$card-column-counts: 1, 2, 3, 4, 5;
.card-columns {
@each $column-count in $card-column-counts {
&.card-columns-#{$column-count} {
column-count: $column-count;
}
}
@each $breakpoint in map-keys($grid-breakpoints) {
@include media-breakpoint-up($breakpoint) {
$infix: breakpoint-infix($breakpoint, $grid-breakpoints);
@each $column-count in $card-column-counts {
&.card-columns#{$infix}-#{$column-count} {
column-count: $column-count;
}
}
}
}
}
The end result of this is if you have the following:
<div class="card-columns card-columns-2 card-columns-md-3 card-columns-xl-4">
...
</div>
Then you would have 2 columns by default, 3 for medium devices and up and 4 for xl devices and up. Additionally if you change your grid breakpoints this will automatically support those, and the $card-column-counts
can be overridden to change the allowed numbers of columns.
The working code
var jsonData = [{person:"me", age :"30"},{person:"you",age:"25"}];_x000D_
_x000D_
for(var obj in jsonData){_x000D_
if(jsonData.hasOwnProperty(obj)){_x000D_
for(var prop in jsonData[obj]){_x000D_
if(jsonData[obj].hasOwnProperty(prop)){_x000D_
alert(prop + ':' + jsonData[obj][prop]);_x000D_
}_x000D_
}_x000D_
}_x000D_
}
_x000D_
I don't think that they really are random, but my guess is those are some hashes.
Whenever I need some random identifier, I usually use a GUID and convert it to its "naked" representation:
Guid.NewGuid().ToString("n");
If you want difference in seconds
SELECT strftime('%s', '2019-12-02 12:32:53') - strftime('%s', '2019-12-02 11:32:53')
select * from Employee inner join [Order]
On Employee.Employee_id=[Order].Employee_id
inner join Book
On Book.Book_id=[Order].Book_id
inner join Book_Author
On Book_Author.Book_id=Book.Book_id
inner join Author
On Book_Author.Author_id=Author.Author_id;
Kathir's answer is great as he solves that problem with just jQuery. I just wanted to make some additions to his answer to work his code with a beautiful HTML progress bar:
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.progress-bar').width(percentComplete+'%');
$('.progress-bar').html(percentComplete+'%');
}
}, false);
return xhr;
},
url: posturlfile,
type: "POST",
data: JSON.stringify(fileuploaddata),
contentType: "application/json",
dataType: "json",
success: function(result) {
console.log(result);
}
});
Here is the HTML code of progress bar, I used Bootstrap 3 for the progress bar element:
<div class="progress" style="display:none;">
<div class="progress-bar progress-bar-success progress-bar-striped
active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style="width:0%">
0%
</div>
</div>
# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.
keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]
Trust this certificate: [Yes]
changeit is the default truststore password
You should reinstall Python:
brew reinstall python
To get brew see the brew homepage.
I got the 404 problem, because of Url Case Sensitivity.
For example
@RequestMapping(value = "/api/getEmployeeData",method = RequestMethod.GET)
should be accessed using http://www.example.com/api/getEmployeeData
. If we are using http://www.example.com/api/getemployeedata
, we'll get the 404 error.
Note:
http://www.example.com
is just for reference which i mentioned above. It should be your domain name where you hosted your application.
After a lot of struggle and apply all the other answers in this post, I got that the problem is with that url only. It might be silly problem. But it cost my 2 hours. So I hope it will help someone.
Local storage can store up to 5mb offline data, whereas session can also store up to 5 mb data. But cookies can store only 4kb data in text format.
LOCAl and Session storage data in JSON format, thus easy to parse. But cookies data is in string format.
It is not possible at all. Variable names aren't communicated within Java (and might also be removed due to compiler optimizations).
EDIT (related to comments):
If you step back from the idea of having to use it as function parameters, here's an alternative (which I wouldn't use - see below):
public void printFieldNames(Object obj, Foo... foos) {
List<Foo> fooList = Arrays.asList(foos);
for(Field field : obj.getClass().getFields()) {
if(fooList.contains(field.get()) {
System.out.println(field.getName());
}
}
}
There will be issues if a == b, a == r, or b == r
or there are other fields which have the same references.
EDIT now unnecessary since question got clarified
For nan of type float
>>> import pandas as pd
>>> value = float(nan)
>>> type(value)
>>> <class 'float'>
>>> pd.isnull(value)
True
>>>
>>> value = 'nan'
>>> type(value)
>>> <class 'str'>
>>> pd.isnull(value)
False
If you want a control to postback automatically when an event is raised, you need to set the AutoPostBack property of the control to True.
I was looking for the solution to show the label dynamically from database like this:
checkbox1 : Option 1 text from database
checkbox2 : Option 2 text from database
checkbox3 : Option 3 text from database
checkbox4 : Option 4 text from database
So none of the above solution worked for me so I used like this:
@Html.CheckBoxFor(m => m.Option1, new { @class = "options" })
<label for="Option1">@Model.Option1Text</label>
@Html.CheckBoxFor(m => m.Option2, new { @class = "options" })
<label for="Option2">@Mode2.Option1Text</label>
In this way when user will click on label, checkbox will be selected.
Might be it can help someone.
You can't, and you shouldn't.
Every other approach / alternative will only cause really bad user engagement.
That's my opinion.
To create an empty Array of Strings in Kotlin you should use one of the following six approaches:
First approach:
val empty = arrayOf<String>()
Second approach:
val empty = arrayOf("","","")
Third approach:
val empty = Array<String?>(3) { null }
Fourth approach:
val empty = arrayOfNulls<String>(3)
Fifth approach:
val empty = Array<String>(3) { "it = $it" }
Sixth approach:
val empty = Array<String>(0, { _ -> "" })
Try this to fix the error:
node_modules
directory.npm i gulp-sass@latest --save-dev
You can use jQuery .getJSON()
function:
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
// JSON result in `data` variable
});
If you don't want to use jQuery you should look at this answer for pure JS solution: https://stackoverflow.com/a/2499647/1361042
I think the correct solution with support library 21 is the following
// action_bar is def resource of appcompat;
// if you have not provided your own toolbar I mean
Toolbar toolbar = (Toolbar) findViewById(R.id.action_bar);
if (toolbar != null) {
// change home icon if you wish
toolbar.setLogo(this.getResValues().homeIconDrawable());
toolbar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//catch here title and home icon click
}
});
}
It Happened to me also you may have two solue=tion for this
If your project consist of some external or project specificdependency in it then you have to manually add it to your M2 repo folder which is located at C:\Users\Mohit.Singh.m2\repository folder and then you have to run mvn eclipse:eclipse and then mvn clean install from the project folder
if you do not have any wxternal or project sppecific dependency then you may import the project into eclipse as Existing maven project then right click on project --> GO to maven --> Click on update project a window will appear check the force snapshot download option and hit on OK
You could try to find it via the command line.
find / -type f -name "php.ini"
Or you could add the following to a .htaccess
file in the root of your site.
php_value max_input_vars 6000
php_value suhosin.get.max_vars 6000
php_value suhosin.post.max_vars 6000
php_value suhosin.request.max_vars 6000
Another way of doing this is using border-image in combination with a linear-gradient.
div {_x000D_
width: 100px;_x000D_
height: 75px;_x000D_
background-color: green;_x000D_
background-clip: content-box; /* so that the background color is not below the border */_x000D_
_x000D_
border-left: 5px solid black;_x000D_
border-image: linear-gradient(to top, #000 50%, rgba(0,0,0,0) 50%); /* to top - at 50% transparent */_x000D_
border-image-slice: 1;_x000D_
}
_x000D_
<div></div>
_x000D_
jsfiddle: https://jsfiddle.net/u7zq0amc/1/
Browser Support: IE: 11+
Chrome: all
Firefox: 15+
For a better support also add vendor prefixes.
Java 8 streams
String body = request.getReader().lines()
.reduce("", (accumulator, actual) -> accumulator + actual);
I use this way to chack that varible is numeric:
v * 1 == v
I don't there there is any DataSource
for the gridview
Though you have DataBind
in your code as
gvdetails.DataBind();
use arrow functions, as arrow functions point to parent scope and this will be available. (substitute of bind technique)
this my solution
ResultSet rs=Statement.executeQuery("query");
int rowCount=0;
if (!rs.isBeforeFirst())
{
System.out.println("No DATA" );
} else {
while (rs.next()) {
rowCount++;
System.out.println("data1,data2,data3...etc..");
}
System.out.println(rowCount);
rowCount=0;
rs.close();
Statement.close();
}
jQuery 1.4 also includes a .delay( duration, [ queueName ] ) method if you only need it to trigger once and have already started using that version.
$('#foo').slideUp(300).delay(800).fadeIn(400);
Ooops....my mistake you were looking for an event to continue triggering. I'll leave this here, someone may find it helpful.
ExeOutput is also can Turn PHP Websites into Windows Applications and Software
Turn PHP Websites into Windows Applications and Software
Applications made with ExeOutput for PHP run PHP scripts, PHP applications, and PHP websites natively, and do not require a web server, a web browser, or PHP distribution. They are stand-alone and work on any computer with recent Windows versions.
ExeOutput for PHP is a powerful website compiler that works with all of the elements found on modern sites: PHP scripts, JavaScript, HTML, CSS, XML, PDF files, Flash, Flash videos, Silverlight videos, databases, and images. Combining these elements with PHP Runtime and PHP Extensions, ExeOutput for PHP builds an EXE file that contains your complete application.
See the thumbnail function of PIL's Image Module. You can use it to save smaller versions of files as various filetypes and if you're wanting to preserve as much quality as you can, consider using the ANTIALIAS
filter when you do.
Other than that, I'm not sure if there's a way to specify a maximum desired size. You could, of course, write a function that might try saving multiple versions of the file at varying qualities until a certain size is met, discarding the rest and giving you the image you wanted.
The match attribute indicates on which parts the template transformation is going to be applied. In that particular case the "/" means the root of the xml document. The value you have to provide into the match attribute should be XPath expression. XPath is the language you have to use to refer specific parts of the target xml file.
To gain a meaningful understanding of what else you can put into match attribute you need to understand what xpath is and how to use it. I suggest yo look at links I've provided for youat the bottom of the answer.
Could I write "table" or any other html tag instead of "/" ?
Yes you can. But this depends what exactly you are trying to do. if your target xml file contains HMTL elements and you are triyng to apply this xsl:template on them it makes sense to use table, div or anithing else.
Here a few links:
For very large matrices using sum(sum(A))
can be faster than sum(A(:))
:
>> A = rand(20000);
>> tic; B=sum(A(:)); toc; tic; C=sum(sum(A)); toc
Elapsed time is 0.407980 seconds.
Elapsed time is 0.322624 seconds.
You can create a C# like extension/helper method by (RE) implementing the Collections interface and adding- example for Java Collection:
public class RockCollection<T extends Comparable<T>> implements Collection<T> {
private Collection<T> _list = new ArrayList<T>();
//###########Custom extension methods###########
public T doSomething() {
//do some stuff
return _list
}
//proper examples
public T find(Predicate<T> predicate) {
return _list.stream()
.filter(predicate)
.findFirst()
.get();
}
public List<T> findAll(Predicate<T> predicate) {
return _list.stream()
.filter(predicate)
.collect(Collectors.<T>toList());
}
public String join(String joiner) {
StringBuilder aggregate = new StringBuilder("");
_list.forEach( item ->
aggregate.append(item.toString() + joiner)
);
return aggregate.toString().substring(0, aggregate.length() - 1);
}
public List<T> reverse() {
List<T> listToReverse = (List<T>)_list;
Collections.reverse(listToReverse);
return listToReverse;
}
public List<T> sort(Comparator<T> sortComparer) {
List<T> listToReverse = (List<T>)_list;
Collections.sort(listToReverse, sortComparer);
return listToReverse;
}
public int sum() {
List<T> list = (List<T>)_list;
int total = 0;
for (T aList : list) {
total += Integer.parseInt(aList.toString());
}
return total;
}
public List<T> minus(RockCollection<T> listToMinus) {
List<T> list = (List<T>)_list;
int total = 0;
listToMinus.forEach(list::remove);
return list;
}
public Double average() {
List<T> list = (List<T>)_list;
Double total = 0.0;
for (T aList : list) {
total += Double.parseDouble(aList.toString());
}
return total / list.size();
}
public T first() {
return _list.stream().findFirst().get();
//.collect(Collectors.<T>toList());
}
public T last() {
List<T> list = (List<T>)_list;
return list.get(_list.size() - 1);
}
//##############################################
//Re-implement existing methods
@Override
public int size() {
return _list.size();
}
@Override
public boolean isEmpty() {
return _list == null || _list.size() == 0;
}
For Python 3.X print syntax:
python -c "import numpy; print (numpy.version.version)"
Or
python -c "import numpy; print(numpy.__version__)"
You can use code as below when
using Image as Loading
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
<asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
using Text as Loading
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
<span style="border-width: 0px; position: fixed; padding: 50px; background-color: #FFFFFF; font-size: 36px; left: 40%; top: 40%;">Loading ...</span>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
You can assign int
to char
directly.
int a = 65;
char c = a;
printf("%c", c);
In fact this will also work.
printf("%c", a); // assuming a is in valid range
var item = (from something in someList
select x).firstordefault();
Would get the item
, and then you could do item.prop1=5;
to change the specific property.
Or are you wanting to get a list of items from the db and have it change the property prop1
on each item in that returned list to a specified value?
If so you could do this (I'm doing it in VB because I know it better):
dim list = from something in someList select x
for each item in list
item.prop1=5
next
(list
will contain all the items returned with your changes)
The correct way to do it for Material design is :
Style :
<style name="MyCheckBox" parent="Theme.AppCompat.Light">
<item name="colorControlNormal">@color/foo</item>
<item name="colorControlActivated">@color/bar</item>
</style>
Layout :
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Check Box"
android:theme="@style/MyCheckBox"/>
It will preserve Material animations on Lollipop+.
I know you're using jQuery but for those who want a pure Javascript solution:
// Serialize form fields as URI argument/HTTP POST data
function serializeForm(form) {
var kvpairs = [];
for ( var i = 0; i < form.elements.length; i++ ) {
var e = form.elements[i];
if(!e.name || !e.value) continue; // Shortcut, may not be suitable for values = 0 (considered as false)
switch (e.type) {
case 'text':
case 'textarea':
case 'password':
case 'hidden':
kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
break;
case 'radio':
case 'checkbox':
if (e.checked) kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
break;
/* To be implemented if needed:
case 'select-one':
... document.forms[x].elements[y].options[0].selected ...
break;
case 'select-multiple':
for (z = 0; z < document.forms[x].elements[y].options.length; z++) {
... document.forms[x].elements[y].options[z].selected ...
} */
break;
}
}
return kvpairs.join("&");
}
Hashing algorithms such as sha1 and md5 are not suitable for password storing. They are designed to be very efficient. This means that brute forcing is very fast. Even if a hacker obtains a copy of your hashed passwords, it is pretty fast to brute force it. If you use a salt, it makes rainbow tables less effective, but does nothing against brute force. Using a slower algorithm makes brute force ineffective. For instance, the bcrypt algorithm can be made as slow as you wish (just change the work factor), and it uses salts internally to protect against rainbow tables. I would go with such an approach or similar (e.g. scrypt or PBKDF2) if I were you.
Just use the Class method using this foobar->foobarfunc();
Another option, using the command module:
- name: Create file
command: touch /path/to/file
args:
creates: /path/to/file
The 'creates' argument ensures that this action is not performed if the file exists.
using recursion
let myArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
let size = 4; //Math.sqrt(myArr.length); --> For a n x n matrix
let tempArr = [];
function createMatrix(arr, i) {
if (arr.length !== 0) {
if(i % size == 0) {
tempArr.push(arr.splice(0,size))
}
createMatrix(arr, i - 1)
}
}
createMatrix(myArr, myArr.length);
console.log(tempArr);
Note: The existing array i.e. myArr will be modified.
From the docs:
Given one or more existing commits, revert the changes that the related patches introduce ...
myFile
is intepretted as a commit - because git revert
doesn't accept file paths; only commits
To change one file to match a previous commit - use git checkout
git checkout HEAD~2 myFile
Constants are like the name implies, fields which don't change and are usually defined statically at compile time in the code.
Read-only variables are fields that can change under specific conditions.
They can be either initialized when you first declare them like a constant, but usually they are initialized during object construction inside the constructor.
They cannot be changed after the initialization takes place, in the conditions mentioned above.
Static read-only sounds like a poor choice to me since, if it's static and it never changes, so just use it public const. If it can change then it's not a constant and then, depending on your needs, you can either use read-only or just a regular variable.
Also, another important distinction is that a constant belongs to the class, while the read-only variable belongs to the instance!
What if you don't immediately set the button to disabled, but delay that through setTimeout? Your 'disable' function would return and the submit would continue.
Here's another way to drop a default constraint with an unknown name without having to first run a separate query to get the constraint name:
DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
WHERE NAME = N'__ColumnName__'
AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
What your statements are telling you is just that "" isn't the same as null - which is true. "" is an empty string; null means that no value has been assigned.
It might be more enlightening to try:
System.out.println(a.length()); // 0
System.out.println(b.length()); // error; b is not an object
"" is still a string, meaning you can call its methods and get meaningful information. null is an empty variable - there's literally nothing there.
cleartext support is disabled by default.Android in 9 and above
Try This one I hope It will work fine
1 Step:-> add inside android build gradle (Module:App)
useLibrary 'org.apache.http.legacy'
android {
compileSdkVersion 28
useLibrary 'org.apache.http.legacy'
}
Then 2 Step:-> manifest add inside manifest application tag
<application
android:networkSecurityConfig="@xml/network_security_config">//add drawable goto Step 4
// Step --->3 add to top this line
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
</application>
//Step 4-->> Create Drawable>>Xml file>>name as>> network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
At first, you need to add :
after the IP address to indicate the path is following:
scp magento.tar.gz [email protected]:/var/www
I don't think you need to sudo
the scp
. In this case it doesn't affect the remote machine, only the local command.
Then if your user
@xx.x.x.xx doesn't have write access to /var/www
then you need to do it in 2 times:
Copy to remote server in your home folder (:
represents your remote home folder, use :subfolder/
if needed, or :/home/user/
for full path):
scp magento.tar.gz [email protected]:
Then SSH and move the file:
ssh [email protected]
sudo mv magento.tar.gz /var/www