I also had this issue.
I'm using IntelliJ IDEA.
I was using src/main/java
for configuration files and src/test/java
for test files.
Because of this testNG couldn't find the class path.
To prevent getting that error need to move all the files from src/main/java
to src/test/java
or vice versa.
Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.
public class Time
{
public static void Timestamps()
{
OutputTimestamp();
Thread.Sleep(1000);
OutputTimestamp();
}
private static void OutputTimestamp()
{
var timestamp = DateTime.UtcNow.Ticks;
var localTicks = DateTime.Now.Ticks;
var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
Console.Out.WriteLine("Timestamp = {0}. Local ticks = {1}. Local time = {2}.", timestamp, localTicks, localTime);
}
}
Output:
Timestamp = 636988286338754530. Local ticks = 636988034338754530. Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736. Local ticks = 636988034348878736. Local time = 2019-07-15 4:03:54 PM.
This is the shortest way
String mPhoneNumber = "+972505555555";
mPhoneNumber = mPhoneNumber.replaceAll("+", "").replaceAll(" ", "").replaceAll("-","");
String mMessage = "Hello world";
String mSendToWhatsApp = "https://wa.me/" + mPhoneNumber + "?text="+mMessage;
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(
mSendToWhatsApp
)));
Maybe just use
window.parent
into your iframe to get the calling frame / windows. If you had multiple calling frame, you can use
window.top
Ensure that your 3rd party jars are in your projects "libs" folder and they will be put in the .apk when you package your application. You may see runtime errors on the device if something in the jar is not supported, but other than that I have had great success with this.
Socket.IO allows you to “namespace” your sockets, which essentially means assigning different endpoints or paths.
This might help: http://socket.io/docs/rooms-and-namespaces/
well my answerd is more simple just in the for the MVVM pattern
in class viewmodel
public string password;
PasswordChangedCommand = new DelegateCommand<RoutedEventArgs>(PasswordChanged);
Private void PasswordChanged(RoutedEventArgs obj)
{
var e = (WatermarkPasswordBox)obj.OriginalSource;
//or depending or what are you using
var e = (PasswordBox)obj.OriginalSource;
password =e.Password;
}
the password property of the PasswordBox that win provides or WatermarkPasswordBox that XCeedtoolkit provides generates an RoutedEventArgs so you can bind it.
now in xmal view
<Xceed:WatermarkPasswordBox Watermark="Input your Password" Grid.Column="1" Grid.ColumnSpan="3" Grid.Row="7" PasswordChar="*" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="PasswordChanged">
<prism:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path= DataContext.PasswordChangedCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path= Password}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Xceed:WatermarkPasswordBox>
or
<PasswordBox Grid.Column="1" Grid.ColumnSpan="3" Grid.Row="7" PasswordChar="*" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="PasswordChanged">
<prism:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path= DataContext.PasswordChangedCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path= Password}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</PasswordBox>
the percent should be relative to an absolute size, try this :
table {
width:200px;
}
td {
width:65%;
border:1px solid black;
}
_x000D_
<table>
<tr>
<td>Testasdas 3123 1 dasd as da</td>
<td>A long string blah blah blah</td>
</tr>
</table>
_x000D_
you can do this in different ways:
see here for more details on the second case:
http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14
and here for details on the last case:
$ git submodule status --recursive
Is also a life saver in this situation. You can use it and gitk --all
to keep track of your sha1's and verify your sub-modules are pointing at what you think they are.
glOrtho describes a transformation that produces a parallel projection. The current matrix (see glMatrixMode) is multiplied by this matrix and the result replaces the current matrix, as if glMultMatrix were called with the following matrix as its argument:
OpenGL documentation (my bold)
The numbers define the locations of the clipping planes (left, right, bottom, top, near and far).
The "normal" projection is a perspective projection that provides the illusion of depth. Wikipedia defines a parallel projection as:
Parallel projections have lines of projection that are parallel both in reality and in the projection plane.
Parallel projection corresponds to a perspective projection with a hypothetical viewpoint—e.g., one where the camera lies an infinite distance away from the object and has an infinite focal length, or "zoom".
It depends on number of entities which are going to be updated, if you have large number of entities using JPA Query Update statement is better as you dont have to load all the entities from database, if you are going to update just one entity then using find and update is fine.
<!--- ON click print button, get print and on click close button of print window, get print window closed--->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Print preview</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(function () {
$("#testid").click(function () {
var sWinHTML = document.getElementById('content_print').innerHTML;
var winprint = window.open("", "");
winprint.document.open();
winprint.document.write('<html><head>');
winprint.document.write('<title>Print</title>');
winprint.document.write('</head><body onload="window.focus(); window.print(); window.close()">');
winprint.document.write(sWinHTML);
winprint.document.write('</body></html>');
winprint.document.close();
winprint.focus();
})
})
</script>
</head>
<body>
<form id="form-print">
<div id="content_print">
<h3>Hello world</h3>
<table cellpadding="0" cellspacing="0" width="100%">
<thead>
<tr>
<th style="text-align:left">S.N</th>
<th style="text-align:left">Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Bijen</td>
</tr>
<tr>
<td>2</td>
<td>BJ</td>
</tr>
</tbody>
</table>
</div>
<button type="button" id="testid"/>Print</button>
</form>
</body>
</html>
Look at the "Sprite Text" sample in the GLSurfaceView samples.
If you get this error when you are running it, then probably its because you have not included mysql-connector JAR file to your webserver's lib folder.
Now it is important to add mysql-connector-java-5.1.25-bin.jar to your classpath and also to your webserver's lib directory. Tomcat lib path is given as an example Tomcat 6.0\lib
For the Germans:
you have to change your decimal commas into a Full stop in your csv-file (in Excel:File -> Options -> Advanced -> "Decimal seperator") , then the error is solved.
Menu items file looks like
res/menu/menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/settings"
android:title="Setting"
app:showAsAction="never" />
<item
android:id="@+id/my_activity"
android:title="My Activity"
app:showAsAction="always"
android:icon="@android:drawable/btn_radio"/>
</menu>
Java code looks like
src/MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.my_activity) {
Intent intent1 = new Intent(this,MyActivity.class);
this.startActivity(intent1);
return true;
}
if (id == R.id.settings) {
Toast.makeText(this, "Setting", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
And add following code to your AndroidManifest.xml file
<activity
android:name=".MyActivity"
android:label="@string/app_name" >
</activity>
I hope it will help you.
int[] x = new int [] { 1, 2, 3}; int[] y = new int [] { 4, 5 };
int[] z = x.Union(y).ToArray();
This line will work,
const content = fs.readFileSync('./Index.html', 'utf8');
console.log(content);
Try os.path.splitext it should do what you want.
import os
print os.path.splitext('/home/user/somefile.txt')[0]+'.jpg'
You can use the npm-remote-ls
module. You can install it globally:
npm install -g npm-remote-ls
And then call:
npm-remote-ls bower
Alternatively, [email protected]
installed then you can use npx
and avoid globally installing the command - just call:
npx npm-remote-ls bower
You can also take a look on library Seismic
public class Demo extends Activity implements ShakeDetector.Listener {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
ShakeDetector sd = new ShakeDetector(this);
sd.start(sensorManager);
TextView tv = new TextView(this);
tv.setGravity(CENTER);
tv.setText("Shake me, bro!");
setContentView(tv, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
@Override public void hearShake() {
Toast.makeText(this, "Don't shake me, bro!", Toast.LENGTH_SHORT).show();
}
}
My one line solution:
hash.each { |key, array| puts "#{key}-----", array }
I think it is pretty easy to read.
It's easy, use a solid shadow with 0 offset:
#foo {
border-radius: 1px;
box-shadow: 0px 0px 0px 8px rgba(0,0,0,0.3);
}
Also, if you set a border-radius to the element, it gives you pretty rounded borders
If the buttons are in a form
var myform = new FormData(getformbywhatever);
myform.get("rate");
QuerySelector above is a better solution. However, this method is easy to understand, especially if you don't have a clue about CSS. Plus, input fields are quite likely to be in a form anyway.
Didn't check, there are other similar solutions, sorry for the repetition
It looks like you just hard-coded the row and column; otherwise, a couple of small tweaks, and I think you're there:
Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer
RowCount = 0
Set sh = ActiveSheet
For Each rw In sh.Rows
If sh.Cells(rw.Row, 1).Value = "" Then
Exit For
End If
RowCount = RowCount + 1
Next rw
MsgBox (RowCount)
In your quesion code you are using TimeSpan.FromMinutes
incorrectly. Please see the MSDN Documentation for TimeSpan.FromMinutes, which gives the following method signature:
public static TimeSpan FromMinutes(double value)
hence, the following code won't compile
var intMinutes = TimeSpan.FromMinutes(varTime); // won't compile
Instead, you can use the TimeSpan.TotalMinutes property to perform this arithmetic. For instance:
TimeSpan varTime = (DateTime)varFinish - (DateTime)varValue;
double fractionalMinutes = varTime.TotalMinutes;
int wholeMinutes = (int)fractionalMinutes;
In modern, supported browsers, you can simply do that in CSS with -
header{
position: sticky;
top: 0;
}
Note: The HTML structure is important while using position: sticky
, since it's make the element sticky relative to the parent. And the sticky positioning might not work with a single element made sticky within a parent.
Run the snippet below to check a sample implementation.
main{_x000D_
padding: 0;_x000D_
}_x000D_
header{_x000D_
position: sticky;_x000D_
top:0;_x000D_
padding:40px;_x000D_
background: lightblue;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
content > div {_x000D_
height: 50px;_x000D_
}
_x000D_
<main>_x000D_
<header>_x000D_
This is my header_x000D_
</header>_x000D_
<content>_x000D_
<div>Some content 1</div>_x000D_
<div>Some content 2</div>_x000D_
<div>Some content 3</div>_x000D_
<div>Some content 4</div>_x000D_
<div>Some content 5</div>_x000D_
<div>Some content 6</div>_x000D_
<div>Some content 7</div>_x000D_
<div>Some content 8</div>_x000D_
</content>_x000D_
</main>
_x000D_
This answer is for a Material Design horizontal card layout with dynamic height and an image.
To prevent distortion of the image due to the dynamic height of the card, you could use a background placeholder image with blur to adjust for changes in height.
<div>
with class wrapper, which is a flexbox.<a>
, class link, is positioned
relative.<div>
class blur and an <img>
class pic which is the clear image.width: 100%
, but class pic has a higher stack order, i.e., z-index: 2
, which places it above the placeholder.
.wrapper {_x000D_
display: flex;_x000D_
width: 100%;_x000D_
border: 1px solid rgba(0, 0, 0, 0.16);_x000D_
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.16), 0 1px 1px rgba(0, 0, 0, 0.23);_x000D_
background-color: #fff;_x000D_
margin: 1rem auto;_x000D_
height: auto;_x000D_
}_x000D_
_x000D_
.wrapper:hover {_x000D_
box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);_x000D_
}_x000D_
_x000D_
.link {_x000D_
display: block;_x000D_
width: 200px;_x000D_
height: auto;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
border-right: 2px solid #ddd;_x000D_
}_x000D_
_x000D_
.blur {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
margin: auto;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
filter: blur(5px);_x000D_
-webkit-filter: blur(5px);_x000D_
-moz-filter: blur(5px);_x000D_
-o-filter: blur(5px);_x000D_
-ms-filter: blur(5px);_x000D_
}_x000D_
_x000D_
.pic {_x000D_
width: calc(100% - 20px);_x000D_
max-width: 100%;_x000D_
height: auto;_x000D_
margin: auto;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
z-index: 2;_x000D_
}_x000D_
_x000D_
.pic:hover {_x000D_
transition: all 0.2s ease-out;_x000D_
transform: scale(1.1);_x000D_
text-decoration: none;_x000D_
border: none;_x000D_
}_x000D_
_x000D_
.content {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
width: 100%;_x000D_
max-width: 100%;_x000D_
padding: 20px;_x000D_
overflow-x: hidden;_x000D_
}_x000D_
_x000D_
.text {_x000D_
margin: 0;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<a href="#" class="link">_x000D_
<div class="blur" style="background: url('http://www.planwallpaper.com/static/assets/img/header.jpg') 50% 50% / cover;"></div>_x000D_
<img src="http://www.planwallpaper.com/static/assets/img/header.jpg" alt="Title" class="pic" />_x000D_
</a>_x000D_
_x000D_
<div class="content">_x000D_
<p class="text">Agendum dicendo memores du gi ad. Perciperem occasionem ei ac im ac designabam. Ista rom sibi vul apud tam. Notaverim to extendere expendere concilium ab. Aliae cogor tales fas modus parum sap nullo. Voluntate ingressus infirmari ex mentemque ac manifeste_x000D_
eo. Ac gnum ei utor sive se. Nec curant contra seriem amisit res gaudet adsunt. </p>_x000D_
</div>_x000D_
</div>
_x000D_
How about:
df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x
To do all these operations in one-liner:
setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))
#[1] name age gender
#<0 rows> (or 0-length row.names)
Or
data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))
Brendon Crawford had the best answer here (in comment), so I'll move it to an answer until he does (and maybe expand a little).
var offset = $('#whatever').offset();
offset.right = $(window).width() - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = $(window).height() - (offset.top + $('#whatever').outerHeight(true));
You need to push i
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
for (var i = yearStart; i < yearEnd+1; i++) {
arr.push(i);
}
Then, your resulting array will be:
arr = [2000, 2001, 2003, ... 2039, 2040]
Hope this helps
fileinput
is quite straightforward as mentioned on previous answers:
import fileinput
def replace_in_file(file_path, search_text, new_text):
with fileinput.input(file_path, inplace=True) as f:
for line in f:
new_line = line.replace(search_text, new_text)
print(new_line, end='')
Explanation:
fileinput
can accept multiple files, but I prefer to close each single file as soon as it is being processed. So placed single file_path
in with
statement.print
statement does not print anything when inplace=True
, because STDOUT
is being forwarded to the original file.end=''
in print
statement is to eliminate intermediate blank new lines.Can be used as follows:
file_path = '/path/to/my/file'
replace_in_file(file_path, 'old-text', 'new-text')
If you guys are having this problem in sails.js just set your cors.js to include Authorization as the allowed header
/***************************************************************************_x000D_
* *_x000D_
* Which headers should be allowed for CORS requests? This is only used in *_x000D_
* response to preflight requests. *_x000D_
* *_x000D_
***************************************************************************/_x000D_
_x000D_
headers: 'Authorization' // this line here
_x000D_
Try this
$('#your_select_element_id').val('your_value').attr().add('selected');
Here are scikit-learn options. With both methods, StandardScaler was used because PCA is effected by scale
Method 1: Have scikit-learn choose the minimum number of principal components such that at least x% (90% in example below) of the variance is retained.
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
iris = load_iris()
# mean-centers and auto-scales the data
standardizedData = StandardScaler().fit_transform(iris.data)
pca = PCA(.90)
principalComponents = pca.fit_transform(X = standardizedData)
# To get how many principal components was chosen
print(pca.n_components_)
Method 2: Choose the number of principal components (in this case, 2 was chosen)
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
iris = load_iris()
standardizedData = StandardScaler().fit_transform(iris.data)
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(X = standardizedData)
# to get how much variance was retained
print(pca.explained_variance_ratio_.sum())
Source: https://towardsdatascience.com/pca-using-python-scikit-learn-e653f8989e60
Don't think so...you can only use openTextFile
for reading (1
), writing (2
), or appending (8
). Reference here.
If you were using VB6 instead of VBScript, you could do:
Open "Filename" [For Mode] [AccessRestriction] [LockType] As #FileNumber
Using the Random
mode. For example:
Open "C:\New\maddy.txt" For Random As #1
A really simple explanation that I found useful: the nosniff response header is a way to keep a website more secure.
From Security Researcher, Scott Helme, here:
It prevents Google Chrome and Internet Explorer from trying to mime-sniff the content-type of a response away from the one being declared by the server.
For me this was thrown when running unit tests under MSTest
(VS2015). Had to add
<startup useLegacyV2RuntimeActivationPolicy="true">
</startup>
in
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\TE.ProcessHost.Managed.exe.config
For anyone looking for a clean way to encode a POST request in Swift 5.
You don’t need to deal with manually adding percent encoding.
Use URLComponents
to create a GET request URL. Then use query
property of that URL to get properly percent escaped query string.
let url = URL(string: "https://example.com")!
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!
components.queryItems = [
URLQueryItem(name: "key1", value: "NeedToEscape=And&"),
URLQueryItem(name: "key2", value: "vålüé")
]
let query = components.url!.query
The query
will be a properly escaped string:
key1=NeedToEscape%3DAnd%26&key2=v%C3%A5l%C3%BC%C3%A9
Now you can create a request and use the query as HTTPBody:
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = Data(query.utf8)
Now you can send the request.
All you have to do is enable the html variable to true.. I had same issue, all i had to do was html : true ,
var hh = "<b>test</b>";
swal({
title: "" + txt + "",
text: "Testno sporocilo za objekt " + hh + "",
html: true,
confirmButtonText: "V redu",
allowOutsideClick: "true"
});
Note: html : "Testno sporocilo za objekt " + hh + "",
may not work as html porperty is only use to active this feature by assign true / false value in the Sweetalert.
this html : "Testno sporocilo za objekt " + hh + "",
is used in SweetAlert2
You can just:
if(variable||variable===0){
//Yes it is set
//do something
}
else {
//No it is not set
//Or its null
//do something else
}
Not free, but with the latest Office there's a very nice automation .Net API. (there has been an API for a long while but was nasty COM) You can do everything you want / need in code all while the Office app remains a hidden background process.
Python's eager in its evaluation, so eval(input(...))
(Python 3) will evaluate the user's input as soon as it hits the eval
, regardless of what you do with the data afterwards. Therefore, this is not safe, especially when you eval
user input.
Use ast.literal_eval
.
As an example, entering this at the prompt could be very bad for you:
__import__('os').system('rm -rf /a-path-you-really-care-about')
You can also use:
String[] lines = someString.split("\n");
If that doesn't work try replacing \n
with \r\n
.
My Windows home directory is on the network, and I suspected that Git Bash commands were looking there first. Sure enough, when I looked at $PATH
, it listed /h/bin
first, where /h
is a share on a Windows file server, even though /h/bin
doesn't exist.
I edited /etc/profile
and commented out the export command that puts it first in $PATH
:
#export PATH="$HOME/bin:$PATH"
This made my commands run much faster, probably because Git Bash is no longer looking across the network for the executables. My /etc/profile
was c:\Program Files (x86)\Git\etc\profile
.
Here is an example of decoding a generic map using both switch and reflection, so if you don't match the type, use reflection to figure it out and then add the type in next time.
var data map[string]interface {}
...
for k, v := range data {
fmt.Printf("pair:%s\t%s\n", k, v)
switch t := v.(type) {
case int:
fmt.Printf("Integer: %v\n", t)
case float64:
fmt.Printf("Float64: %v\n", t)
case string:
fmt.Printf("String: %v\n", t)
case bool:
fmt.Printf("Bool: %v\n", t)
case []interface {}:
for i,n := range t {
fmt.Printf("Item: %v= %v\n", i, n)
}
default:
var r = reflect.TypeOf(t)
fmt.Printf("Other:%v\n", r)
}
}
An abbreviated version of your code worked for me,
class Remote: NSObject {
var data = NSMutableData()
func connect(query:NSString) {
var url = NSURL.URLWithString("http://www.google.com")
var request = NSURLRequest(URL: url)
var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
println("didReceiveResponse")
}
func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
self.data.appendData(conData)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
println(self.data)
}
deinit {
println("deiniting")
}
}
This is the code I used in the calling class,
class ViewController: UIViewController {
var remote = Remote()
@IBAction func downloadTest(sender : UIButton) {
remote.connect("/apis")
}
}
You didn't specify in your question where you had this code,
var remote = Remote()
remote.connect("/apis")
If var is a local variable, then the Remote class will be deallocated right after the connect(query:NSString) method finishes, but before the data returns. As you can see by my code, I usually implement reinit (or dealloc up to now) just to make sure when my instances go away. You should add that to your Remote class to see if that's your problem.
It may be happening your branch is corrupted create new branch git branch #check branch. I have created a new branch and working .
branch -b "main"
git checkout -b "main" #main is new branch
git add .
git commit -m "all files"
git remote add origin #**YOUR REPO** https://github.com/tarun-techmarbles/wp-dump-sql-git-push.git
git push origin main #push with new branch
Lists of bytes are subscriptable (at least in Python 3.6). This way you can retrieve the decimal value of each byte individually.
>>> intlist = [64, 4, 26, 163, 255]
>>> bytelist = bytes(intlist) # b'@x04\x1a\xa3\xff'
>>> for b in bytelist:
... print(b) # 64 4 26 163 255
>>> [b for b in bytelist] # [64, 4, 26, 163, 255]
>>> bytelist[2] # 26
Yes, the error you are getting means that there is not a private key on your Mac associated with the distribution certificate you are trying to use to sign the app.
There are two possible solutions, depending on whether the computer who requested the distribution certificate is available or not.
If the computer who requested the distribution certificate is available (or there is a backup of the distribution assets somewhere)
If the computer where the distribution profile was created is not accessible anymore (and there is not a backup)
You have to revoke the certificate and create a new one.
You may need to ask your team admin or agent to give you some privileges in order to generate distribution certificates. Once you have enough privileges, follow these steps (accurate as of 15-May-2013):
Reopen Xcode and check your project configuration to see if you can now select an "iPhone Distribution" certificate (i.e. it's not grayed out).
You can use lscache. It handles this for you automatically, including instances where the storage size exceeds the limit. If that happens, it begins pruning items that are the closest to their specified expiration.
From the readme
:
lscache.set
Stores the value in localStorage. Expires after specified number of minutes.
Arguments
key (string)
value (Object|string)
time (number: optional)
This is the only real difference between the regular storage methods. Get, remove, etc work the same.
If you don't need that much functionality, you can simply store a time stamp with the value (via JSON) and check it for expiry.
Noteworthy, there's a good reason why local storage is left up to the user. But, things like lscache do come in handy when you need to store extremely temporary data.
DependencyObject GetTopParent(DependencyObject current)
{
while (VisualTreeHelper.GetParent(current) != null)
{
current = VisualTreeHelper.GetParent(current);
}
return current;
}
DependencyObject parent = GetTopParent(thisUserControl);
Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship.
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
You can add 'debugger' in your code and reload the app, which puts the breakpoint there and you can 'step over' , or run.
var service = {
user_id: null,
getCurrentUser: function() {
debugger; // Set the debugger inside
// this function
return service.user_id;
}
Broadcasting is really good for this:
row_sums = a.sum(axis=1)
new_matrix = a / row_sums[:, numpy.newaxis]
row_sums[:, numpy.newaxis]
reshapes row_sums from being (3,)
to being (3, 1)
. When you do a / b
, a
and b
are broadcast against each other.
You can learn more about broadcasting here or even better here.
This is known as varargs see the link here for more details
In past java releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message:
Object[] arguments = {
new Integer(7),
new Date(),
"a disturbance in the Force"
};
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet "
+ "{0,number,integer}.", arguments);
It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:
public static String format(String pattern,
Object... arguments);
you can use the identity
log[a]x
log[b]x = ---------
log[a]b
so this would be applicable for log2.
log[10]x
log[2]x = ----------
log[10]2
just plug this into the java Math log10 method....
Bootstrap 2
CSS solution:.collapse { transition: height 0.01s; }
NB: setting transition: none
disables the collapse functionnality.
Bootstrap 4
solution:.collapsing {
transition: none !important;
}
@Ian Nelson: I'm wondering if others see the problem there.
Let's say you have split fields. That's 70 characters total, 35 for first name and 35 for last name. However, if you have one field, you neglect the space that separates first and last names, short changing you by 1 character. Sure, it's "only" one character, but that could make the difference between someone entering their full name and someone not. Therefore, I would change that suggestion to "35 characters for each of Given Name and Family Name, or 71 characters for a single field to hold the Full Name".
You can also get them with pure javascript.
For example:
new URL(location.href).searchParams.get('page')
For this url: websitename.com/user/?page=1, it would return a value of 1
You can use:
<td onclick='javascript:someFunc(this);'></td>
With passing this you can access the DOM object via your function parameters.
The generally-preferred code for 10.5+/iOS.
for (id object in array) {
// do something with object
}
This construct is used to enumerate objects in a collection which conforms to the NSFastEnumeration
protocol. This approach has a speed advantage because it stores pointers to several objects (obtained via a single method call) in a buffer and iterates through them by advancing through the buffer using pointer arithmetic. This is much faster than calling -objectAtIndex:
each time through the loop.
It's also worth noting that while you technically can use a for-in loop to step through an NSEnumerator
, I have found that this nullifies virtually all of the speed advantage of fast enumeration. The reason is that the default NSEnumerator
implementation of -countByEnumeratingWithState:objects:count:
places only one object in the buffer on each call.
I reported this in radar://6296108
(Fast enumeration of NSEnumerators is sluggish) but it was returned as Not To Be Fixed. The reason is that fast enumeration pre-fetches a group of objects, and if you want to enumerate only to a given point in the enumerator (e.g. until a particular object is found, or condition is met) and use the same enumerator after breaking out of the loop, it would often be the case that several objects would be skipped.
If you are coding for OS X 10.6 / iOS 4.0 and above, you also have the option of using block-based APIs to enumerate arrays and other collections:
[array enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
// do something with object
}];
You can also use -enumerateObjectsWithOptions:usingBlock:
and pass NSEnumerationConcurrent
and/or NSEnumerationReverse
as the options argument.
The standard idiom for pre-10.5 is to use an NSEnumerator
and a while loop, like so:
NSEnumerator *e = [array objectEnumerator];
id object;
while (object = [e nextObject]) {
// do something with object
}
I recommend keeping it simple. Tying yourself to an array type is inflexible, and the purported speed increase of using -objectAtIndex:
is insignificant to the improvement with fast enumeration on 10.5+ anyway. (Fast enumeration actually uses pointer arithmetic on the underlying data structure, and removes most of the method call overhead.) Premature optimization is never a good idea — it results in messier code to solve a problem that isn't your bottleneck anyway.
When using -objectEnumerator
, you very easily change to another enumerable collection (like an NSSet
, keys in an NSDictionary
, etc.), or even switch to -reverseObjectEnumerator
to enumerate an array backwards, all with no other code changes. If the iteration code is in a method, you could even pass in any NSEnumerator
and the code doesn't even have to care about what it's iterating. Further, an NSEnumerator
(at least those provided by Apple code) retains the collection it's enumerating as long as there are more objects, so you don't have to worry about how long an autoreleased object will exist.
Perhaps the biggest thing an NSEnumerator
(or fast enumeration) protects you from is having a mutable collection (array or otherwise) change underneath you without your knowledge while you're enumerating it. If you access the objects by index, you can run into strange exceptions or off-by-one errors (often long after the problem has occurred) that can be horrific to debug. Enumeration using one of the standard idioms has a "fail-fast" behavior, so the problem (caused by incorrect code) will manifest itself immediately when you try to access the next object after the mutation has occurred. As programs get more complex and multi-threaded, or even depend on something that third-party code may modify, fragile enumeration code becomes increasingly problematic. Encapsulation and abstraction FTW! :-)
This is how I've done it using parameterized commands.
MSSQL
INSERT INTO MyTable (Field1, Field2) VALUES (@Value1, @Value2);
SELECT SCOPE_IDENTITY();
MySQL
INSERT INTO MyTable (Field1, Field2) VALUES (?Value1, ?Value2);
SELECT LAST_INSERT_ID();
I see many (all) posts above relying on LBound
/UBound
calls upon yet potentially uninitialized VBA dynamic array, what causes application's inevitable death ...
Erratic code:
Dim x As Long
Dim arr1() As SomeType
...
x = UBound(arr1) 'crashes
Correct code:
Dim x As Long
Dim arr1() As SomeType
...
ReDim Preserve arr1(0 To 0)
...
x = UBound(arr1)
... i.e. any code where Dim arr1()
is followed immediatelly by LBound(arr1)
/UBound(arr1)
calls without ReDim arr1(...)
in between, crashes. The roundabout is to employ an On Error Resume Next
and check the Err.Number
right after the LBound(arr1)
/UBound(arr1)
call - it should be 0 if the array is initialized, otherwise non-zero. As there is some VBA built-in misbehavior, the further check of array's limits is needed. Detailed explanation may everybody read at Chip Pearson's website (which should be celebrated as a Mankind Treasure Of VBA Wisdom ...)
Heh, that's my first post, believe it is legible.
<?xml version="1.0" encoding="utf-8"?>
<gradient
android:angle="90"
android:startColor="@color/colorPrimary"
android:endColor="@color/colorPrimary"
android:centerColor="@color/white"
android:type="linear"/>
<corners android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:topRightRadius="10dp"
android:topLeftRadius="10dp"/>
In c++11, you can use std::regex_replace
:
#include <string>
#include <regex>
std::string test = "abc def abc def";
test = std::regex_replace(test, std::regex("def"), "klm");
TempData in Asp.Net MVC is one of the very useful feature. It is used to pass data from current request to subsequent request. In other words if we want to send data from one page to another page while redirection occurs, we can use TempData, but we need to do some consideration in code to achieve this feature in MVC. Because the life of TempData is very short and lies only till the target view is fully loaded. But, we can use Keep() method to persist data in TempData.
git reset is what you want, but I'm going to add a couple extra things you might find useful that the other answers didn't mention.
git reset --hard HEAD
resets your changes back to the last commit that your local repo has tracked. If you made a commit, did not push it to GitHub, and want to throw that away too, see @absiddiqueLive's answer.
git clean -df
will discard any new files or directories that you may have added, in case you want to throw those away. If you haven't added any, you don't have to run this.
git pull
(or if you are using git shell with the GitHub client) git sync
will get the new changes from GitHub.
Edit from way in the future:
I updated my git shell the other week and noticed that the git sync
command is no longer defined by default. For the record, typing git sync
was equivalent to git pull && git push
in bash. I find it still helpful so it is in my bashrc.
return sentence.replaceAll("\s",".");
They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.
private
- Only the current class will have access to the field or method.
protected
- Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.
public
- Any class can refer to the field or call the method.
This assumes these keywords are used as part of a field or method declaration within a class definition.
For Angular2 + Material2 + Sidenav, you'll need to do the following:
ngAfterViewInit() {
this.element.nativeElement.getElementsByClassName('md-sidenav-content')[0].style.overflow = 'hidden';
}
Well I write a script which works very well.
> @echo off TITLE Modifying your HOSTS file COLOR F0 ECHO.
>
> :LOOP SET Choice= SET /P Choice="Do you want to modify HOSTS file ?
> (Y/N)"
>
> IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
>
> ECHO. IF /I '%Choice%'=='Y' GOTO ACCEPTED IF /I '%Choice%'=='N' GOTO
> REJECTED ECHO Please type Y (for Yes) or N (for No) to proceed! ECHO.
> GOTO Loop
>
>
> :REJECTED ECHO Your HOSTS file was left
> unchanged>>%systemroot%\Temp\hostFileUpdate.log ECHO Finished. GOTO
> END
>
>
> :ACCEPTED SET NEWLINE=^& echo. ECHO Carrying out requested
> modifications to your HOSTS file FIND /C /I "www.youtube.com"
> %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1 www.youtube.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "youtube.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> youtube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxysite.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.proxysite.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxfree.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.proxfree.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.hidemyass.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.hidemyass.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.freeyoutubeproxy.org" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.freeyoutubeproxy.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "www.facebook.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.facebook.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "facebook.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> facebook.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.4everproxy.com " %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1 www.4everproxy.com
> >>%WINDIR%\system32\drivers\etc\hosts FIND /C /I "4everproxy.com " %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1 4everproxy.com >>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "proxysite.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> proxysite.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxfree.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> proxfree.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "hidemyass.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> hidemyass.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "freeyoutubeproxy.org" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> freeyoutubeproxy.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblockvideos.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> unblockvideos.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxyone.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> proxyone.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "kuvia.eu" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1 kuvia.eu>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "kuvia.eu/facebook-proxy"
> %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1
> kuvia.eu/facebook-proxy>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "hidemytraxproxy.ca" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> hidemytraxproxy.ca>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "github.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> github.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "funproxy.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> funproxy.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "en.wikipedia.org" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> en.wikipedia.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "wikipedia.org" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> wikipedia.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "dronten.proxylistpro.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> dronten.proxylistpro.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "proxylistpro.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> proxylistpro.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zfreez.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> zfreez.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zendproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> zendproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zalmos.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> zalmos.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youtubeunblockproxy.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> youtubeunblockproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "youtubefreeproxy.net" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> youtubefreeproxy.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youliaoren.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> youliaoren.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "xitenow.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> xitenow.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.youtubeproxy.pk" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.youtubeproxy.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youtubeproxy.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> youtubeproxy.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.youproxytube.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.youproxytube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.webmasterview.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.webmasterview.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "webmasterview.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> webmasterview.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youproxytube.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> youproxytube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.vobas.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.vobas.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "vobas.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1 vobas.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "www.unblockmyweb.com" %WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1
> www.unblockmyweb.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblockmyweb.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> unblockmyweb.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.unblocker.yt" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.unblocker.yt>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblocker.yt" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> unblocker.yt>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.unblock.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.unblock.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblock.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> unblock.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.techgyd.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.techgyd.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "techgyd.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> techgyd.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.snapdeal.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.snapdeal.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "snapdeal.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> snapdeal.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.site2unblock.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.site2unblock.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "site2unblock.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> site2unblock.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.shopclues.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.shopclues.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "shopclues.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> shopclues.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxypk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.proxypk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxypk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> proxypk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxay.co.uk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.proxay.co.uk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxay.co.uk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> proxay.co.uk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.myntra.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.myntra.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "myntra.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> myntra.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.maddw.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.maddw.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "maddw.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1 maddw.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "www.lenskart.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.lenskart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "lenskart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> lenskart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.kproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.kproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "kproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> kproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.jabong.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.jabong.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "jabong.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> jabong.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.flipkart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.flipkart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "flipkart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1
> flipkart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.facebook-proxyserver.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.facebook-proxyserver.com>>%WINDIR%\system32\drivers\etc\hosts FIND
> /C /I "facebook-proxyserver.com" %WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1
> facebook-proxyserver.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "www.dontfilter.us" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.dontfilter.us>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "dontfilter.us" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> dontfilter.us>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.dolopo.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1
> www.dolopo.net>>%WINDIR%\system32\drivers\etc\hosts ECHO Finished GOTO
> END
>
>
> :END ECHO. ping -n 11 127.0.0.1 > nul EXIT
You can try the services of https://www.geoip-db.com They provide a JSON or JSONP-callback solution.
<?php
$json = file_get_contents("https://www.geoip-db.com/json");
$data = json_decode($json);
print $data->country_code . "<br>";
print $data->country_name . "<br>";
print $data->state . "<br>";
print $data->city . "<br>";
print $data->postal . "<br>";
print $data->latitude . "<br>";
print $data->longitude . "<br>";
print $data->IPv4 . "<br>";
?>
Click on SVG's <g>
element in <object>
with click event. Works 100%. Take a look on the nested javascript in <svg>
. Don't forget to insert window.parent.location.href=
if you want to redirect the parent page.
You must set your environments
and reference my blog.(sorry post was Korean)
http://blog.naver.com/PostSearchList.nhn?SearchText=webdeploy&blogId=xyz37&x=25&y=7
@ECHO OFF
:: http://stackoverflow.com/questions/5598668/valid-parameters-for-msdeploy-via-msbuild
::-DeployOnBuild -True
:: -False
::
::-DeployTarget -MsDeployPublish
:: -Package
::
::-Configuration -Name of a valid solution configuration
::
::-CreatePackageOnPublish -True
:: -False
::
::-DeployIisAppPath -<Web Site Name>/<Folder>
::
::-MsDeployServiceUrl -Location of MSDeploy installation you want to use
::
::-MsDeployPublishMethod -WMSVC (Web Management Service)
:: -RemoteAgent
::
::-AllowUntrustedCertificate (used with self-signed SSL certificates) -True
:: -False
::
::-UserName
::-Password
SETLOCAL
IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v2.0.50727" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v2.0.50727"
IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v3.5" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v3.5"
IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v4.0.30319" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v4.0.30319"
SET targetFile=<web site fullPath ie. .\trunk\WebServer\WebServer.csproj
SET configuration=Release
SET msDeployServiceUrl=https://<domain>:8172/MsDeploy.axd
SET msDeploySite="<WebSite name>"
SET userName="WebDeploy"
SET password=%USERNAME%
SET platform=AnyCPU
SET msbuild=%FXPath%\MSBuild.exe /MaxCpuCount:%NUMBER_OF_PROCESSORS% /clp:ShowCommandLine
%MSBuild% %targetFile% /p:configuration=%configuration%;Platform=%platform% /p:DeployOnBuild=True /p:DeployTarget=MsDeployPublish /p:CreatePackageOnPublish=False /p:DeployIISAppPath=%msDeploySite% /p:MSDeployPublishMethod=WMSVC /p:MsDeployServiceUrl=%msDeployServiceUrl% /p:AllowUntrustedCertificate=True /p:UserName=%USERNAME% /p:Password=%password% /p:SkipExtraFilesOnServer=True /p:VisualStudioVersion=12.0
IF NOT "%ERRORLEVEL%"=="0" PAUSE
ENDLOCAL
Or simply
add to your element
[ngStyle]="{'color': myVariableColor}"
eg
<mat-icon [ngStyle]="{'color': myVariableColor}">{{ getActivityIcon() }}</mat-icon>
Where color
can be defined at another component etc
In Go, there is a general rule that syntax should not hide complex/costly operations. Converting a string
to an interface{}
is done in O(1) time. Converting a []string
to an interface{}
is also done in O(1) time since a slice is still one value. However, converting a []string
to an []interface{}
is O(n) time because each element of the slice must be converted to an interface{}
.
The one exception to this rule is converting strings. When converting a string
to and from a []byte
or a []rune
, Go does O(n) work even though conversions are "syntax".
There is no standard library function that will do this conversion for you. You could make one with reflect, but it would be slower than the three line option.
Example with reflection:
func InterfaceSlice(slice interface{}) []interface{} {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
panic("InterfaceSlice() given a non-slice type")
}
// Keep the distinction between nil and empty slice input
if s.IsNil() {
return nil
}
ret := make([]interface{}, s.Len())
for i:=0; i<s.Len(); i++ {
ret[i] = s.Index(i).Interface()
}
return ret
}
Your best option though is just to use the lines of code you gave in your question:
b := make([]interface{}, len(a))
for i := range a {
b[i] = a[i]
}
this worked for me:-
<?php echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; ?>
thanks for sharing code...
Array
(
[__ci_last_regenerate] => 1490879962
[user_id] => 3
[designation_name] => Admin
[region_name] => admin
[territory_name] => admin
[designation_id] => 2
[region_id] => 1
[territory_id] => 1
[employee_user_id] => mosin11
)
Change the line into this
angular.forEach(values, function(value, key){
console.log(key + ': ' + value);
});
angular.forEach(values, function(value, key){
console.log(key + ': ' + value.Name);
});
Another native JS solution that can be useful for "complex" or deeply nested elements is to use NodeIterator. Put NodeFilter.SHOW_TEXT
as the second argument ("whatToShow"), and iterate over just the text node children of the element.
var root = document.querySelector('p'),_x000D_
iter = document.createNodeIterator(root, NodeFilter.SHOW_TEXT),_x000D_
textnode;_x000D_
_x000D_
// print all text nodes_x000D_
while (textnode = iter.nextNode()) {_x000D_
console.log(textnode.textContent)_x000D_
}
_x000D_
<p>_x000D_
<br>some text<br>123_x000D_
</p>
_x000D_
You can also use TreeWalker
. The difference between the two is that NodeIterator
is a simple linear iterator, while TreeWalker
allows you to navigate via siblings and ancestors as well.
This should work.
int i = 1;
foreach (ListViewItem lvi in listView.Items) {
...
if(++i == 50) break;
}
I guess you are actually using Amazon Linux AMI 2013.03.1 instead of Ubuntu Server 12.x reason why you don't have apt-get tool installed.
This worked for me..
Open Virtual Box and select your mobile VM. Right click->Settings
Change Promiscuous mode to Allow VMS and click ok
You may try this way. just use a function to get your object
def get_object(self, id):
try:
return Comment.objects.get(pk=id)
except Comment.DoesNotExist:
return False
In the direction of Bradgonesurfing's answer, many times one doesn't really need to concatenate two vectors (O(n)), but instead just work with them as if they were concatenated (O(1)). If this is your case, it can be done without the need of Boost libraries.
The trick is to create a vector proxy: a wrapper class which manipulates references to both vectors, externally seen as a single, contiguous one.
USAGE
std::vector<int> A{ 1, 2, 3, 4, 5};
std::vector<int> B{ 10, 20, 30 };
VecProxy<int> AB(A, B); // ----> O(1). No copies performed.
for (size_t i = 0; i < AB.size(); ++i)
std::cout << AB[i] << " "; // 1 2 3 4 5 10 20 30
IMPLEMENTATION
template <class T>
class VecProxy {
private:
std::vector<T>& v1, v2;
public:
VecProxy(std::vector<T>& ref1, std::vector<T>& ref2) : v1(ref1), v2(ref2) {}
const T& operator[](const size_t& i) const;
const size_t size() const;
};
template <class T>
const T& VecProxy<T>::operator[](const size_t& i) const{
return (i < v1.size()) ? v1[i] : v2[i - v1.size()];
};
template <class T>
const size_t VecProxy<T>::size() const { return v1.size() + v2.size(); };
MAIN BENEFIT
It's O(1) (constant time) to create it, and with minimal extra memory allocation.
SOME STUFF TO CONSIDER
The post needs an update after the links
option is deprecated.
Basically, links
is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network
. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.
For docker run
, --link
is also deprecated and should be replaced by a custom network.
docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image
depends_on
expresses start order (and implicitly image pulling order), which was a good side effect of links
.
According to MSDN, the JavaScript Date object does not provide any specific date formatting methods (as you may see with other programming languages). However, you can use a few of the Date
methods and formatting to accomplish your goal:
function dateToString (date) {
// Use an array to format the month numbers
var months = [
"January",
"February",
"March",
...
];
// Use an object to format the timezone identifiers
var timeZones = {
"360": "EST",
...
};
var month = months[date.getMonth()];
var day = date.getDate();
var year = date.getFullYear();
var hours = date.getHours();
var minutes = date.getMinutes();
var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
var timezone = timeZones[date.getTimezoneOffset()];
// Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
return month + " " + day + ", " + year + " - " + time + " " + timezone;
}
var date = new Date("2011-01-28T19:30:00-05:00");
alert(dateToString(date));
You could even take it one step further and override the Date.toString()
method:
function dateToString () { // No date argument this time
// Use an array to format the month numbers
var months = [
"January",
"February",
"March",
...
];
// Use an object to format the timezone identifiers
var timeZones = {
"360": "EST",
...
};
var month = months[*this*.getMonth()];
var day = *this*.getDate();
var year = *this*.getFullYear();
var hours = *this*.getHours();
var minutes = *this*.getMinutes();
var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
var timezone = timeZones[*this*.getTimezoneOffset()];
// Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
return month + " " + day + ", " + year + " - " + time + " " + timezone;
}
var date = new Date("2011-01-28T19:30:00-05:00");
Date.prototype.toString = dateToString;
alert(date.toString());
One way to solve the problem of the text to look good on both desktop and mobile/tablet is in fixing the text size to physical units like physical centimeters or inches, which don't depend on the screen PPI (points per inch).
Based on this answer, below is the code I use at the end of the HTML document for a responsive font size:
<div id='testdiv' style='height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;'></div>
<script type='text/javascript'>
var devicePixelRatio = window.devicePixelRatio || 1;
dpi_x = document.getElementById('testdiv').offsetWidth * devicePixelRatio;
dpi_y = document.getElementById('testdiv').offsetHeight * devicePixelRatio;
function setFontSizeForClass(className, fontSize) {
var elms = document.getElementsByClassName(className);
for(var i=0; i<elms.length; i++) {
elms[i].style.fontSize = String(fontSize * dpi_y / 96) + "px";
}
}
setFontSizeForClass('h1-font-size', 30);
setFontSizeForClass('action-font-size', 20);
setFontSizeForClass('guideline-font-size', 25);
// etc for your different classes
</script>
In the code above the items of a different class are assigned font sizes in physical units, as long as the browser/OS is configured correctly for the PPI of its screen.
A physical-unit font is always not too large and not too small, so long as the distance to the screen is usual (book-reading distance).
If you're using Cordova 3.3 or higher and your device is running Android 4.4 or higher you can use 'Remote Debugging on Android with Chrome'. Full instructions are here:
https://developer.chrome.com/devtools/docs/remote-debugging
In summary:
Or, if you're using Cordova 3.3+ and don't have a physical device with 4.4, you can use an emulator that uses Android 4.4+ to run the application through the emulator, on your desktop computer.
Personally, I use something close from fubo's solution and it works well:
image.ScaleToFit(document.PageSize);
image.SetAbsolutePosition(0,0);
In my case i forgot to add the () after the function name inside the render function of a react component
public render() {
let ctrl = (
<>
<div className="aaa">
{this.renderView}
</div>
</>
);
return ctrl;
};
private renderView() : JSX.Element {
// some html
};
Changing the render method, as it states in the error message to
<div className="aaa">
{this.renderView()}
</div>
fixed the problem
Similar to yebmouxing I could not the
xhr.getResponseHeader('Set-Cookie');
method to work. It would only return null even if I had set HTTPOnly to false on my server.
I too wrote a simple js helper function to grab the cookies from the document. This function is very basic and only works if you know the additional info (lifespan, domain, path, etc. etc.) to add yourself:
function getCookie(cookieName){
var cookieArray = document.cookie.split(';');
for(var i=0; i<cookieArray.length; i++){
var cookie = cookieArray[i];
while (cookie.charAt(0)==' '){
cookie = cookie.substring(1);
}
cookieHalves = cookie.split('=');
if(cookieHalves[0]== cookieName){
return cookieHalves[1];
}
}
return "";
}
Follow this steps:
-Build
-Generate Signed Apk
-Create new
Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)
As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)
EDIT 1:
Following your comment, I run a test table:
mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)
Insertion:
mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)
EDIT 2:
So, aparently you want to insert a NULL value to pdd
field as your comment states ?
You can do that in 2 ways like this:
Method 1:
mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)
Method 2:
mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)
EDIT 3:
You failed to change the default value of pdd
field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)
mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3 Duplicates: 0 Warnings: 1
Here's a fun demo of controlling the various states of the console, including minimize and hidden.
Add-Type -Name ConsoleUtils -Namespace WPIA -MemberDefinition @'
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'@
$ConsoleMode = @{
HIDDEN = 0;
NORMAL = 1;
MINIMIZED = 2;
MAXIMIZED = 3;
SHOW = 5
RESTORE = 9
}
$hWnd = [WPIA.ConsoleUtils]::GetConsoleWindow()
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.MAXIMIZED)
"maximized $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.NORMAL)
"normal $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.MINIMIZED)
"minimized $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.RESTORE)
"restore $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.HIDDEN)
"hidden $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.SHOW)
"show $a"
You do like this:
List<int>[] a = new List<int>[100];
Now you have an array of type List<int>
containing 100 null references. You have to create lists and put in the array, for example:
a[0] = new List<int>();
<!DOCTYPE html>
<html>
<head>
<style>
.cardDetaileclips{
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3; /* after 3 line show ... */
-webkit-box-orient: vertical;
}
</style>
</head>
<body>
<div style="width:100px;">
<div class="cardDetaileclips">
My Name is Manoj and pleasure to help you.
</div>
</div>
</body>
</html>
On python command line, first import that module for which you need location.
import module_name
Then type:
print(module_name.__file__)
For example to find out "pygal" location:
import pygal
print(pygal.__file__)
Output:
/anaconda3/lib/python3.7/site-packages/pygal/__init__.py
I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser
which is doing most of the work. Where he puts req.body.name
, I believe he/she is using body-parser
to get the contents of the name attribute(s) received when the form is submitted.
If you do not want to use Express, use querystring
which is a built-in Node module. See the answers in the link below for an example of how to use querystring
.
It might help to look at this answer, which is very similar to your quest.
Try to clean and rebuild the project. I had the absolutely same question, this solved it.
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
"Is it safe..?" is a question about the language standard and the generated code.
"Is is a good practice?" is a question about how well the statement is understood by any arbitrary human reader of the statement. If you are asking this question, it suggests that the "safe" version is less clear to future readers and writers.
In addition, don't inject to a static
member, it will be null
.
Configuring a button (or any widget) in Tkinter is done by calling a configure method "config"
To change the size of a button called button1
you simple call
button1.config( height = WHATEVER, width = WHATEVER2 )
If you know what size you want at initialization these options can be added to the constructor.
button1 = Button(self, text = "Send", command = self.response1, height = 100, width = 100)
For #4, the closest thing to starting java with a jar file for your app is a new feature in Python 2.6, executable zip files and directories.
python myapp.zip
Where myapp.zip is a zip containing a __main__.py
file which is executed as the script file to be executed. Your package dependencies can also be included in the file:
__main__.py
mypackage/__init__.py
mypackage/someliblibfile.py
You can also execute an egg, but the incantation is not as nice:
# Bourn Shell and derivatives (Linux/OSX/Unix)
PYTHONPATH=myapp.egg python -m myapp
rem Windows
set PYTHONPATH=myapp.egg
python -m myapp
This puts the myapp.egg on the Python path and uses the -m argument to run a module. Your myapp.egg will likely look something like:
myapp/__init__.py
myapp/somelibfile.py
And python will run __init__.py
(you should check that __file__=='__main__'
in your app for command line use).
Egg files are just zip files so you might be able to add __main__.py
to your egg with a zip tool and make it executable in python 2.6 and run it like python myapp.egg
instead of the above incantation where the PYTHONPATH environment variable is set.
More information on executable zip files including how to make them directly executable with a shebang can be found on Michael Foord's blog post on the subject.
For references you can call
rails generate migration AddUserIdColumnToTable user:references
If in the future you need to add a general index you can launch this
rails g migration AddOrdinationNumberToTable ordination_number:integer:index
Generate code:
class AddOrdinationNumberToTable < ActiveRecord::Migration
def change
add_column :tables, :ordination_number, :integer
add_index :tables, :ordination_number, unique: true
end
end
I just posted an answer to a question that was subequently closed as a duplicate of this one (for good reasons I think), but I'm surprised to see that my proposed solution is not included in any of the answers here.
Rather than using a defaultdict
or messing around with membership tests or manual exception handling, you can easily append values onto lists within a dictionary using the setdefault
method:
results = {} # use a normal dictionary for our output
for k, v in some_data: # the keys may be duplicates
results.setdefault(k, []).append(v) # magic happens here!
This is a lot like using a defaultdict, but you don't need a special data type. When you call setdefault
, it checks to see if the first argument (the key) is already in the dictionary. If doesn't find anything, it assigns the second argument (the default value, an empty list in this case) as a new value for the key. If the key does exist, nothing special is done (the default goes unused). In either case though, the value (whether old or new) gets returned, so we can unconditionally call append
on it, knowing it should always be a list.
See question: How to find an item in a std::vector?
You'll also need to ensure you've implemented a suitable operator==()
for your object, if the default one isn't sufficient for a "deep" equality test.
sorry I saw the question late, Here is an easy programmatically solution that works well on me,
Create those global variables:
float firstWidth;
float firstHeight;
after on load, fill those variables;
firstWidth = this.Size.Width;
firstHeight = this.Size.Height;
then select your form and put these code to your form's SizeChange event;
private void AnaMenu_SizeChanged(object sender, EventArgs e)
{
float size1 = this.Size.Width / firstWidth;
float size2 = this.Size.Height / firstHeight;
SizeF scale = new SizeF(size1, size2);
firstWidth = this.Size.Width;
firstHeight = this.Size.Height;
foreach (Control control in this.Controls)
{
control.Font = new Font(control.Font.FontFamily, control.Font.Size* ((size1+ size2)/2));
control.Scale(scale);
}
}
I hope this helps, it works perfect on my projects.
If you need to return a JSON object using a String, then the following should work:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;
...
@RestController
@RequestMapping("/student")
public class StudentController {
@GetMapping
@RequestMapping("/")
public ResponseEntity<JsonNode> get() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree("{\"id\": \"132\", \"name\": \"Alice\"}");
return ResponseEntity.ok(json);
}
...
}
I found good answers here, but also found a simpler way.
The button to create the blob and the download link can be combined in one link, as the link element can have an onclick attribute. (The reverse seems not possible, adding a href to a button does not work.)
You can style the link as a button using bootstrap
, which is still pure javascript, except for styling.
Combining the button and the download link also reduces code, as fewer of those ugly getElementById
calls are needed.
This example needs only one button click to create the text-blob and download it:
<a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary"
onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
>
Write To File
</a>
<script>
// URL pointing to the Blob with the file contents
var objUrl = null;
// create the blob with file content, and attach the URL to the downloadlink;
// NB: link must have the download attribute
// this method can go to your library
function exportFile(fileContent, downloadLinkId) {
// revoke the old object URL to avoid memory leaks.
if (objUrl !== null) {
window.URL.revokeObjectURL(objUrl);
}
// create the object that contains the file data and that can be referred to with a URL
var data = new Blob([fileContent], { type: 'text/plain' });
objUrl = window.URL.createObjectURL(data);
// attach the object to the download link (styled as button)
var downloadLinkButton = document.getElementById(downloadLinkId);
downloadLinkButton.href = objUrl;
};
</script>
You have two choices, either correct your markup so that it uses correct elements and utilizes the Bootstrap grid system:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
<h1>About Me</h1>_x000D_
<div class="row">_x000D_
<div class="col-md-4">_x000D_
<div class="imgAbt">_x000D_
<img width="220" height="220" src="img/me.jpg" />_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-8">_x000D_
<p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Or, if you wish the text to closely wrap the image, change your markup to:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
<h1>About Me</h1>_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
<img style='float:left;width:200px;height:200px; margin-right:10px;' src="img/me.jpg" />_x000D_
<p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
</div>_x000D_
</div>
_x000D_
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
public static Bitmap decodeFile(String path) {
Bitmap b = null;
File f = new File(path);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int IMAGE_MAX_SIZE = 1024; // maximum dimension limit
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
public static Bitmap showBitmapFromFile(String file_path)
{
try {
File imgFile = new File(file_path);
if(imgFile.exists()){
Bitmap pic_Bitmap = decodeFile(file_path);
return pic_Bitmap;
}
} catch (Exception e) {
MyLog.e("Exception showBitmapFromFile");
return null;
}
return null;
}
if you are using image loading in List view then use Aquery concept .
https://github.com/AshishPsaini/AqueryExample
AQuery aq= new AQuery((Activity) activity, convertView);
//load image from file, down sample to target width of 250 pixels .gi
File file=new File("//pic/path/here/aaaa.jpg");
if(aq!=null)
aq.id(holder.pic_imageview).image(file, 250);
You can use composition instead... this will allow you to access class objects from the static type. But still cant implements interfaces or abstract classes
Use CHARINDEX
. Perhaps make user function. If you use this split often.
I would create this function:
CREATE FUNCTION [dbo].[Split]
(
@String VARCHAR(max),
@Delimiter varCHAR(1)
)
RETURNS TABLE
AS
RETURN
(
WITH Split(stpos,endpos)
AS(
SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
UNION ALL
SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
FROM Split
WHERE endpos > 0
)
SELECT 'INT_COLUMN' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
'STRING_COLUMN' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
FROM Split
)
GO
Just an FYI adding to Chris. B (best answer):
d = defaultdict(int)
Works as well; the reason is that calling int()
returns 0
which is what defaultdict
does behind the scenes (when constructing a dictionary), hence the name "Factory Function" in the documentation.
If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
Note- position really matters add google() before jcenter()
And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
check these links below for more details-
You can't use it from the XML.
You need to extend the widget you are using in the XML and add the logic to set the text using what's mentioned on Konstantin Burov's answer.
You can create your own AuthorizationHandler that will find custom attributes on your Controllers and Actions, and pass them to the HandleRequirementAsync method.
public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
{
var attributes = new List<TAttribute>();
var action = (context.Resource as AuthorizationFilterContext)?.ActionDescriptor as ControllerActionDescriptor;
if (action != null)
{
attributes.AddRange(GetAttributes(action.ControllerTypeInfo.UnderlyingSystemType));
attributes.AddRange(GetAttributes(action.MethodInfo));
}
return HandleRequirementAsync(context, requirement, attributes);
}
protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);
private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo)
{
return memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
}
}
Then you can use it for any custom attributes you need on your controllers or actions. For example to add permission requirements. Just create your custom attribute.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class PermissionAttribute : AuthorizeAttribute
{
public string Name { get; }
public PermissionAttribute(string name) : base("Permission")
{
Name = name;
}
}
Then create a Requirement to add to your Policy
public class PermissionAuthorizationRequirement : IAuthorizationRequirement
{
//Add any custom requirement properties if you have them
}
Then create the AuthorizationHandler for your custom attribute, inheriting the AttributeAuthorizationHandler that we created earlier. It will be passed an IEnumerable for all your custom attributes in the HandleRequirementsAsync method, accumulated from your Controller and Action.
public class PermissionAuthorizationHandler : AttributeAuthorizationHandler<PermissionAuthorizationRequirement, PermissionAttribute>
{
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement, IEnumerable<PermissionAttribute> attributes)
{
foreach (var permissionAttribute in attributes)
{
if (!await AuthorizeAsync(context.User, permissionAttribute.Name))
{
return;
}
}
context.Succeed(requirement);
}
private Task<bool> AuthorizeAsync(ClaimsPrincipal user, string permission)
{
//Implement your custom user permission logic here
}
}
And finally, in your Startup.cs ConfigureServices method, add your custom AuthorizationHandler to the services, and add your Policy.
services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();
services.AddAuthorization(options =>
{
options.AddPolicy("Permission", policyBuilder =>
{
policyBuilder.Requirements.Add(new PermissionAuthorizationRequirement());
});
});
Now you can simply decorate your Controllers and Actions with your custom attribute.
[Permission("AccessCustomers")]
public class CustomersController
{
[Permission("AddCustomer")]
IActionResult AddCustomer([FromBody] Customer customer)
{
//Add customer
}
}
ACID are desirable properties of any transaction processing engine.
A DBMS is (if it is any good) a particular kind of transaction processing engine that exposes, usually to a very large extent but not quite entirely, those properties.
But other engines exist that can also expose those properties. The kind of software that used to be called "TP monitors" being a case in point (nowadays' equivalent mostly being web servers).
Such TP monitors can access resources other than a DBMS (e.g. a printer), and still guarantee ACID toward their users. As an example of what ACID might mean when a printer is involved in a transaction:
You can call the super class's constructor like this
class A(object):
def __init__(self, number):
print "parent", number
class B(A):
def __init__(self):
super(B, self).__init__(5)
b = B()
NOTE:
This will work only when the parent class inherits object
Try adding android:fillViewport="true"
to the ScrollView.
Found the solution here: LinearLayout not expanding inside a ScrollView
To me, this looks like the simplest/fastest:
$('form input[type=submit]').click(function() { // attach the listener to your button
var yourWantedObjectIsHere = $(this.form); // use the native JS object with `this`
});
Especially for the older Git versions, most of the suggestions won't work that well. If that's the case, I'd put a separate .gitignore in the directory where I want the content to be included regardless of other settings and allow there what is needed.
For example: /.gitignore
# ignore all .dll files
*.dll
/dependency_files/.gitignore
# include everything
!*
So everything in /dependency_files (even .dll files) are included just fine.
I created this function that allows to enter a string and returns a list of string trimmed by any character
func Trim(input:String, character:Character)-> [String]
{
var collection:[String] = [String]()
var index = 0
var copy = input
let iterable = input
var trim = input.startIndex.advancedBy(index)
for i in iterable.characters
{
if (i == character)
{
trim = input.startIndex.advancedBy(index)
// apennding to the list
collection.append(copy.substringToIndex(trim))
//cut the input
index += 1
trim = input.startIndex.advancedBy(index)
copy = copy.substringFromIndex(trim)
index = 0
}
else
{
index += 1
}
}
collection.append(copy)
return collection
}
as didn't found a way to do this in swift (compiles and work perfectly in swift 2.0)
Little late to the game but i found a way to fix this for me that i had not seen anywhere else. Select your connection from Connection Managers. On the right you should see properties. Check to see if there are any expressions there if not add one. In your package explorer add a variable called connection to sql or whatever. Set the variable as a string and set the value as your connection string and include the User Id and password. Back to the connection manager properties and expression. From the drop down select ConnectionString and set the second box as the name of your variable. It should look like this
I could not for the life of me find another solution but this worked!
This should do the trick
export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get -q -y install mysql-server
Of course, it leaves you with a blank root password - so you'll want to run something like
mysqladmin -u root password mysecretpasswordgoeshere
Afterwards to add a password to the account.
make the utility class final and add a private constructor
If it is a windows form Datagrid, you could use the below code to format the datetime for a column
dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy HH:mm:ss";
EDIT :
Apart from this, if you need the datetime in AM/PM format, you could use the below code
dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt";
How about the alternate form of for
mentioned in (bashref)Looping Constructs?
When using aggregate functions to filter, you must use a HAVING statement.
SELECT *
FROM tblMoney
HAVING Sum(CASH) > 500
Maybe you should look at $.ajax() instead (if you are using jQuery, which it looks like). Take a look at: http://docs.jquery.com/Ajax/jQuery.ajax#options and the option "cache".
Another approach would be to look at how you cache things on the server side.
Instead of above way u can achieve the solution simply by following method..
public static void main(String args[]) {
String ini = "Hi there";
for (int i = 0; i < ini.length(); i++) {
System.out.print(" " + ini.charAt(i));
}
}
Attempts of abrupt thread termination are well-known bad programming practice and evidence of poor application design. All threads in the multithreaded application explicitly and implicitly share the same process state and forced to cooperate with each other to keep it consistent, otherwise your application will be prone to the bugs which will be really hard to diagnose. So, it is a responsibility of developer to provide an assurance of such consistency via careful and clear application design.
There are two main right solutions for the controlled threads terminations:
Good and detailed explanation of the issues related to the abrupt threads termination as well as examples of wrong and right solutions for the controlled threads termination can be found here:
Angular 2
For anyone looking to do the same in Angular 2 it is very similar apart from getting a hold of the form
<form role="form" [ngFormModel]="myFormModel" (ngSubmit)="onSubmit()" #myForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input autofocus type="text" ngControl="usename" #name="ngForm" class="form-control" id="name" placeholder="Name">
<div [hidden]="name.valid || name.pristine" class="alert alert-danger">
Name is required
</div>
</div>
</form>
<button type="submit" class="btn btn-primary" (click)="myForm.ngSubmit.emit()">Add</button>
import { Component, } from '@angular/core';
import { FormBuilder, Validators } from '@angular/common';
@Component({
selector: 'my-example-form',
templateUrl: 'app/my-example-form.component.html',
directives: []
})
export class MyFormComponent {
myFormModel: any;
constructor(private _formBuilder: FormBuilder) {
this.myFormModel = this._formBuilder.group({
'username': ['', Validators.required],
'password': ['', Validators.required]
});
}
onSubmit() {
this.myFormModel.markAsDirty();
for (let control in this.myFormModel.controls) {
this.myFormModel.controls[control].markAsDirty();
};
if (this.myFormModel.dirty && this.myFormModel.valid) {
// My submit logic
}
}
}
The standard way to do this is as follows:
Provide:
and get in return a Integer between min and max, inclusive.
Random rand = new Random();
// nextInt as provided by Random is exclusive of the top value so you need to add 1
int randomNum = rand.nextInt((max - min) + 1) + min;
See the relevant JavaDoc.
As explained by Aurund, Random objects created within a short time of each other will tend to produce similar output, so it would be a good idea to keep the created Random object as a field, rather than in a method.
If anyone interested in the easiest example with ModelViewset for Django Rest Framework.
The Model is,
class MyModel(models.Model):
name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True)
imageUrl = models.FileField(db_column='image_url', blank=True, null=True, upload_to='images/')
class Meta:
managed = True
db_table = 'MyModel'
The Serializer,
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = "__all__"
And the View is,
class MyModelView(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
Test in Postman,
Dictionary does not support duplicate keys- So you will get the last key i.e.a=16
but not the first key a=15
>>>qs = [{u'a': 15L, u'b': 9L, u'a': 16L}]
>>>qs
>>>[{u'a': 16L, u'b': 9L}]
>>>result_list = [int(v) for k,v in qs[0].items()]
>>>result_list
>>>[16, 9]
To resolve all conflicts with the version in a particular branch:
git diff --name-only --diff-filter=U | xargs git checkout ${branchName}
So, if you are already in the merging state, and you want to keep the master version of the conflicting files:
git diff --name-only --diff-filter=U | xargs git checkout master
Numbers don't have a length, but you can easily convert the number to a string, check the length and then prepend the 0 if it's necessary:
var strMonth = '' + date.getMinutes(); if (strMonth.length == 1) { strMonth = '0' + strMonth; }
You can also use the tag, this works in divs and everything else:
<center><form></form></center>
This link will help you with the tag:
You can use .length
, like this:
var count = $("ul li").length;
.length
tells how many matches the selector found, so this counts how many <li>
under <ul>
elements you have...if there are sub-children, use "ul > li"
instead to get only direct children. If you have other <ul>
elements in your page, just change the selector to match only his one, for example if it has an ID you'd use "#myListID > li"
.
In other situations where you don't know the child type, you can use the *
(wildcard) selector, or .children()
, like this:
var count = $(".parentSelector > *").length;
or:
var count = $(".parentSelector").children().length;
If you are doing VANILLA plain JavaScript without jQuery, then you must use (Internet Explorer 9 or later):
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded and ready
});
Above is the equivalent of jQuery .ready
:
$(document).ready(function() {
console.log("Ready!");
});
Which ALSO could be written SHORTHAND like this, which jQuery will run after the ready even occurs.
$(function() {
console.log("ready!");
});
NOT TO BE CONFUSED with BELOW (which is not meant to be DOM ready):
DO NOT use an IIFE like this that is self executing:
Example:
(function() {
// Your page initialization code here - WRONG
// The DOM will be available here - WRONG
})();
This IIFE will NOT wait for your DOM to load. (I'm even talking about latest version of Chrome browser!)
EDIT (after comment): the below will solve the coding issue, but is highly not recommended to use this approach because a linear regression model is a very poor classifier, which will very likely not separate the classes correctly.
Read the well written answer below by @desertnaut, explaining why this error is an hint of something wrong in the machine learning approach rather than something you have to 'fix'.
accuracy_score(y_true, y_pred.round(), normalize=False)
To chain CSS3 styles which spans across multiple lines, you can do like this,
var styles = [
'background: linear-gradient(#D33106, #571402)'
, 'border: 1px solid #3E0E02'
, 'color: white'
, 'display: block'
, 'text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)'
, 'box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset'
, 'line-height: 40px'
, 'text-align: center'
, 'font-weight: bold'
].join(';');
console.log('%c a spicy log message ?', styles);
Result
Find more :- https://coderwall.com/p/fskzdw/colorful-console-log
Cheers.
I've tried various combinations and had them fail in FireFox. It has been a while so the answer above may work fine or I may have missed something.
What has always worked for me is to add the following to the head of each page, or the template (Master Page in .net).
<script language="javascript" type="text/javascript">
window.onbeforeunload = function () {
// This function does nothing. It won't spawn a confirmation dialog
// But it will ensure that the page is not cached by the browser.
}
</script>
This has disabled all caching in all browsers for me without fail.
f = open('C:\\Users\\Pooja\\Desktop\\trolldata.csv')
Use '\\' for python program in Python version 3 and above.. Error will be resolved..
Sample Usage:
import paramiko
paramiko.util.log_to_file("paramiko.log")
# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))
# Auth
username,password = "bar","foo"
transport.connect(None,username,password)
# Go!
sftp = paramiko.SFTPClient.from_transport(transport)
# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)
# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)
# Close
if sftp: sftp.close()
if transport: transport.close()
After reading around alot, only this worked: In class to set Shared preferences:
SharedPreferences userDetails = getApplicationContext().getSharedPreferences("test", MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.clear();
edit.putString("test1", "1");
edit.putString("test2", "2");
edit.commit();
In AlarmReciever:
SharedPreferences userDetails = context.getSharedPreferences("test", Context.MODE_PRIVATE);
String test1 = userDetails.getString("test1", "");
String test2 = userDetails.getString("test2", "");
I think its because the two machines usually would need to be optimized in different ways. Other than that I have no idea, we run all our applications with the server-database on the same machine - granted we're not public facing - but we've had no problems.
I can't imagine that too many people care about one machine being compromised over both since the web application will usually have nearly unrestricted access to at the very least the data if not the schema inside the database.
Interested in what others might say.
Here's my two cents as the accepted answer didn't work for me.
var documentAtBottom = (document.documentElement.scrollTop + window.innerHeight) >= document.documentElement.scrollHeight;
Primarily because the result of a someString.join()
is a string.
The sequence (list or tuple or whatever) doesn't appear in the result, just a string. Because the result is a string, it makes sense as a method of a string.
Try this:
<div id="mainTable" style="width:100px; height:200px;"></div>
$(document).ready(function() {
$("#mainTable").width(100).height(200);
}) ;
Safest & simplest is to just loop;
Dim buff() As String
ReDim buff(Len(my_string) - 1)
For i = 1 To Len(my_string)
buff(i - 1) = Mid$(my_string, i, 1)
Next
If your guaranteed to use ansi characters only you can;
Dim buff() As String
buff = Split(StrConv(my_string, vbUnicode), Chr$(0))
ReDim Preserve buff(UBound(buff) - 1)
I'll assume you mean the URI:
class BankController < ActionController::Base
before_filter :pre_process
def index
# do something
end
private
def pre_process
logger.debug("The URL" + request.url)
end
end
As per your comment below, if you need the name of the controller, you can simply do this:
private
def pre_process
self.controller_name # Will return "order"
self.controller_class_name # Will return "OrderController"
end
One way is to add it by yourself! How? By merging kwargs
with a bunch of defaults. This won't be appropriate on all occasions, for example, if the keys are not known to you in advance. However, if they are, here is a simple example:
import sys
def myfunc(**kwargs):
args = {'country':'England','town':'London',
'currency':'Pound', 'language':'English'}
diff = set(kwargs.keys()) - set(args.keys())
if diff:
print("Invalid args:",tuple(diff),file=sys.stderr)
return
args.update(kwargs)
print(args)
The defaults are set in the dictionary args
, which includes all the keys we are expecting. We first check to see if there are any unexpected keys in kwargs. Then we update args
with kwargs
which will overwrite any new values that the user has set. We don't need to test if a key exists, we now use args
as our argument dictionary and have no further need of kwargs
.
You need to open the file in binary mode i.e. wb
instead of w
. If you don't, the end of line characters are auto-converted to OS specific ones.
Here is an excerpt from Python reference about open()
.
The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.
// in the HTML code I used some razor
@Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));
// now down in the script I do this
<script type="text/javascript">
var url = $("#RedirectTo").val();
$(document).ready(function () {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Controller/Action',
success: function (result) {
if (result.UserFriendlyErrMsg === 'Some Message') {
// display a prompt
alert("Message: " + result.UserFriendlyErrMsg);
// redirect us to the new page
location.href = url;
}
$('#friendlyMsg').html(result.UserFriendlyErrMsg);
}
});
</script>
A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.
Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
You should have if row[2] != "0"
. Otherwise it's not checking to see if the string value is equal to 0.
Like this?
public static void Test()
{
using (var image = Image.FromFile(@"c:\logo.png"))
using (var newImage = ScaleImage(image, 300, 400))
{
newImage.Save(@"c:\test.png", ImageFormat.Png);
}
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
To make a dropdown list you need two properties:
In your case you only have a list of string which cannot be exploited to create a usable drop down list.
While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:
@model List<string>
@Html.DropDownList(
"Foo",
new SelectList(
Model.Select(x => new { Value = x, Text = x }),
"Value",
"Text"
)
)
where Foo
will be the name of the ddl and used by the default model binder. So the generated markup might look something like this:
<select name="Foo" id="Foo">
<option value="item 1">item 1</option>
<option value="item 2">item 2</option>
<option value="item 3">item 3</option>
...
</select>
This being said a far better view model for a drop down list is the following:
public class MyListModel
{
public string SelectedItemId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
and then:
@model MyListModel
@Html.DropDownListFor(
x => x.SelectedItemId,
new SelectList(Model.Items, "Value", "Text")
)
and if you wanted to preselect some option in this list all you need to do is to set the SelectedItemId
property of this view model to the corresponding Value
of some element in the Items
collection.
I made a javascript function to create dots with an svg. You can adjust dot spacing and size in the javascript code.
var make_dotted_borders = function() {_x000D_
// EDIT THESE SETTINGS:_x000D_
_x000D_
var spacing = 8;_x000D_
var dot_width = 2;_x000D_
var dot_height = 2;_x000D_
_x000D_
//---------------------_x000D_
_x000D_
var dotteds = document.getElementsByClassName("dotted");_x000D_
for (var i = 0; i < dotteds.length; i++) {_x000D_
var width = dotteds[i].clientWidth + 1.5;_x000D_
var height = dotteds[i].clientHeight;_x000D_
_x000D_
var horizontal_count = Math.floor(width / spacing);_x000D_
var h_spacing_percent = 100 / horizontal_count;_x000D_
var h_subtraction_percent = ((dot_width / 2) / width) * 100;_x000D_
_x000D_
var vertical_count = Math.floor(height / spacing);_x000D_
var v_spacing_percent = 100 / vertical_count;_x000D_
var v_subtraction_percent = ((dot_height / 2) / height) * 100;_x000D_
_x000D_
var dot_container = document.createElement("div");_x000D_
dot_container.classList.add("dot_container");_x000D_
dot_container.style.display = getComputedStyle(dotteds[i], null).display;_x000D_
_x000D_
var clone = dotteds[i].cloneNode(true);_x000D_
_x000D_
dotteds[i].parentElement.replaceChild(dot_container, dotteds[i]);_x000D_
dot_container.appendChild(clone);_x000D_
_x000D_
for (var x = 0; x < horizontal_count; x++) {_x000D_
// The Top Dots_x000D_
var dot = document.createElement("div");_x000D_
dot.classList.add("dot");_x000D_
dot.style.width = dot_width + "px";_x000D_
dot.style.height = dot_height + "px";_x000D_
_x000D_
var left_percent = (h_spacing_percent * x) - h_subtraction_percent;_x000D_
dot.style.left = left_percent + "%";_x000D_
dot.style.top = (-dot_height / 2) + "px";_x000D_
dot_container.appendChild(dot);_x000D_
_x000D_
// The Bottom Dots_x000D_
var dot = document.createElement("div");_x000D_
dot.classList.add("dot");_x000D_
dot.style.width = dot_width + "px";_x000D_
dot.style.height = dot_height + "px";_x000D_
_x000D_
dot.style.left = (h_spacing_percent * x) - h_subtraction_percent + "%";_x000D_
dot.style.top = height - (dot_height / 2) + "px";_x000D_
dot_container.appendChild(dot);_x000D_
}_x000D_
_x000D_
for (var y = 1; y < vertical_count; y++) {_x000D_
// The Left Dots:_x000D_
var dot = document.createElement("div");_x000D_
dot.classList.add("dot");_x000D_
dot.style.width = dot_width + "px";_x000D_
dot.style.height = dot_height + "px";_x000D_
_x000D_
dot.style.left = (-dot_width / 2) + "px";_x000D_
dot.style.top = (v_spacing_percent * y) - v_subtraction_percent + "%";_x000D_
dot_container.appendChild(dot);_x000D_
}_x000D_
for (var y = 0; y < vertical_count + 1; y++) {_x000D_
// The Right Dots:_x000D_
var dot = document.createElement("div");_x000D_
dot.classList.add("dot");_x000D_
dot.style.width = dot_width + "px";_x000D_
dot.style.height = dot_height + "px";_x000D_
_x000D_
dot.style.left = width - (dot_width / 2) + "px";_x000D_
if (y < vertical_count) {_x000D_
dot.style.top = (v_spacing_percent * y) - v_subtraction_percent + "%";_x000D_
}_x000D_
else {_x000D_
dot.style.top = height - (dot_height / 2) + "px";_x000D_
}_x000D_
_x000D_
dot_container.appendChild(dot);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
make_dotted_borders();
_x000D_
div.dotted {_x000D_
display: inline-block;_x000D_
padding: 0.5em;_x000D_
}_x000D_
_x000D_
div.dot_container {_x000D_
position: relative;_x000D_
margin-left: 0.25em;_x000D_
margin-right: 0.25em;_x000D_
}_x000D_
_x000D_
div.dot {_x000D_
position: absolute;_x000D_
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100"><circle cx="50" cy="50" r="50" fill="black" /></svg>');_x000D_
}
_x000D_
<div class="dotted">Lorem Ipsum</div>
_x000D_
@echo off
// quote the path or else it won't work if there are spaces in the path
SET INSTALL_PATH="c:\\etc etc\\test";
if exist %INSTALL_PATH% (
//
echo 222;
)
I was facing the same issue when integrating Firebase Cloud Store in my project. Inside the project level gradle, I added
classpath 'com.google.gms:google-services:4.0.1'
that fixed the issue.
recordId is property of the object
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Nai_record other = (Nai_record) obj;
if (recordId == null) {
if (other.recordId != null)
return false;
} else if (!recordId.equals(other.recordId))
return false;
return true;
}
I am not comfortable using "Index" and so on...could come up as below
df.columns
Index(['A123', 'B123'], dtype='object')
df=pd.concat([df,pd.DataFrame(columns=list('CDE'))])
df.rename(columns={
'C':'C123',
'D':'D123',
'E':'E123'
},inplace=True)
df.columns
Index(['A123', 'B123', 'C123', 'D123', 'E123'], dtype='object')
A POD is a type (including classes) where the C++ compiler guarantees that there will be no "magic" going on in the structure: for example hidden pointers to vtables, offsets that get applied to the address when it is cast to other types (at least if the target's POD too), constructors, or destructors. Roughly speaking, a type is a POD when the only things in it are built-in types and combinations of them. The result is something that "acts like" a C type.
int
, char
, wchar_t
, bool
, float
, double
are PODs, as are long/short
and signed/unsigned
versions of them.enums
are PODsconst
or volatile
POD is a POD.class
, struct
or union
of PODs is a POD provided that all non-static data members are public
, and it has no base class and no constructors, destructors, or virtual methods. Static members don't stop something being a POD under this rule. This rule has changed in C++11 and certain private members are allowed: Can a class with all private members be a POD class?3.9(10): "Arithmetic types (3.9.1), enumeration types, pointer types, and pointer to member types (3.9.2) and cv-qualified versions of these types (3.9.3) are collectively caller scalar types. Scalar types, POD-struct types, POD-union types (clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called POD types"
9(4): "A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor. Similarly a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor.
8.5.1(1): "An aggregate is an array or class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10) and no virtual functions (10.3)."
#!/bin/bash
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"
# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"
# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer
or:
You need a back inserter to copy into vectors:
std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));
You cannot assign arrays to copy them. How you can copy the contents of one into another depends on multiple factors:
For char
arrays, if you know the source array is null terminated and destination array is large enough for the string in the source array, including the null terminator, use strcpy()
:
#include <string.h>
char array1[18] = "abcdefg";
char array2[18];
...
strcpy(array2, array1);
If you do not know if the destination array is large enough, but the source is a C string, and you want the destination to be a proper C string, use snprinf()
:
#include <stdio.h>
char array1[] = "a longer string that might not fit";
char array2[18];
...
snprintf(array2, sizeof array2, "%s", array1);
If the source array is not necessarily null terminated, but you know both arrays have the same size, you can use memcpy
:
#include <string.h>
char array1[28] = "a non null terminated string";
char array2[28];
...
memcpy(array2, array1, sizeof array2);
Deleting and Recreating a project with same name is tricky. If you try to follow above suggested steps and try to create a project with same name as the one you just deleted, you will run into error like
'C:/xxxxxx/pom.xml' already exists in VFS
Here is what I found would work.
What is the proper #include for the function 'sleep()'?
sleep()
isn't Standard C, but POSIX so it should be:
#include <unistd.h>
if you just want to stopping insecure warning like:
/usr/lib/python3/dist-packages/urllib3/connectionpool.py:794: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html InsecureRequestWarning)
do:
requests.METHOD("https://www.google.com", verify=False)
verify=False
is the key, followings are not good at it:
requests.packages.urllib3.disable_warnings()
or
urllib3.disable_warnings()
but, you HAVE TO know, that might cause potential security risks.
BufferedReader br = null;
try {
String fpath = Environment.getExternalStorageDirectory() + <your file name>;
try {
br = new BufferedReader(new FileReader(fpath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = "";
while ((line = br.readLine()) != null) {
//Do something here
}
Easy way to shutdown mySQL server for Windows7 :
My Computer > Manage > Services and Application > Services > select "MySQL 56"(the name depends upon the version of MySQL installed.) three options are present at left top corner. Stop the Service pause the Service Restart the Service
choose Stop the service > to stop the server
Again to start you can come to the same location or we can chose tools options on mySQL GUI Server > Startup/Shutdown > Choose to Startup or Shutdown
PS: some times it is not possible to stop the server from the GUI even though the options are provided. so is the reason the above alternative method is provided.
share the ans. to improve. thanks
Since a comprehensive list does not appear to exist, let's start one here on SO. This can be of great value to the ASP.NET MVC community if people add their experience (esp. anyone who contributed to one of these). Anything implementing IViewEngine
(e.g. VirtualPathProviderViewEngine
) is fair game here. Just alphabetize new View Engines (leaving WebFormViewEngine and Razor at the top), and try to be objective in comparisons.
System.Web.Mvc.WebFormViewEngine
Design Goals:
A view engine that is used to render a Web Forms page to the response.
Pros:
Cons:
Example:
<%@ Control Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
<% if(model.Any()) { %>
<ul>
<% foreach(var p in model){%>
<li><%=p.Name%></li>
<%}%>
</ul>
<%}else{%>
<p>No products available</p>
<%}%>
Design Goals:
Pros:
Cons:
Con Example #1 (notice the placement of "string[]..."):
@{
<h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert"};
foreach (var person in teamMembers)
{
<p>@person</p>
}
}
Design goals:
- Respect HTML as first-class language as opposed to treating it as "just text".
- Don't mess with my HTML! The data binding code (Bellevue code) should be separate from HTML.
- Enforce strict Model-View separation
Design Goals:
The Brail view engine has been ported from MonoRail to work with the Microsoft ASP.NET MVC Framework. For an introduction to Brail, see the documentation on the Castle project website.
Pros:
Cons:
Example:
<html>
<head>
<title>${title}</title>
</head>
<body>
<p>The following items are in the list:</p>
<ul><%for element in list: output "<li>${element}</li>"%></ul>
<p>I hope that you would like Brail</p>
</body>
</html>
Hasic uses VB.NET's XML literals instead of strings like most other view engines.
Pros:
Cons:
Example:
Protected Overrides Function Body() As XElement
Return _
<body>
<h1>Hello, World</h1>
</body>
End Function
Design Goals:
NDjango is an implementation of the Django Template Language on the .NET platform, using the F# language.
Pros:
WebFormViewEngine
Design Goals:
.NET port of Rails Haml view engine. From the Haml website:
Haml is a markup language that's used to cleanly and simply describe the XHTML of any web document, without the use of inline code... Haml avoids the need for explicitly coding XHTML into the template, because it is actually an abstract description of the XHTML, with some code to generate dynamic content.
Pros:
Cons:
Example:
@type=IEnumerable<Product>
- if(model.Any())
%ul
- foreach (var p in model)
%li= p.Name
- else
%p No products available
NVelocityViewEngine (MvcContrib)
Design Goals:
A view engine based upon NVelocity which is a .NET port of the popular Java project Velocity.
Pros:
Cons:
Example:
#foreach ($p in $viewdata.Model)
#beforeall
<ul>
#each
<li>$p.Name</li>
#afterall
</ul>
#nodata
<p>No products available</p>
#end
Design Goals:
SharpTiles is a partial port of JSTL combined with concept behind the Tiles framework (as of Mile stone 1).
Pros:
Cons:
Example:
<c:if test="${not fn:empty(Page.Tiles)}">
<p class="note">
<fmt:message key="page.tilesSupport"/>
</p>
</c:if>
Design Goals:
The idea is to allow the html to dominate the flow and the code to fit seamlessly.
Pros:
Cons:
Example:
<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
<li each="var p in products">${p.Name}</li>
</ul>
<else>
<p>No products available</p>
</else>
<Form style="background-color:olive;">
<Label For="username" />
<TextBox For="username" />
<ValidationMessage For="username" Message="Please type a valid username." />
</Form>
StringTemplate View Engine MVC
Design Goals:
- Lightweight. No page classes are created.
- Fast. Templates are written to the Response Output stream.
- Cached. Templates are cached, but utilize a FileSystemWatcher to detect file changes.
- Dynamic. Templates can be generated on the fly in code.
- Flexible. Templates can be nested to any level.
- In line with MVC principles. Promotes separation of UI and Business Logic. All data is created ahead of time, and passed down to the template.
Pros:
Cons:
Wing Beats is an internal DSL for creating XHTML. It is based on F# and includes an ASP.NET MVC view engine, but can also be used solely for its capability of creating XHTML.
Pros:
Cons:
Design Goals:
Builds views from familiar XSLT
Pros:
Cons:
There is a situation where the dot operator will give different answers when dealing with arrays as with dealing with matrices. For example, suppose the following:
>>> a=numpy.array([1, 2, 3])
>>> b=numpy.array([1, 2, 3])
Lets convert them into matrices:
>>> am=numpy.mat(a)
>>> bm=numpy.mat(b)
Now, we can see a different output for the two cases:
>>> print numpy.dot(a.T, b)
14
>>> print am.T*bm
[[1. 2. 3.]
[2. 4. 6.]
[3. 6. 9.]]
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
Although Adrien's answer is correct, you can do this all in single line. No need for extra function or mess.
It works I checked it in ASP.NET Core 1.0
var user = await _userManager.GetUserAsync(HttpContext.User);
then you can get other properties of the variable like user.Email
. I hope this helps someone.
Ember-Data's ActiveRecord adapter expects 422 UNPROCESSABLE ENTITY
to be returned from server. So, if you're client is written in Ember.js you should use 422. Only then DS.Errors will be populated with returned errors. You can of course change 422 to any other code in your adapter.
as your service is already setup, simply add a broadcast receiver in your service:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
//action for sms received
}
else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
//action for phone state changed
}
}
};
in your service's onCreate
do this:
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more
registerReceiver(receiver, filter);
and in your service's onDestroy
:
unregisterReceiver(receiver);
and you are good to go to receive broadcast for what ever filters you mention in onCreate
. Make sure to add any permission if required. for e.g.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
The "pro tip" above from Someone Somewhere (Making TextView scrollable on Android) works great, however, what if you're dynamically adding text to the ScrollView and would like to automatically scroll to the bottom after an append only when the user is at the bottom of the ScrollView? (Perhaps because if the user has scrolled up to read something you don't want to automatically reset to the bottom during an append, which would be annoying.)
Anyway, here it is:
if ((mTextStatus.getMeasuredHeight() - mScrollView.getScrollY()) <=
(mScrollView.getHeight() + mTextStatus.getLineHeight())) {
scrollToBottom();
}
The mTextStatus.getLineHeight() will make it so that you don't scrollToBottom() if the user is within one line from the end of the ScrollView.
For PyTorch v1.0 and possibly above:
>>> import torch
>>> var = torch.tensor([[1,0], [0,1]])
# Using .size function, returns a torch.Size object.
>>> var.size()
torch.Size([2, 2])
>>> type(var.size())
<class 'torch.Size'>
# Similarly, using .shape
>>> var.shape
torch.Size([2, 2])
>>> type(var.shape)
<class 'torch.Size'>
You can cast any torch.Size object to a native Python list:
>>> list(var.size())
[2, 2]
>>> type(list(var.size()))
<class 'list'>
In PyTorch v0.3 and 0.4:
Simply list(var.size())
, e.g.:
>>> import torch
>>> from torch.autograd import Variable
>>> from torch import IntTensor
>>> var = Variable(IntTensor([[1,0],[0,1]]))
>>> var
Variable containing:
1 0
0 1
[torch.IntTensor of size 2x2]
>>> var.size()
torch.Size([2, 2])
>>> list(var.size())
[2, 2]
If there is no database with the same name as the username, then clicking "Choose Database" will fail with an error like "Status : Failure -FATAL: database "your_username" does not exist"
To work around this, put 5432/database_name?
in the Port field, where 5432
is the port of your Postgres instance and database_name
is the name of at an existing database that your_username
has access to. Then click "Choose Database" again and it should work. Now you can choose the database you want and remove the extra /database_name?
from the Port field.
var employee = (from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select new {res.EMAIL, res.USERNAME} );
OR you can use
var employee = (from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select new {email=res.EMAIL, username=res.USERNAME} );
Explanation :
Select employee from the db as res.
Filter the employee details as per the where condition.
Select required fields from the employee object by creating an Anonymous object using new { }
Did you try list(x)??
y = '+123-456-7890'
c =list(y)
c
['+', '1', '2', '3', '-', '4', '5', '6', '-', '7', '8', '9', '0']
add #include <iostream>
to the start of io.cpp
too.
Directly from the Windows.h header file:
#ifndef WIN32_LEAN_AND_MEAN
#include <cderr.h>
#include <dde.h>
#include <ddeml.h>
#include <dlgs.h>
#ifndef _MAC
#include <lzexpand.h>
#include <mmsystem.h>
#include <nb30.h>
#include <rpc.h>
#endif
#include <shellapi.h>
#ifndef _MAC
#include <winperf.h>
#include <winsock.h>
#endif
#ifndef NOCRYPT
#include <wincrypt.h>
#include <winefs.h>
#include <winscard.h>
#endif
#ifndef NOGDI
#ifndef _MAC
#include <winspool.h>
#ifdef INC_OLE1
#include <ole.h>
#else
#include <ole2.h>
#endif /* !INC_OLE1 */
#endif /* !MAC */
#include <commdlg.h>
#endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */
if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.
Also, from Microsoft's support page:
To speed the build process, Visual C++ and the Windows Headers provide the following new defines:
VC_EXTRALEAN
WIN32_LEAN_AND_MEANYou can use them to reduce the size of the Win32 header files.
Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.
I have created main.css file and included all css files in it.
We can include only one main.css file
@import url('style.css');
@import url('platforms.css');
Uses reqclient, it's a small client module on top of request
that allows you to log all the activity with cURL style (optional, for development environments). Also has nice features like URL and parameters parsing, authentication integrations, cache support, etc.
For example, if you create a client object an do a request:
var RequestClient = require("reqclient").RequestClient;
var client = new RequestClient({
baseUrl:"http://baseurl.com/api/v1.1",
debugRequest:true, debugResponse:true
});
var resp = client.post("client/orders", {"client":1234,"ref_id":"A987"}, {headers: {"x-token":"AFF01XX"}})
It will log within the console something like this:
[Requesting client/orders]-> -X POST http://baseurl.com/api/v1.1/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json
[Response client/orders]<- Status 200 - {"orderId": 1320934}
The request will return a Promise object, so you have to handle with then
and catch
what to do with the result.
reqclient
is available with npm, you can install the module with: npm install reqclient
.
It is not that complicated actually. Relevant Qt widgets are in matplotlib.backends.backend_qt4agg
. FigureCanvasQTAgg
and NavigationToolbar2QT
are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a Figure
, Navigation
and a single button that draws some random data. I've added comments to explain things.
import sys
from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import random
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = Figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
self.button = QtGui.QPushButton('Plot')
self.button.clicked.connect(self.plot)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def plot(self):
''' plot some random stuff '''
# random data
data = [random.random() for i in range(10)]
# create an axis
ax = self.figure.add_subplot(111)
# discards the old graph
ax.clear()
# plot data
ax.plot(data, '*-')
# refresh canvas
self.canvas.draw()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
Edit:
Updated to reflect comments and API changes.
NavigationToolbar2QTAgg
changed with NavigationToolbar2QT
Figure
instead of pyplot
ax.hold(False)
with ax.clear()
Here are two approaches:
@echo off
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: --examples
::assigning chcp command output to %code-page% variable
chcp %[[%code-page%]]%
echo 1: %code-page%
::assigning whoami command output to %its-me% variable
whoami %[[%its-me%]]%
echo 2: %its-me%
::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set "" &::
;;set "}}==%%#"" &::
::::::::::::::::::::::::::::::::::::::::::::::::::
:: --examples
::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%
::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%
Here my solution
function getTime() {
var systemDate = new Date();
var hours = systemDate.getHours();
var minutes = systemDate.getMinutes();
var strampm;
if (hours >= 12) {
strampm= "PM";
} else {
strampm= "AM";
}
hours = hours % 12;
if (hours == 0) {
hours = 12;
}
_hours = checkTimeAddZero(hours);
_minutes = checkTimeAddZero(minutes);
console.log(_hours + ":" + _minutes + " " + strampm);
}
function checkTimeAddZero(i) {
if (i < 10) {
i = "0" + i
}
return i;
}
dumpsys window windows
gives more detail about the current activity:
adb shell "dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'"
mCurrentFocus=Window{41d2c970 u0 com.android.launcher/com.android.launcher2.Launcher}
mFocusedApp=AppWindowToken{4203c170 token=Token{41b77280 ActivityRecord{41b77a28 u0 com.android.launcher/com.android.launcher2.Launcher t3}}}
However in order to find the process ID (e.g. to kill the current activity), use dumpsys activity
, and grep on "top-activity":
adb shell "dumpsys activity | grep top-activity"
Proc # 0: fore F/A/T trm: 0 3074:com.android.launcher/u0a8 (top-activity)
adb shell "kill 3074"