Here is an React (Native) version:
import React, { Component } from 'react';
import {
View,
Text,
} from 'react-native';
export default class CountUp extends Component {
state = {
seconds: null,
}
get formatedTime() {
const { seconds } = this.state;
return [
pad(parseInt(seconds / 60)),
pad(seconds % 60),
].join(':');
}
componentWillMount() {
this.setState({ seconds: 0 });
}
componentDidMount() {
this.timer = setInterval(
() => this.setState({
seconds: ++this.state.seconds
}),
1000
);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<View>
<Text>{this.formatedTime}</Text>
</View>
);
}
}
function pad(num) {
return num.toString().length > 1 ? num : `0${num}`;
}
Download jansi-1.4.jar and Set classpath and Try This code 100% working :
import org.fusesource.jansi.AnsiConsole;
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;
public class SampleColour
{
public static void main(String[] args)
{
AnsiConsole.systemInstall();
System.out.println(ansi().fg(RED).a("Hello World").reset());
System.out.println("My Name is Raman");
AnsiConsole.systemUninstall();
}
}
I tried your code, you didn't assign/bind a value to your formControlName.
In HTML file:
<form [formGroup]="form">
<label>
<input type="radio" value="Male" formControlName="gender">
<span>male</span>
</label>
<label>
<input type="radio" value="Female" formControlName="gender">
<span>female</span>
</label>
</form>
In the TS file:
form: FormGroup;
constructor(fb: FormBuilder) {
this.name = 'Angular2'
this.form = fb.group({
gender: ['', Validators.required]
});
}
Make sure you use Reactive form properly: [formGroup]="form"
and you don't need the name attribute.
In my sample. words male
and female
in span tags are the values display along the radio button and Male
and Female
values are bind to formControlName
To make it shorter:
<form [formGroup]="form">
<input type="radio" value='Male' formControlName="gender" >Male
<input type="radio" value='Female' formControlName="gender">Female
</form>
Hope it helps:)
I believe bind always tries to send an event parameter. Try:
self.entry_1.bind("<Return>", lambda event: self.calculate(self.buttonOut_1.grid_info(), 1))
You accept the parameter and never use it.
You can use replace:
df['y'] = df['y'].replace({'N/A': np.nan})
Also be aware of the inplace
parameter for replace
. You can do something like:
df.replace({'N/A': np.nan}, inplace=True)
This will replace all instances in the df without creating a copy.
Similarly, if you run into other types of unknown values such as empty string or None value:
df['y'] = df['y'].replace({'': np.nan})
df['y'] = df['y'].replace({None: np.nan})
Reference: Pandas Latest - Replace
The debug compilation is different from the release one, so:
Consider your Project file structure like that [this case if for a Debug assemble]:
src
|
debug
|
assets
|
index.html
You should call index.html into your WebView like:
web.loadUrl("file:///android_asset/index.html");
So forth, for the Release assemble, it should be like:
src
|
release
|
assets
|
index.html
The bellow structure also works, for both compilations [debug and release]:
src
|
main
|
assets
|
index.html
Code:
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
Required Permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
According to the highly upvoted comments, there are a few caveats to be aware of. This can return null
or ""
or even "???????"
, and it can return a stale phone number that is no longer valid. If you want something that uniquely identifies the device, you should use getDeviceId()
instead.
As suggested on the Chrome Mobile Emulation page, you can use Clumsy on Windows, Network Link Conditioner on Mac OS X and dummynet on Linux.
JavaScript is a dynamic language. You could just add it to the object itself.
var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};
Also, because all v3 objects extend MVCObject()
. You can use:
marker.setValues({type: "point", id: 1});
// or
marker.set("type", "point");
marker.set("id", 1);
var val = marker.get("id");
Give the DIV a specific with in percentage or pixels and center it using CSS margin property.
HTML
<div id="my-main-div"></div>
CSS
#my-main-div { margin: 0 auto; }
enjoy :)
Just yesterday I've added my git-analytics docker-compose file, which builds up several containers to start analyzing multiple git repositories against each other.
It is able to show you commit statistics over time about the author and also several diff statistics.
You can use the provided angular client and also kibana to visualize the statistics.
https://github.com/alexejsailer/git-analytics-docker
It will be improved over time.
my answer is transposed of 3x3 matrix
#include<iostream.h>
#include<math.h>
main()
{
int a[3][3];
int b[3];
cout<<"You must give us an array 3x3 and then we will give you Transposed it "<<endl;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cout<<"Enter a["<<i<<"]["<<j<<"]: ";
cin>>a[i][j];
}
}
cout<<"Matrix you entered is :"<<endl;
for (int e = 0 ; e < 3 ; e++ )
{
for ( int f = 0 ; f < 3 ; f++ )
cout << a[e][f] << "\t";
cout << endl;
}
cout<<"\nTransposed of matrix you entered is :"<<endl;
for (int c = 0 ; c < 3 ; c++ )
{
for ( int d = 0 ; d < 3 ; d++ )
cout << a[d][c] << "\t";
cout << endl;
}
return 0;
}
create or replace procedure my_proc( v_number IN number,p_rc OUT SYS_REFCURSOR )
as
begin
open p_rc
for select 1 col1
from dual;
end;
/
and then write a function lie this which calls your stored procedure
create or replace function my_proc_test(v_number IN NUMBER) RETURN sys_refcursor
as
p_rc sys_refcursor;
begin
my_proc(v_number,p_rc);
return p_rc;
end
/
then you can run this SQL query in the SQLDeveloper editor.
SELECT my_proc_test(3) FROM DUAL;
you will see the result in the console right click on it and cilck on single record view and edit the result you can see the all the records that were returned by the ref cursor.
You can delete files in PHP using the unlink()
function.
unlink('path/to/file.jpg');
Use BigInt datatype with its implicit operations. The plus point for it is it will not give answers in exponential representation. It will give full length result
Here is an example of addition
BigInteger big1 = new BigInteger("1234567856656567242177779");
BigInteger big2 = new BigInteger("12345565678566567131275737372777569");
BigInteger bigSum = big1.add(big2);
System.out.println(bigSum );
Another (probably not production-ready or recommended) method I just came up with is to concat the values to a string and count this string distinctively:
SELECT count(DISTINCT concat(id, name, address)) FROM mytable;
For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button
You need that code to be in the actionPerformed(...)
of the ActionListener
registered with the Start button, not for the Start button itself.
You can add a simple ActionListener
like this:
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
startButton.setEnabled(false);
stopButton.setEnabled(true);
}
}
);
note that your startButton above will need to be final
in the above example if you want to create the anonymous listener in local scope.
I made the follow action:
[HttpGet]
[Route("api/DownloadPdfFile/{id}")]
public HttpResponseMessage DownloadPdfFile(long id)
{
HttpResponseMessage result = null;
try
{
SQL.File file = db.Files.Where(b => b.ID == id).SingleOrDefault();
if (file == null)
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{
// sendo file to client
byte[] bytes = Convert.FromBase64String(file.pdfBase64);
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new ByteArrayContent(bytes);
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = file.name + ".pdf";
}
return result;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.Gone);
}
}
If you need to remove it from all your plots, you can remove spines in style settings (style sheet or rcParams). E.g:
import matplotlib as mpl
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.spines.top'] = False
If you want to remove all spines:
mpl.rcParams['axes.spines.left'] = False
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.bottom'] = False
The MDN documentation shows how the getItem
method is implementated:
Object.defineProperty(oStorage, "getItem", {
value: function (sKey) { return sKey ? this[sKey] : null; },
writable: false,
configurable: false,
enumerable: false
});
If the value isn't set, it returns null
. You are testing to see if it is undefined
. Check to see if it is null
instead.
if(localStorage.getItem("username") === null){
hai sir
There is one event which is default associate with any webcontrol. For example, in case of Button click event, in case of Check box CheckChangedEvent is there. So in case of AutoPostBack true these events are called by default and event handle at server sid
JPG does not support a transparent background, you can easily convert it to a PNG which does support a transparent background by opening it in near any photo editor and save it as a.PNG
This is how I applied the code snippet below and it's working fine. Hope, this would help somebody.
<EditText
android:id="@+id/EditText02"
android:gravity="top|left"
android:inputType="textMultiLine"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:lines="5"
android:scrollHorizontally="false"
/>
Cheers! ...Thanks.
A solution is possible only because of the difference between 1 megabyte and 1 million bytes. There are about 2 to the power 8093729.5 different ways to choose 1 million 8-digit numbers with duplicates allowed and order unimportant, so a machine with only 1 million bytes of RAM doesn't have enough states to represent all the possibilities. But 1M (less 2k for TCP/IP) is 1022*1024*8 = 8372224 bits, so a solution is possible.
Part 1, initial solution
This approach needs a little more than 1M, I'll refine it to fit into 1M later.
I'll store a compact sorted list of numbers in the range 0 to 99999999 as a sequence of sublists of 7-bit numbers. The first sublist holds numbers from 0 to 127, the second sublist holds numbers from 128 to 255, etc. 100000000/128 is exactly 781250, so 781250 such sublists will be needed.
Each sublist consists of a 2-bit sublist header followed by a sublist body. The sublist body takes up 7 bits per sublist entry. The sublists are all concatenated together, and the format makes it possible to tell where one sublist ends and the next begins. The total storage required for a fully populated list is 2*781250 + 7*1000000 = 8562500 bits, which is about 1.021 M-bytes.
The 4 possible sublist header values are:
00 Empty sublist, nothing follows.
01 Singleton, there is only one entry in the sublist and and next 7 bits hold it.
10 The sublist holds at least 2 distinct numbers. The entries are stored in non-decreasing order, except that the last entry is less than or equal to the first. This allows the end of the sublist to be identified. For example, the numbers 2,4,6 would be stored as (4,6,2). The numbers 2,2,3,4,4 would be stored as (2,3,4,4,2).
11 The sublist holds 2 or more repetitions of a single number. The next 7 bits give the number. Then come zero or more 7-bit entries with the value 1, followed by a 7-bit entry with the value 0. The length of the sublist body dictates the number of repetitions. For example, the numbers 12,12 would be stored as (12,0), the numbers 12,12,12 would be stored as (12,1,0), 12,12,12,12 would be (12,1,1,0) and so on.
I start off with an empty list, read a bunch of numbers in and store them as 32 bit integers, sort the new numbers in place (using heapsort, probably) and then merge them into a new compact sorted list. Repeat until there are no more numbers to read, then walk the compact list once more to generate the output.
The line below represents memory just before the start of the list merge operation. The "O"s are the region that hold the sorted 32-bit integers. The "X"s are the region that hold the old compact list. The "=" signs are the expansion room for the compact list, 7 bits for each integer in the "O"s. The "Z"s are other random overhead.
ZZZOOOOOOOOOOOOOOOOOOOOOOOOOO==========XXXXXXXXXXXXXXXXXXXXXXXXXX
The merge routine starts reading at the leftmost "O" and at the leftmost "X", and starts writing at the leftmost "=". The write pointer doesn't catch the compact list read pointer until all of the new integers are merged, because both pointers advance 2 bits for each sublist and 7 bits for each entry in the old compact list, and there is enough extra room for the 7-bit entries for the new numbers.
Part 2, cramming it into 1M
To Squeeze the solution above into 1M, I need to make the compact list format a bit more compact. I'll get rid of one of the sublist types, so that there will be just 3 different possible sublist header values. Then I can use "00", "01" and "1" as the sublist header values and save a few bits. The sublist types are:
A Empty sublist, nothing follows.
B Singleton, there is only one entry in the sublist and and next 7 bits hold it.
C The sublist holds at least 2 distinct numbers. The entries are stored in non-decreasing order, except that the last entry is less than or equal to the first. This allows the end of the sublist to be identified. For example, the numbers 2,4,6 would be stored as (4,6,2). The numbers 2,2,3,4,4 would be stored as (2,3,4,4,2).
D The sublist consists of 2 or more repetitions of a single number.
My 3 sublist header values will be "A", "B" and "C", so I need a way to represent D-type sublists.
Suppose I have the C-type sublist header followed by 3 entries, such as "C[17][101][58]". This can't be part of a valid C-type sublist as described above, since the third entry is less than the second but more than the first. I can use this type of construct to represent a D-type sublist. In bit terms, anywhere I have "C{00?????}{1??????}{01?????}" is an impossible C-type sublist. I'll use this to represent a sublist consisting of 3 or more repetitions of a single number. The first two 7-bit words encode the number (the "N" bits below) and are followed by zero or more {0100001} words followed by a {0100000} word.
For example, 3 repetitions: "C{00NNNNN}{1NN0000}{0100000}", 4 repetitions: "C{00NNNNN}{1NN0000}{0100001}{0100000}", and so on.
That just leaves lists that hold exactly 2 repetitions of a single number. I'll represent those with another impossible C-type sublist pattern: "C{0??????}{11?????}{10?????}". There's plenty of room for the 7 bits of the number in the first 2 words, but this pattern is longer than the sublist that it represents, which makes things a bit more complex. The five question-marks at the end can be considered not part of the pattern, so I have: "C{0NNNNNN}{11N????}10" as my pattern, with the number to be repeated stored in the "N"s. That's 2 bits too long.
I'll have to borrow 2 bits and pay them back from the 4 unused bits in this pattern. When reading, on encountering "C{0NNNNNN}{11N00AB}10", output 2 instances of the number in the "N"s, overwrite the "10" at the end with bits A and B, and rewind the read pointer by 2 bits. Destructive reads are ok for this algorithm, since each compact list gets walked only once.
When writing a sublist of 2 repetitions of a single number, write "C{0NNNNNN}11N00" and set the borrowed bits counter to 2. At every write where the borrowed bits counter is non-zero, it is decremented for each bit written and "10" is written when the counter hits zero. So the next 2 bits written will go into slots A and B, and then the "10" will get dropped onto the end.
With 3 sublist header values represented by "00", "01" and "1", I can assign "1" to the most popular sublist type. I'll need a small table to map sublist header values to sublist types, and I'll need an occurrence counter for each sublist type so that I know what the best sublist header mapping is.
The worst case minimal representation of a fully populated compact list occurs when all the sublist types are equally popular. In that case I save 1 bit for every 3 sublist headers, so the list size is 2*781250 + 7*1000000 - 781250/3 = 8302083.3 bits. Rounding up to a 32 bit word boundary, thats 8302112 bits, or 1037764 bytes.
1M minus the 2k for TCP/IP state and buffers is 1022*1024 = 1046528 bytes, leaving me 8764 bytes to play with.
But what about the process of changing the sublist header mapping ? In the memory map below, "Z" is random overhead, "=" is free space, "X" is the compact list.
ZZZ=====XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Start reading at the leftmost "X" and start writing at the leftmost "=" and work right. When it's done the compact list will be a little shorter and it will be at the wrong end of memory:
ZZZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=======
So then I'll need to shunt it to the right:
ZZZ=======XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
In the header mapping change process, up to 1/3 of the sublist headers will be changing from 1-bit to 2-bit. In the worst case these will all be at the head of the list, so I'll need at least 781250/3 bits of free storage before I start, which takes me back to the memory requirements of the previous version of the compact list :(
To get around that, I'll split the 781250 sublists into 10 sublist groups of 78125 sublists each. Each group has its own independent sublist header mapping. Using the letters A to J for the groups:
ZZZ=====AAAAAABBCCCCDDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
Each sublist group shrinks or stays the same during a sublist header mapping change:
ZZZ=====AAAAAABBCCCCDDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAA=====BBCCCCDDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABB=====CCCCDDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCC======DDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDD======EEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDDEEE======FFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDDEEEFFF======GGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDDEEEFFFGGGGGGGGGG=======HHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDDEEEFFFGGGGGGGGGGHH=======IJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDDEEEFFFGGGGGGGGGGHHI=======JJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDDEEEFFFGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ=======
ZZZ=======AAAAAABBCCCDDDDDEEEFFFGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
The worst case temporary expansion of a sublist group during a mapping change is 78125/3 = 26042 bits, under 4k. If I allow 4k plus the 1037764 bytes for a fully populated compact list, that leaves me 8764 - 4096 = 4668 bytes for the "Z"s in the memory map.
That should be plenty for the 10 sublist header mapping tables, 30 sublist header occurrence counts and the other few counters, pointers and small buffers I'll need, and space I've used without noticing, like stack space for function call return addresses and local variables.
Part 3, how long would it take to run?
With an empty compact list the 1-bit list header will be used for an empty sublist, and the starting size of the list will be 781250 bits. In the worst case the list grows 8 bits for each number added, so 32 + 8 = 40 bits of free space are needed for each of the 32-bit numbers to be placed at the top of the list buffer and then sorted and merged. In the worst case, changing the sublist header mapping results in a space usage of 2*781250 + 7*entries - 781250/3 bits.
With a policy of changing the sublist header mapping after every fifth merge once there are at least 800000 numbers in the list, a worst case run would involve a total of about 30M of compact list reading and writing activity.
Source:
this code works with me
ImageView carView = (ImageView) v.findViewById(R.id.car_icon);
byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
InputStream input=new ByteArrayInputStream(decodedString);
Bitmap ext_pic = BitmapFactory.decodeStream(input);
carView.setImageBitmap(ext_pic);
Did you override equals and hashCode in the Block class?
EDIT:
I assumed you mean it doesn't work at runtime... did you mean that or at compile time? If compile time what is the error message? If it crashes at runtime what is the stack trace? If it compiles and runs but doesn't work right then the equals and hashCode are the likely issue.
You're looking for Action<T>
, which takes a parameter.
This is live version of PHP Code to get your friends from Facebook
<?php
$user = $facebook->getUser();
if ($user) {
$user_profile = $facebook->api('/me');
$friends = $facebook->api('/me/friends');
echo '<ul>';
foreach ($friends["data"] as $value) {
echo '<li>';
echo '<div class="pic">';
echo '<img src="https://graph.facebook.com/' . $value["id"] . '/picture"/>';
echo '</div>';
echo '<div class="picName">'.$value["name"].'</div>';
echo '</li>';
}
echo '</ul>';
}
?>
A simple JavaScript function will do the job.
function ClearFields() {
document.getElementById("textfield1").value = "";
document.getElementById("textfield2").value = "";
}
And just have your button call it:
<button type="button" onclick="ClearFields();">Clear</button>
For checking for a time of day use:
TimeSpan start = new TimeSpan(10, 0, 0); //10 o'clock
TimeSpan end = new TimeSpan(12, 0, 0); //12 o'clock
TimeSpan now = DateTime.Now.TimeOfDay;
if ((now > start) && (now < end))
{
//match found
}
For absolute times use:
DateTime start = new DateTime(2009, 12, 9, 10, 0, 0)); //10 o'clock
DateTime end = new DateTime(2009, 12, 10, 12, 0, 0)); //12 o'clock
DateTime now = DateTime.Now;
if ((now > start) && (now < end))
{
//match found
}
For AngularJs you have to use "angular-datatables.min.js" file for datatable settings. You will get this from http://l-lin.github.io/angular-datatables/#/welcome.
After that you can write code like below,
<script>
var app = angular.module('AngularWayApp', ['datatables']);
</script>
<div ng-app="AngularWayApp" ng-controller="AngularWayCtrl">
<table id="example" datatable="ng" class="table">
<thead>
<tr>
<th><b>UserID</b></th>
<th><b>Firstname</b></th>
<th><b>Lastname</b></th>
<th><b>Email</b></th>
<th><b>Actions</b></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" ng-click="testingClick(user)">
<td>
{{user.UserId}}
</td>
<td>
{{user.FirstName}}
</td>
<td>
{{user.Lastname}}
</td>
<td>
{{user.Email}}
</td>
<td>
<span ng-click="editUser(user)" style="color:blue;cursor: pointer; font-weight:500; font-size:15px" class="btnAdd" data-toggle="modal" data-target="#myModal">Edit</span> |
<span ng-click="deleteUser(user)" style="color:red; cursor: pointer; font-weight:500; font-size:15px" class="btnRed">Delete</span>
</td>
</tr>
</tbody>
</table>
</div>
Go To Build.Gradle(module:app)
use this - minifyEnabled false
Windows:
system("cls");
Unix:
system("clear");
You could instead, insert newline chars until everything gets scrolled, take a look here.
With that, you achieve portability easily.
h2 { display: inline }
Git reset has 5 main modes: soft, mixed, merged, hard, keep. The difference between them is to change or not change head, stage (index), working directory.
Git reset --hard will change head, index and working directory.
Git reset --soft will change head only. No change to index, working directory.
So in other words if you want to undo your commit, --soft should be good enough. But after that you still have the changes from bad commit in your index and working directory. You can modify the files, fix them, add them to index and commit again.
With the --hard, you completely get a clean slate in your project. As if there hasn't been any change from the last commit. If you are sure this is what you want then move forward. But once you do this, you'll lose your last commit completely. (Note: there are still ways to recover the lost commit).
I know there area lot of correct answers here, with respect to all of them I introduce this hack :
In StartUp.cs
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
and then everywhere you need HttpContext you can use :
httpContext = new HttpContextAccessor().HttpContext;
Hope it helps ;)
If you wish to inject pure function, instead of text, you can use this method:
function inject(){_x000D_
document.body.style.backgroundColor = 'blue';_x000D_
}_x000D_
_x000D_
// this includes the function as text and the barentheses make it run itself._x000D_
var actualCode = "("+inject+")()"; _x000D_
_x000D_
document.documentElement.setAttribute('onreset', actualCode);_x000D_
document.documentElement.dispatchEvent(new CustomEvent('reset'));_x000D_
document.documentElement.removeAttribute('onreset');
_x000D_
And you can pass parameters (unfortunatelly no objects and arrays can be stringifyed) to the functions. Add it into the baretheses, like so:
function inject(color){_x000D_
document.body.style.backgroundColor = color;_x000D_
}_x000D_
_x000D_
// this includes the function as text and the barentheses make it run itself._x000D_
var color = 'yellow';_x000D_
var actualCode = "("+inject+")("+color+")";
_x000D_
My suggestions :
For setting the values in the number, use constructors. Do not use like the methods you have used above like :
public void setNumber(double fnum, double snum){ this.fn = fnum; this.sn = snum; }
Constructors exists to initialize the objects.This is their job and they are pretty good at it.
Getters for members of Calculate class seem in place. But setters are not. Getters and setters serves as one important block in the bridge of efficient programming with java. Put setters for fnum and snum as well
In the main class, create a Calculate object using the new operator and the constructor in place.
Call the getAnswer() method with the created Calculate object.
Rest of the code looks fine to me. Be modular. You could read your program in a much better way.
Here is my modular piece of code. Two files : Main.java & Calculate.java
public class Calculate {
private double fn;
private double sn;
private char op;
public double getFn() {
return fn;
}
public void setFn(double fn) {
this.fn = fn;
}
public double getSn() {
return sn;
}
public void setSn(double sn) {
this.sn = sn;
}
public char getOp() {
return op;
}
public void setOp(char op) {
this.op = op;
}
public Calculate(double fn, double sn, char op) {
this.fn = fn;
this.sn = sn;
this.op = op;
}
public void getAnswer(){
double ans;
switch (getOp()){
case '+':
ans = add(getFn(), getSn());
ansOutput(ans);
break;
case '-':
ans = sub (getFn(), getSn());
ansOutput(ans);
break;
case '*':
ans = mul (getFn(), getSn());
ansOutput(ans);
break;
case '/':
ans = div (getFn(), getSn());
ansOutput(ans);
break;
default:
System.out.println("--------------------------");
System.out.println("Invalid choice of operator");
System.out.println("--------------------------");
}
}
public static double add(double x,double y){
return x + y;
}
public static double sub(double x, double y){
return x - y;
}
public static double mul(double x, double y){
return x * y;
}
public static double div(double x, double y){
return x / y;
}
public static void ansOutput(double x){
System.out.println("----------- -------");
System.out.printf("the answer is %.2f\n", x);
System.out.println("-------------------");
}
}
public class Main {
public static void main(String args[])
{
Calculate obj = new Calculate(1,2,'+');
obj.getAnswer();
}
}
Moment.subtract
does not support an argument of type Moment - documentation:
moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(String, String); // 2.7.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);
The simplest solution is to specify the time delta as an object:
// Assumes string is hh:mm:ss
var myString = "03:15:00",
myStringParts = myString.split(':'),
hourDelta: +myStringParts[0],
minuteDelta: +myStringParts[1];
date.subtract({ hours: hourDelta, minutes: minuteDelta});
date.toString()
// -> "Sat Jun 07 2014 06:07:06 GMT+0100"
It is configured to use localhost:25
for the mail server.
The error message says that it can't connect to localhost:25
.
Therefore you have two options:
Droiddraw is good. I have been using it since long and haven't faced any issues yet (though it crashes sometimes, but thats ok)
Success to try it:
var letters:NSString = "abcdefghijkl"
var strRendom = NSMutableString.stringWithCapacity(strlength)
for var i=0; i<strlength; i++ {
let rndString = Int(arc4random() % 12)
//let strlk = NSString(format: <#NSString#>, <#CVarArg[]#>)
let strlk = NSString(format: "%c", letters.characterAtIndex(rndString))
strRendom.appendString(String(strlk))
}
find ./ -name "FOLDERNAME" | xargs rm -Rf
Should do the trick. WARNING, if you accidentally pump a .
or /
into xargs rm -Rf
your entire computer will be deleted without an option to get it back, requiring an OS reinstall.
In order for the client to be able to read cookies from cross-origin requests, you need to have:
All responses from the server need to have the following in their header:
Access-Control-Allow-Credentials: true
The client needs to send all requests with withCredentials: true
option
In my implementation with Angular 7 and Spring Boot, I achieved that with the following:
Server-side:
@CrossOrigin(origins = "http://my-cross-origin-url.com", allowCredentials = "true")
@Controller
@RequestMapping(path = "/something")
public class SomethingController {
...
}
The origins = "http://my-cross-origin-url.com"
part will add Access-Control-Allow-Origin: http://my-cross-origin-url.com
to every server's response header
The allowCredentials = "true"
part will add Access-Control-Allow-Credentials: true
to every server's response header, which is what we need in order for the client to read the cookies
Client-side:
import { HttpInterceptor, HttpXsrfTokenExtractor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from 'rxjs';
@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// send request with credential options in order to be able to read cross-origin cookies
req = req.clone({ withCredentials: true });
// return XSRF-TOKEN in each request's header (anti-CSRF security)
const headerName = 'X-XSRF-TOKEN';
let token = this.tokenExtractor.getToken() as string;
if (token !== null && !req.headers.has(headerName)) {
req = req.clone({ headers: req.headers.set(headerName, token) });
}
return next.handle(req);
}
}
With this class you actually inject additional stuff to all your request.
The first part req = req.clone({ withCredentials: true });
, is what you need in order to send each request with withCredentials: true
option. This practically means that an OPTION request will be send first, so that you get your cookies and the authorization token among them, before sending the actual POST/PUT/DELETE requests, which need this token attached to them (in the header), in order for the server to verify and execute the request.
The second part is the one that specifically handles an anti-CSRF token for all requests. Reads it from the cookie when needed and writes it in the header of every request.
The desired result is something like this:
1. You've got the right idea about how to design your resources, IMHO. I wouldn't change a thing.
2. Rather than trying to extend HTTP with more verbs, consider what your proposed verbs can be reduced to in terms of the basic HTTP methods and resources. For example, instead of an activate_login
verb, you could set up resources like: /api/users/1/login/active
which is a simple boolean. To activate a login, just PUT
a document there that says 'true' or 1 or whatever. To deactivate, PUT
a document there that is empty or says 0 or false.
Similarly, to change or set passwords, just do PUT
s to /api/users/1/password
.
Whenever you need to add something (like a credit) think in terms of POST
s. For example, you could do a POST
to a resource like /api/users/1/credits
with a body containing the number of credits to add. A PUT
on the same resource could be used to overwrite the value rather than add. A POST
with a negative number in the body would subtract, and so on.
3. I'd strongly advise against extending the basic HTTP status codes. If you can't find one that matches your situation exactly, pick the closest one and put the error details in the response body. Also, remember that HTTP headers are extensible; your application can define all the custom headers that you like. One application that I worked on, for example, could return a 404 Not Found
under multiple circumstances. Rather than making the client parse the response body for the reason, we just added a new header, X-Status-Extended
, which contained our proprietary status code extensions. So you might see a response like:
HTTP/1.1 404 Not Found
X-Status-Extended: 404.3 More Specific Error Here
That way a HTTP client like a web browser will still know what to do with the regular 404 code, and a more sophisticated HTTP client can choose to look at the X-Status-Extended
header for more specific information.
4. For authentication, I recommend using HTTP authentication if you can. But IMHO there's nothing wrong with using cookie-based authentication if that's easier for you.
A quick note that if you are using AWS ec2 instance then there is one more extra step that I believe is also mandatory. I missed the step-3 and it took me whole day to figure out to add an inbound rule to security group
Step 1(as previous): in your redis.conf change bind 127.0.0.1 to bind 0.0.0.0
Step2(as previous): in your redis.conf change protected-mode yes to protected-mode no
Step3: In your current ec2 machine go to the security group. add an inbound rule for custom TCP with 6379 port and select option "use from anywhere".
I built a program that inserts multiple lines to a server that was located in another city.
I found out that using this method was about 10 times faster than executemany
. In my case tup
is a tuple containing about 2000 rows. It took about 10 seconds when using this method:
args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup)
cur.execute("INSERT INTO table VALUES " + args_str)
and 2 minutes when using this method:
cur.executemany("INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)", tup)
setDate() has issues with month boundaries that are noted in comments above. A clean workaround is to find the date difference using epoch timestamps rather than the (surprisingly counterintuitive) methods on the Date object. I.e.
function getPreviousMonday(fromDate) {
var dayMillisecs = 24 * 60 * 60 * 1000;
// Get Date object truncated to date.
var d = new Date(new Date(fromDate || Date()).toISOString().slice(0, 10));
// If today is Sunday (day 0) subtract an extra 7 days.
var dayDiff = d.getDay() === 0 ? 7 : 0;
// Get date diff in millisecs to avoid setDate() bugs with month boundaries.
var mondayMillisecs = d.getTime() - (d.getDay() + dayDiff) * dayMillisecs;
// Return date as YYYY-MM-DD string.
return new Date(mondayMillisecs).toISOString().slice(0, 10);
}
You can create folder using the following Java code:
File dir = new File("nameoffolder");
dir.mkdir();
By executing above you will have folder 'nameoffolder' in current folder.
Suppose you want the value of the first item.
ListBox list = new ListBox();
Console.Write(list.Items[0].Value);
I don't know of any methodology to use to fix things like this. I don't think it would be possible to come up with one either for the very issue at hand is that your program's behavior is undefined (I don't know of any case when SEGFAULT hasn't been caused by some sort of UB).
There are all kinds of "methodologies" to avoid the issue before it arises. One important one is RAII.
Besides that, you just have to throw your best psychic energies at it.
Just use Control.Invoke Method or Control.BeginInvoke Method.
Great example: How to: Make Thread-Safe Calls to Windows Forms Controls.
try this
<input type="button" style="background-image:url('your_url')"/>
Recovering from Repository Corruption is the official answer.
The really short answer is: find uncorrupted objects and copy them.
Thanks I have added below snippet in POM.xml file and Mp problem resolved and create fat jar file that include all dependent jars.
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
Convert a string to a DateTime, you could try
DateTime timeValue = Convert.ToDateTime("01:00 PM");
Console.WriteLine(timeValue.ToString("HH:mm"));
If the trick using position:absolute
, position:relative
and top/left/bottom/right: 0px
is not appropriate for your situation, you could try:
#nav {
height: inherit;
}
This worked on one of our pages, although I am not sure exactly what other conditions were needed for it to succeed!
Why not like this?
SELECT count(1)
FROM AD_CurrentView
WHERE myColumn=1
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
How are you collecting user input in the first place? This question / answer may assist if you're using a FormController
:
@Creighton:
In Haskell there is a library function called product:
prouduct list = foldr 1 (*) list
or simply:
product = foldr 1 (*)
so the "idiomatic" factorial
fac n = foldr 1 (*) [1..n]
would simply be
fac n = product [1..n]
Check out the documentation on MSDN for the Hashtable class.
Represents a collection of key-and-value pairs that are organized based on the hash code of the key.
Also, keep in mind that this is not thread-safe.
Microsoft has a tool just for this purpose: Microsoft Expression Web. There's a free version with a bunch of FrontPage/Dreamweaver-like garbage that nobody wants. What's important is that it has a great browser testing feature. I'm running Windows 8.1 Pro (final release, not preview) with Internet Explorer 11. I get these local browsers:
Then I get a Remote Browsers (Beta) option. I'm supposed to sign up with a valid e-mail, but there's an error communicating with the server. Oh well.
Firefox used to be supported, but I don't see it now. Might be hiding.
I can compare side-by-side between browser versions. I can also compare with an image, or apparently, a PSD file (no idea how well that works). InDesign would be nice, but that's probably asking for too much.
I have the full version of Expression partially installed as well due to Visual Studio Ultimate being on the same computer, so I'd appreciate someone confirming in a comment that my free installation isn't automatically upgrading.
Update: Looks like the online service was discontinued, but local browsers are still supported. You can also download just SuperPreview, without the editor garbage. If you want the full IDE, the latest version is Microsoft Expression Web 4 (Free Version). Here's the official list of supported browsers. IE6 seems to give an error on Windows 8.1, but IE7 works.
Update 2014-12-09: Microsoft has pretty much given up on this. Don't expect it to work well.
You could also try this
Private Sub CommandButton1_Click()
Sheets("Sheet1").Range("A3:E3").Copy
Dim lastrow As Long
lastrow = Range("A65536").End(xlUp).Row
Sheets("Summary Info").Activate
Cells(lastrow + 1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End Sub
To quote the documentation:
Key words and unquoted identifiers are case insensitive. Therefore:
UPDATE MY_TABLE SET A = 5;
can equivalently be written as:
uPDaTE my_TabLE SeT a = 5;
You could also write it using quoted identifiers:
UPDATE "my_table" SET "a" = 5;
Quoting an identifier makes it case-sensitive, whereas unquoted names are always folded to lower case (unlike the SQL standard where unquoted names are folded to upper case). For example, the identifiers FOO
, foo
, and "foo"
are considered the same by PostgreSQL, but "Foo"
and "FOO"
are different from these three and each other.
If you want to write portable applications you are advised to always quote a particular name or never quote it.
Note that SimpleDateFormat format pattern Z is for RFC 822 time zone and pattern X is for ISO 8601 (this standard supports single letter time zone names like Z for Zulu).
So new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
produces a format that can parse both "2013-03-11T01:38:18.309Z"
and "2013-03-11T01:38:18.309+0000"
and will give you the same result.
Unfortunately, as far as I can tell, you can't get this format to generate the Z for Zulu version, which is annoying.
I actually have more trouble on the JavaScript side to deal with both formats.
I have written long back thought to share here
class SingletonDesignPattern {
//just for demo there will be only one instance
private static $instanceCount =0;
//create the private instance variable
private static $myInstance=null;
//make constructor private so no one create object using new Keyword
private function __construct(){}
//no one clone the object
private function __clone(){}
//avoid serialazation
public function __wakeup(){}
//ony one way to create object
public static function getInstance(){
if(self::$myInstance==null){
self::$myInstance=new SingletonDesignPattern();
self::$instanceCount++;
}
return self::$myInstance;
}
public static function getInstanceCount(){
return self::$instanceCount;
}
}
//now lets play with singleton design pattern
$instance = SingletonDesignPattern::getInstance();
$instance = SingletonDesignPattern::getInstance();
$instance = SingletonDesignPattern::getInstance();
$instance = SingletonDesignPattern::getInstance();
echo "number of instances: ".SingletonDesignPattern::getInstanceCount();
Even I was having the same problem, I am having checkbox, did the following to masker itemClickListener work,
Added the following properties to the checkbox,
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
and ItemClickListner started working.
For detailed example you can go through the link,
http://knowledge-cess.com/android-itemclicklistner-with-checkbox-or-radiobutton/
Hope it helps Cheers!!
var minRows = 5;
var maxRows = 26;
function ResizeTextarea(id) {
var t = document.getElementById(id);
if (t.scrollTop == 0) t.scrollTop=1;
while (t.scrollTop == 0) {
if (t.rows > minRows)
t.rows--; else
break;
t.scrollTop = 1;
if (t.rows < maxRows)
t.style.overflowY = "hidden";
if (t.scrollTop > 0) {
t.rows++;
break;
}
}
while(t.scrollTop > 0) {
if (t.rows < maxRows) {
t.rows++;
if (t.scrollTop == 0) t.scrollTop=1;
} else {
t.style.overflowY = "auto";
break;
}
}
}
Kinda old subject but I had same question a few days ago and I came up with another idea (maybe someone will still find it usefull)
For example you can make a config.bat with different subjects (family, size, color, animals) and apply them individually in any order anywhere you want in your batch scripts:
@echo off
rem Empty the variable to be ready for label config_all
set config_all_selected=
rem Go to the label with the parameter you selected
goto :config_%1
REM This next line is just to go to end of file
REM in case that the parameter %1 is not set
goto :end
REM next label is to jump here and get all variables to be set
:config_all
set config_all_selected=1
:config_family
set mother=Mary
set father=John
set sister=Anna
rem This next line is to skip going to end if config_all label was selected as parameter
if not "%config_all_selected%"=="1" goto :end
:config_test
set "test_parameter_all=2nd set: The 'all' parameter WAS used before this echo"
if not "%config_all_selected%"=="1" goto :end
:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end
:config_color
set first_color=blue
set second_color=green
if not "%config_all_selected%"=="1" goto :end
:config_animals
set dog=Max
set cat=Miau
if not "%config_all_selected%"=="1" goto :end
:end
After that, you can use it anywhere by calling fully with 'call config.bat all' or calling only parts of it (see example bellow) The idea in here is that sometimes is more handy when you have the option not to call everything at once. Some variables maybe you don't want to be called yet so you can call them later.
Example test.bat
@echo off
rem This is added just to test the all parameter
set "test_parameter_all=1st set: The 'all' parameter was NOT used before this echo"
call config.bat size
echo My birthday present had a width of %width% and a height of %height%
call config.bat family
call config.bat animals
echo Yesterday %father% and %mother% surprised %sister% with a cat named %cat%
echo Her brother wanted the dog %dog%
rem This shows you if the 'all' parameter was or not used (just for testing)
echo %test_parameter_all%
call config.bat color
echo His lucky color is %first_color% even if %second_color% is also nice.
echo.
pause
Hope it helps the way others help me in here with their answers.
A short version of the above:
config.bat
@echo off
set config_all_selected=
goto :config_%1
goto :end
:config_all
set config_all_selected=1
:config_family
set mother=Mary
set father=John
set daughter=Anna
if not "%config_all_selected%"=="1" goto :end
:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end
:end
test.bat
@echo off
call config.bat size
echo My birthday present had a width of %width% and a height of %height%
call config.bat family
echo %father% and %mother% have a daughter named %daughter%
echo.
pause
Good day.
Note, you may also be interested in:
Custom web font not working in IE9
Which includes a more descriptive breakdown of the CSS you see below (and explains the tweaks that make it work better on IE6-9).
@font-face {
font-family: 'Bumble Bee';
src: url('bumblebee-webfont.eot');
src: local('?'),
url('bumblebee-webfont.woff') format('woff'),
url('bumblebee-webfont.ttf') format('truetype'),
url('bumblebee-webfont.svg#webfontg8dbVmxj') format('svg');
}
@font-face {
font-family: 'GestaReFogular';
src: url('gestareg-webfont.eot');
src: local('?'),
url('gestareg-webfont.woff') format('woff'),
url('gestareg-webfont.ttf') format('truetype'),
url('gestareg-webfont.svg#webfontg8dbVmxj') format('svg');
}
body {
background: #fff url(../images/body-bg-corporate.gif) repeat-x;
padding-bottom: 10px;
font-family: 'GestaRegular', Arial, Helvetica, sans-serif;
}
h1 {
font-family: "Bumble Bee", "Times New Roman", Georgia, Serif;
}
And your follow-up questions:
Q. I would like to use a font such as "Bumble bee," for example. How can I use
@font-face
to make that font available on the user's computer?
Note that I don't know what the name of your Bumble Bee font or file is, so adjust accordingly, and that the font-face declaration should precede (come before) your use of it, as I've shown above.
Q. Can I still use the other
@font-face
typeface "GestaRegular" as well? Can I use both in the same stylesheet?
Just list them together as I've shown in my example. There is no reason you can't declare both. All that @font-face
does is instruct the browser to download and make a font-family available. See: http://iliadraznin.com/2009/07/css3-font-face-multiple-weights
There is one built into windows 7 in which you can open by clicking the windows and r keys at the same time and then typing edit.com.
I hope this helped
This is one way to access(and have used) self
from inside a decorator
defined inside the same class:
class Thing(object):
def __init__(self, name):
self.name = name
def debug_name(function):
def debug_wrapper(*args):
self = args[0]
print 'self.name = ' + self.name
print 'running function {}()'.format(function.__name__)
function(*args)
print 'self.name = ' + self.name
return debug_wrapper
@debug_name
def set_name(self, new_name):
self.name = new_name
Output (tested on Python 2.7.10
):
>>> a = Thing('A')
>>> a.name
'A'
>>> a.set_name('B')
self.name = A
running function set_name()
self.name = B
>>> a.name
'B'
The example above is silly, but it works.
With Java 7 or above you could use
ThreadLocalRandom.current().nextInt(int origin, int bound)
Javadoc: ThreadLocalRandom.nextInt
Necromancing.
I use this to load dependant scripts;
it works with IE8+ without adding any dependency on another library like jQuery !
var cScriptLoader = (function ()
{
function cScriptLoader(files)
{
var _this = this;
this.log = function (t)
{
console.log("ScriptLoader: " + t);
};
this.withNoCache = function (filename)
{
if (filename.indexOf("?") === -1)
filename += "?no_cache=" + new Date().getTime();
else
filename += "&no_cache=" + new Date().getTime();
return filename;
};
this.loadStyle = function (filename)
{
// HTMLLinkElement
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = _this.withNoCache(filename);
_this.log('Loading style ' + filename);
link.onload = function ()
{
_this.log('Loaded style "' + filename + '".');
};
link.onerror = function ()
{
_this.log('Error loading style "' + filename + '".');
};
_this.m_head.appendChild(link);
};
this.loadScript = function (i)
{
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = _this.withNoCache(_this.m_js_files[i]);
var loadNextScript = function ()
{
if (i + 1 < _this.m_js_files.length)
{
_this.loadScript(i + 1);
}
};
script.onload = function ()
{
_this.log('Loaded script "' + _this.m_js_files[i] + '".');
loadNextScript();
};
script.onerror = function ()
{
_this.log('Error loading script "' + _this.m_js_files[i] + '".');
loadNextScript();
};
_this.log('Loading script "' + _this.m_js_files[i] + '".');
_this.m_head.appendChild(script);
};
this.loadFiles = function ()
{
// this.log(this.m_css_files);
// this.log(this.m_js_files);
for (var i = 0; i < _this.m_css_files.length; ++i)
_this.loadStyle(_this.m_css_files[i]);
_this.loadScript(0);
};
this.m_js_files = [];
this.m_css_files = [];
this.m_head = document.getElementsByTagName("head")[0];
// this.m_head = document.head; // IE9+ only
function endsWith(str, suffix)
{
if (str === null || suffix === null)
return false;
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
for (var i = 0; i < files.length; ++i)
{
if (endsWith(files[i], ".css"))
{
this.m_css_files.push(files[i]);
}
else if (endsWith(files[i], ".js"))
{
this.m_js_files.push(files[i]);
}
else
this.log('Error unknown filetype "' + files[i] + '".');
}
}
return cScriptLoader;
})();
var ScriptLoader = new cScriptLoader(["foo.css", "Scripts/Script4.js", "foobar.css", "Scripts/Script1.js", "Scripts/Script2.js", "Scripts/Script3.js"]);
ScriptLoader.loadFiles();
If you are interested in the typescript-version used to create this:
class cScriptLoader {
private m_js_files: string[];
private m_css_files: string[];
private m_head:HTMLHeadElement;
private log = (t:any) =>
{
console.log("ScriptLoader: " + t);
}
constructor(files: string[]) {
this.m_js_files = [];
this.m_css_files = [];
this.m_head = document.getElementsByTagName("head")[0];
// this.m_head = document.head; // IE9+ only
function endsWith(str:string, suffix:string):boolean
{
if(str === null || suffix === null)
return false;
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
for(let i:number = 0; i < files.length; ++i)
{
if(endsWith(files[i], ".css"))
{
this.m_css_files.push(files[i]);
}
else if(endsWith(files[i], ".js"))
{
this.m_js_files.push(files[i]);
}
else
this.log('Error unknown filetype "' + files[i] +'".');
}
}
public withNoCache = (filename:string):string =>
{
if(filename.indexOf("?") === -1)
filename += "?no_cache=" + new Date().getTime();
else
filename += "&no_cache=" + new Date().getTime();
return filename;
}
public loadStyle = (filename:string) =>
{
// HTMLLinkElement
let link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = this.withNoCache(filename);
this.log('Loading style ' + filename);
link.onload = () =>
{
this.log('Loaded style "' + filename + '".');
};
link.onerror = () =>
{
this.log('Error loading style "' + filename + '".');
};
this.m_head.appendChild(link);
}
public loadScript = (i:number) =>
{
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = this.withNoCache(this.m_js_files[i]);
var loadNextScript = () =>
{
if (i + 1 < this.m_js_files.length)
{
this.loadScript(i + 1);
}
}
script.onload = () =>
{
this.log('Loaded script "' + this.m_js_files[i] + '".');
loadNextScript();
};
script.onerror = () =>
{
this.log('Error loading script "' + this.m_js_files[i] + '".');
loadNextScript();
};
this.log('Loading script "' + this.m_js_files[i] + '".');
this.m_head.appendChild(script);
}
public loadFiles = () =>
{
// this.log(this.m_css_files);
// this.log(this.m_js_files);
for(let i:number = 0; i < this.m_css_files.length; ++i)
this.loadStyle(this.m_css_files[i])
this.loadScript(0);
}
}
var ScriptLoader = new cScriptLoader(["foo.css", "Scripts/Script4.js", "foobar.css", "Scripts/Script1.js", "Scripts/Script2.js", "Scripts/Script3.js"]);
ScriptLoader.loadFiles();
If it's to load a dynamic list of scripts, write the scripts into an attribute, such as data-main, e.g.
<script src="scriptloader.js" data-main="file1.js,file2.js,file3.js,etc." ></script>
and do a element.getAttribute("data-main").split(',')
such as
var target = document.currentScript || (function() {
var scripts = document.getElementsByTagName('script');
// Note: this is for IE as IE doesn't support currentScript
// this does not work if you have deferred loading with async
// e.g. <script src="..." async="async" ></script>
// https://web.archive.org/web/20180618155601/https://www.w3schools.com/TAgs/att_script_async.asp
return scripts[scripts.length - 1];
})();
target.getAttribute("data-main").split(',')
to obtain the list.
This might be what you are looking for:
<?php
$text = 'This is a Simple text.';
// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');
// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>
Is it?
Or maybe this:
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
Or even this
<?php
$email = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>
You can read all about them in the documentation here:
The sexiest version by far is with format strings.
from datetime import datetime
print(f'{datetime.today():%Y-%m-%d}')
You are prematurely optimizing. Also, you should really put some thought into whether GET should be used for stuff you're POST-ing, for security reasons.
Something like...
Minutes.minutesBetween(getStart(), getEnd()).getMinutes();
First check if your wlan card support hosted network and if no update the card driver. Follow this steps
1) open cmd with administrative rights
2) on the black screen type: netsh wlan show driver | findstr Hosted
3) See Hosted network supported, if No then update drivers
import/export
is now doing the job with ES6. I still tend to prefix not exported functions with _
if most of my functions are exported.
If you export only a class (like in angular projects), it's not needed at all.
export class MyOpenClass{
open(){
doStuff()
this._privateStuff()
return close();
}
_privateStuff() { /* _ only as a convention */}
}
function close(){ /*... this is really private... */ }
I was having this same problem using Angular CLI. I needed to import the bootstrap.js.min
file in the .angular-cli.json file:
"scripts": ["../node_modules/jquery/dist/jquery.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js"],
It looks like you probably pasted this (or used a word processor like MS Word) using a kind of double-quotes that are not recognized by the browser. Please check that your code uses actual double-quotes like this one "
, which is different from the following character: ”
Replace the meta tag with this one and try again:
<meta http-equiv="refresh" content="5" >
see more this url:
http://www.baeldung.com/spring-nosuchbeandefinitionexception
There are two steps:
** You can set width by setting fixed Pixels like "150 px" or by percentage like"10%".
Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.
Try as follows:
Enter the following formula:
=ISERROR(MATCH(A1,$B$1:$B$10,0))
Now select the format you want to highlight the values in col A that do not appear in col B
This will highlight any value in Col A that does not appear in Col B.
As there is no proper wheel file in http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv?
Try this:(Worked in Anaconda Prompt or Pycharm)
pip install opencv-contrib-python
pip install opencv-python
val list = List(1, 2, 4, 2, 4, 7, 3, 2, 4)
// Using the provided count method this would yield the occurrences of each value in the list:
l map(x => l.count(_ == x))
List[Int] = List(1, 3, 3, 3, 3, 1, 1, 3, 3)
// This will yield a list of pairs where the first number is the number from the original list and the second number represents how often the first number occurs in the list:
l map(x => (x, l.count(_ == x)))
// outputs => List[(Int, Int)] = List((1,1), (2,3), (4,3), (2,3), (4,3), (7,1), (3,1), (2,3), (4,3))
str.erase( str.end()-1 )
Reference: std::string::erase() prototype 2
no c++11 or c++0x needed.
The arrow is a border.
You need to change for each arrow the color depending on the 'data-placement' of the tooltip.
.tooltip.top .tooltip-arrow {
border-top-color: @color;
}
.tooltip.top-left .tooltip-arrow {
border-top-color: @color;
}
.tooltip.top-right .tooltip-arrow {
border-top-color:@color;
}
.tooltip.right .tooltip-arrow {
border-right-color: @color;
}
.tooltip.left .tooltip-arrow {
border-left-color: @color;
}
.tooltip.bottom .tooltip-arrow {
border-bottom-color: @color;
}
.tooltip.bottom-left .tooltip-arrow {
border-bottom-color: @color;
}
.tooltip.bottom-right .tooltip-arrow {
border-bottom-color: @color;
}
.tooltip > .tooltip-inner {
background-color: @color;
}
Unless you do some kind of post-processing work, the video will never be better than the original frames. Also just like a flip-book, if you have a big "jump" between keyframes it will look funny. You generally need enough "tweens" in between the keyframes to give smooth animation. HTH
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
Don't use jsonObject.toString
on a JSON object.
Css:
br {
display: block;
margin: 10px 0;
}
The solution is probably not cross-browser compatible, but it's something at least. Also consider setting line-height
:
line-height:22px;
For Google Chrome, consider setting content
:
content: " ";
Other than that, I think you're stuck with a JavaScript solution.
Like as has been said already, . location
is an objectBut that person suggested using either. But, you will do better to use the .href
version.
Objects have default properties which, if nothing else is specified, they are assumed. In the case of the location
object, it has a property called .href
. And by not specifying ANY property during the assignment, it will assume "href" by default.
This is all well and fine until a later object model version changes and there either is no longer a default property, or the default property is changed. Then your program breaks unexpectedly.
If you mean href
, you should specify href
.
If you don't need to do it through code, just press CTRL+L
I had faced the same problem while accessing any hard drive directory. Then I solved it in this way.
import os
os.startfile("D:\folder_name\file_name") #running shortcut
os.startfile("F:") #accessing directory
The picture above shows an error and resolved output.
Many long (and correct) answers here. But usually you won't do these things manually - at least not when you set up your first projects for development (this is where you usually stumble upon these things). If you use koa for the backend: use koa-cors. Install via npm...
npm install --save koa-cors
...and use it in the code:
const cors = require('koa-cors');
const Koa = require('koa');
const app = new Koa();
app.use(cors());
problem solved.
In my case it was just an old cached Javascript file. After clearing the cache I saw my logs.
The counter variable inside the loop is called loop.index in jinja2.
>>> from jinja2 import Template
>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}"
>>> Template(s).render(elements=["a", "b", "c", "d"])
1 2 3 4
See http://jinja.pocoo.org/docs/templates/ for more.
Passphrases can be added to an existing key or changed without regenerating the key pair:
Note This will work if keys doesn't had a passphrase, otherwise you'll get this: Enter old passphrase:
then Bad passphrase
$ ssh-keygen -p
Enter file in which the key is (/Users/tekkub/.ssh/id_rsa):
Key has comment '/Users/tekkub/.ssh/id_rsa'
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved with the new passphrase.
If your key had passphrase
then, There's no way to recover the passphrase for a pair of SSH keys. In that case you have to create a new pair of SSH keys.
Use negative lookaround: (?!
pattern
)
Positive lookarounds can be used to assert that a pattern matches. Negative lookarounds is the opposite: it's used to assert that a pattern DOES NOT match. Some flavor supports assertions; some puts limitations on lookbehind, etc.
These are attempts to come up with regex solutions to toy problems as exercises; they should be educational if you're trying to learn the various ways you can use lookarounds (nesting them, using them to capture, etc):
Just an extension, if anyone need a library then this might help. Thanks to Raghav
My problem was that a webfilter didn't allow me to download the node-sass package, when I executed the command
npm i
After the installation of the Windows Build Tools
npm i -g windows-build-tools
it build node-sass
on it's own and now I can use it.
PS: I also installed Python 2.7.17 before, but I don't think that helped.
Its extremely easy! Create a file that contains:
call <filename> // the file you made
cls
echo An error occured!
<Your commands>
pause
So now when you start it, it will launch your program as normal. But when anything goes wrong it exits and continues the script inside the first file. Now there you can put your own commands in.
You can't really compare NA
with another value, so using ==
would not work. Consider the following:
NA == NA
# [1] NA
You can just change your comparison from ==
to %in%
:
ifelse(is.na(test$time) | test$type %in% "A", NA, "1")
# [1] NA "1" NA "1"
Regarding your other question,
I could get this to work with my existing code if I could somehow change the result of
is.na(test$type)
to returnFALSE
instead ofTRUE
, but I'm not sure how to do that.
just use !
to negate the results:
!is.na(test$time)
# [1] TRUE TRUE FALSE TRUE
I use the following:
lastrow = ActiveSheet.Columns("A").Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
It'll find the last row in a specific column. If you want the last used row for any column then:
lastrow = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
Interfaces are only at compile time. This allows only you to check that the expected data received follows a particular structure. For this you can cast your content to this interface:
this.http.get('...')
.map(res => <Product[]>res.json());
See these questions:
You can do something similar with class but the main differences with class are that they are present at runtime (constructor function) and you can define methods in them with processing. But, in this case, you need to instantiate objects to be able to use them:
this.http.get('...')
.map(res => {
var data = res.json();
return data.map(d => {
return new Product(d.productNumber,
d.productName, d.productDescription);
});
});
And yet another possibility:
In [2]: a = array([1, 2, 3, -4, 5])
In [3]: where(a<0, 0, a)
Out[3]: array([1, 2, 3, 0, 5])
Off the top of my head you could do this with a ScrollView. Your top-level container could be a flex container, inside that have a ScrollView at the top and your footer at the bottom. Then inside the ScrollView just put the rest of your app as normal.
This is related to Content-Type
. As you might have noticed from other discussions and answers to this question some people were able to solve it by setting Content-Type: 'application/json'
. Unfortunately in my case it didn't work, my POST request was still empty on the server side.
However, if you try with jQuery's $.post()
and it's working, the reason is probably because of jQuery using Content-Type: 'x-www-form-urlencoded'
instead of application/json
.
data = Object.keys(data).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])).join('&')
fetch('/api/', {
method: 'post',
credentials: "include",
body: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
If your label is in table, padding may cause it to expand. To avoid this you may use margin:
div label {
display: block;
text-align: left;
margin-bottom: -0.2%;
}
Or you can use querySelectorAll
which returns NodeList:
document.querySelectorAll('.myclass').forEach(...)
Supported by modern browsers (including Edge, but not IE):
Can I use querySelectorAll
NodeList.prototype.forEach()
Use the <shape>
tag to create a drawable in XML with rounded corners. (You can do other stuff with the shape tag like define a color gradient as well).
Here's a copy of a XML file I'm using in one of my apps to create a drawable with a white background, black border and rounded corners:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffffff"/>
<stroke android:width="3dp"
android:color="#ff000000" />
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp" />
<corners android:radius="7dp" />
</shape>
This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding
ABS(CHARINDEX(' ', PostCode ) -1))
which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1)
is a -ve value. Correct me if I'm wrong!
Try upgrade pip with the below command and retry
python -m pip install -U pip
The easiest option to do that is running a VM with a OSX copy.
You can also use head
and tail
:
In [29]: pd.concat([df.head(1), df.tail(1)])
Out[29]:
a b
0 1 a
3 4 d
1. We can use aggregate function with HAVING clause not by WHERE clause e.g. min,max,avg.
2. WHERE clause eliminates the record tuple by tuple HAVING clause eliminates entire group from the collection of group
Mostly HAVING is used when you have groups of data and WHERE is used when you have data in rows.
To merge one branch into another, such as merging "feature_x" branch into "master" branch:
git checkout master
git merge feature_x
This page is the first result for several search engines when looking for "git merge one branch into another". However, the original question is more specific and special case than the title would suggest.
It is also more complex than both the subject and the search expression. As such, this is a minimal but explanatory answer for the benefit of most visitors.
cd <ANDROID_SDK_PATH>
(for me on Windows cd C:\Users\Willi\AppData\Local\Android\sdk
)cd platform-tools
adb shell
(this works only if only one emulator is running)cd data/data
su
(gain super user privileges)cd <PACKAGE_NAME>/databases
sqlite3 <DB_NAME>
;
, otherwise the statement is not issued and it breaks to a new line instead.)Note: Use ls
(Linux) or dir
(Windows) if you need to list directory contents.
There actually is now a GAC Utility for .NET 4.0. It is found in the Microsoft Windows 7 and .NET 4.0 SDK (the SDK supports multiple OSs -- not just Windows 7 -- so if you are using a later OS from Microsoft the odds are good that it's supported).
This is the SDK. You can download the ISO or do a Web install. Kind-of overkill to download the entire thing if all you want is the GAC Util; however, it does work.
Using py2exe, include this in your setup.py:
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1}},
windows = [{'script': "YourScript.py"}],
zipfile = None,
)
then you can run it through command prompt / Idle, both works for me. Hope it helps
What are native methods in Java and where should they be used?
Once you see a small example, it becomes clear:
Main.java:
public class Main {
public native int intMethod(int i);
public static void main(String[] args) {
System.loadLibrary("Main");
System.out.println(new Main().intMethod(2));
}
}
Main.c:
#include <jni.h>
#include "Main.h"
JNIEXPORT jint JNICALL Java_Main_intMethod(
JNIEnv *env, jobject obj, jint i) {
return i * i;
}
Compile and run:
javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
-I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main
Output:
4
Tested on Ubuntu 14.04 with Oracle JDK 1.8.0_45.
So it is clear that it allows you to:
This could be used to:
with the tradeoff of lower portability.
It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?
Example on GitHub for you to play with.
I think it may be the sudo has no access to get ORACLE_HOME.You can do like this.
sudo visudo
modify the text add
Defaults env_keep += "ORACLE_HOME"
then
sudo python setup.py build install
If you want to use Visual Studio option, please see How to remove Nuget Packages from Existing Visual Studio solution:
Step 1:
In Visual Studio, Go to Tools/NuGet Package Manager/Manage NuGet Packages for Solution…
Step 2:
UnCheck your project(s) from Current solution
Step 3:
Unselect project(s) and press OK
Main point you are looking for is:
.tag-remove::before {
content: 'x'; // here is your X(cross) sign.
color: #fff;
font-weight: 300;
font-family: Arial, sans-serif;
}
FYI, you can make a close button by yourself very easily:
#mdiv {_x000D_
width: 25px;_x000D_
height: 25px;_x000D_
background-color: red;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
.mdiv {_x000D_
height: 25px;_x000D_
width: 2px;_x000D_
margin-left: 12px;_x000D_
background-color: black;_x000D_
transform: rotate(45deg);_x000D_
Z-index: 1;_x000D_
}_x000D_
_x000D_
.md {_x000D_
height: 25px;_x000D_
width: 2px;_x000D_
background-color: black;_x000D_
transform: rotate(90deg);_x000D_
Z-index: 2;_x000D_
}
_x000D_
<div id="mdiv">_x000D_
<div class="mdiv">_x000D_
<div class="md"></div>_x000D_
</div>_x000D_
</div>
_x000D_
Please note there's also git reset --soft HEAD^
. It's similar to git reset
(which defaults to --mixed
) but it retains the index contents. So that if you've added/removed files, you have them in the index already.
Turns out to be very useful in case of giant commits.
$unit1 = "paragrahp1";
$unit2 = "paragrahp2";
echo '<p>'.$unit1.'</p>';
echo '<p>'.$unit2.'</p>';
Use Tag <p>
always when starting with a new line so you don't need to use /n type syntax.
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
Assumes, you have a data.json file in the src/app folder of your project with the following values:
[
{
"id": 1,
"name": "Licensed Frozen Hat",
"description": "Incidunt et magni est ut.",
"price": "170.00",
"imageUrl": "https://source.unsplash.com/1600x900/?product",
"quantity": 56840
},
...
]
import { Component, OnInit } from '@angular/core';
import * as data from './data.json';
@Component({
selector: 'app-root',
template: `<ul>
<li *ngFor="let product of products">
</li>
</ul>`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Angular Example';
products: any = (data as any).default;
constructor(){}
ngOnInit(){
console.log(data);
}
}
import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";
@Component({
selector: 'app-root',
template: `<ul>
<li *ngFor="let product of products">
</li>
</ul>`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Angular Example';
products: any = [];
constructor(private httpClient: HttpClient){}
ngOnInit(){
this.httpClient.get("assets/data.json").subscribe(data =>{
console.log(data);
this.products = data;
})
}
}
But first we need to add a typing file as follows:
declare module "*.json" {
const value: any;
export default value;
}
Add this inside a new file json-typings.d.ts
file in the src/app folder.
Now, you can import JSON files just like TypeScript 2.9+.
import * as data from "data.json";
md5sum
worked fine for me, but I had issues with sort
and sorting file names. So instead I sorted by md5sum
result. I also needed to exclude some files in order to create comparable results.
find . -type f -print0 \
| xargs -r0 md5sum \
| grep -v ".env" \
| grep -v "vendor/autoload.php" \
| grep -v "vendor/composer/" \
| sort -d \
| md5sum
For hibernate5 I solved this issue by puting next lines in my application.properties file:
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Have you considered applying ON DELETE CASCADE
where relevant?
You can try this,
$info = pathinfo($_FILES['userFile']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "newname.".$ext;
$target = 'images/'.$newname;
move_uploaded_file( $_FILES['userFile']['tmp_name'], $target);
No, that would be a huge security breach. Imagine if someone could run
format c:
whenever you visted their website.
Here's an example of one with dynamic columns and rows with angularJS: http://plnkr.co/edit/0fsRUp?p=preview
Date
itself is not deprecated. It's just a lot of its methods are. See here for details.
Use java.util.Calendar
instead.
use return
for this
if(i==1) {
return; //stop the execution of function
}
//keep on going
Only changing the settings with the following command did not work in my environment:
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
I had to also ran the Force Merge API command:
curl -X POST "localhost:9200/my-index-000001/_forcemerge?pretty"
ref: Force Merge API
FAT32
along with FAT16
and FAT12
are File System Types, but vfat
along with umsdos
and msdos
are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos
driver don't have long filenames (they are 8.3 format). vfat
is the most common driver for mounting FAT32 file systems nowadays.
Source: this wikipedia article
Output of commands like df
and lsblk
indeed show vfat
as the File System Type. But sudo file -sL /dev/<partition>
shows FAT (32 bit)
if a File System is FAT32.
You can confirm vfat
is a module and not a File System Type by running modinfo vfat
.
This worked for my GIT version 1.8.4:
You can use strftime
to convert datetimes to any character format:
> t <- strftime(times, format="%H:%M:%S")
> t
[1] "02:06:49" "03:37:07" "00:22:45" "00:24:35" "03:09:57" "03:10:41"
[7] "05:05:57" "07:39:39" "06:47:56" "07:56:36"
But that doesn't help very much, since you want to plot your data. One workaround is to strip the date element from your times, and then to add an identical date to all of your times:
> xx <- as.POSIXct(t, format="%H:%M:%S")
> xx
[1] "2012-03-23 02:06:49 GMT" "2012-03-23 03:37:07 GMT"
[3] "2012-03-23 00:22:45 GMT" "2012-03-23 00:24:35 GMT"
[5] "2012-03-23 03:09:57 GMT" "2012-03-23 03:10:41 GMT"
[7] "2012-03-23 05:05:57 GMT" "2012-03-23 07:39:39 GMT"
[9] "2012-03-23 06:47:56 GMT" "2012-03-23 07:56:36 GMT"
Now you can use these datetime
objects in your plot:
plot(xx, rnorm(length(xx)), xlab="Time", ylab="Random value")
For more help, see ?DateTimeClasses
If I put stdlib.h or stdio.h, I don't have to link those but I have to link when I compile:
stdlib.h
, stdio.h
are the header files. You include them for your convenience. They only forecast what symbols will become available if you link in the proper library. The implementations are in the library files, that's where the functions really live.
Including math.h
is only the first step to gaining access to all the math functions.
Also, you don't have to link against libm
if you don't use it's functions, even if you do a #include <math.h>
which is only an informational step for you, for the compiler about the symbols.
stdlib.h
, stdio.h
refer to functions available in libc
, which happens to be always linked in so that the user doesn't have to do it himself.
If the variable ax.xaxis._autolabelpos = True, matplotlib sets the label position in function _update_label_position in axis.py according to (some excerpts):
bboxes, bboxes2 = self._get_tick_bboxes(ticks_to_draw, renderer)
bbox = mtransforms.Bbox.union(bboxes)
bottom = bbox.y0
x, y = self.label.get_position()
self.label.set_position((x, bottom - self.labelpad * self.figure.dpi / 72.0))
You can set the label position independently of the ticks by using:
ax.xaxis.set_label_coords(x0, y0)
that sets _autolabelpos to False or as mentioned above by changing the labelpad parameter.
In My case I had to Upgrade the SQL Server since evaluation licence had been expired.
I tried most of the previous answers, but it didn’t work for my machine, Ubuntu 18.04 (Bionic Beaver), but what worked for me was this.
First: check your PHP version
$ php -version
Second: add your PHP version to the command. Mine was:
$ sudo apt-get install php7.2-curl
Lastly, restart the Apache server:
sudo service apache2 restart
Although most persons claimed that it not necessary to restart Apache :)
As of v 2.5, NUnit has the following method-level Assert
s for testing exceptions:
Assert.Throws, which will test for an exact exception type:
Assert.Throws<NullReferenceException>(() => someNullObject.ToString());
And Assert.Catch
, which will test for an exception of a given type, or an exception type derived from this type:
Assert.Catch<Exception>(() => someNullObject.ToString());
As an aside, when debugging unit tests which throw exceptions, you may want to prevent VS from breaking on the exception.
Edit
Just to give an example of Matthew's comment below, the return of the generic Assert.Throws
and Assert.Catch
is the exception with the type of the exception, which you can then examine for further inspection:
// The type of ex is that of the generic type parameter (SqlException)
var ex = Assert.Throws<SqlException>(() => MethodWhichDeadlocks());
Assert.AreEqual(1205, ex.Number);
you can use any prefix or postfix name for modal. but you need to make sure that's should use everywhere with same prefix/postfix name.
body .modal-nk {
/* new custom width */
width: 560px;
/* must be half of the width, minus scrollbar on the left (30px) */
margin-left: -280px;
}
or
body .nk-modal {
/* new custom width */
width: 560px;
/* must be half of the width, minus scrollbar on the left (30px) */
margin-left: -280px;
}
or just study /etc/groups (ok this does probably not work if it uses pam with ldap)
I had two significant errors in my program. From the other answers, I learned in a single java program, one can not declare two classes as "public". So I changed the access specifier, but got another error as added to my question as "EDIT" that "Selection does not contain a main type". Finally I observed I forgot to add "String args[]" part in my main method. That's why the code was not working. After rectification, it worked as expected.
Building on Jeremy Bader and David West's excellent answers, a Swift 3 extension:
extension String {
func withBoldText(boldPartsOfString: Array<NSString>, font: UIFont!, boldFont: UIFont!) -> NSAttributedString {
let nonBoldFontAttribute = [NSFontAttributeName:font!]
let boldFontAttribute = [NSFontAttributeName:boldFont!]
let boldString = NSMutableAttributedString(string: self as String, attributes:nonBoldFontAttribute)
for i in 0 ..< boldPartsOfString.count {
boldString.addAttributes(boldFontAttribute, range: (self as NSString).range(of: boldPartsOfString[i] as String))
}
return boldString
}
}
Usage:
let label = UILabel()
let font = UIFont(name: "AvenirNext-Italic", size: 24)!
let boldFont = UIFont(name: "AvenirNext-BoldItalic", size: 24)!
label.attributedText = "Make sure your face is\nbrightly and evenly lit".withBoldText(
boldPartsOfString: ["brightly", "evenly"], font: font, boldFont: boldFont)
//get the value of a gridview
public string getUpdatingGridviewValue(GridView gridviewEntry, string fieldEntry)
{//start getGridviewValue
//scan gridview for cell value
string result = Convert.ToString(functionsOther.getCurrentTime());
for(int i = 0; i < gridviewEntry.HeaderRow.Cells.Count; i++)
{//start i for
if(gridviewEntry.HeaderRow.Cells[i].Text == fieldEntry)
{//start check field match
result = gridviewEntry.Rows[rowUpdateIndex].Cells[i].Text;
break;
}//end check field match
}//end i for
//return
return result;
}//end getGridviewValue
If you are uploading your files through GIT from your local machine then you can use the same command you are using in your local machine while you are connected to your live server using BASH or something like.You can use this as like you use locally.
php artisan cache:clear
php artisan route:cache
It should work.
You can use removeItemFromArrayByPath function which includes some lodash functions and splice
/**
* Remove item from array by given path and index
*
* Note: this function mutates array.
*
* @param {Object|Array} data (object or array)
* @param {Array|String} The array path to remove given index
* @param {Number} index to be removed from given data by path
*
* @returns {undefined}
*/
const removeItemFromArrayByPath = (data, arrayPath, indexToRemove) => {
const array = _.get(data, arrayPath, []);
if (!_.isEmpty(array)) {
array.splice(indexToRemove, 1);
}
};
You can check the examples here: https://codepen.io/fatihturgut/pen/NWbxLNv
With ggplot2 version 2.1.0 it is
+ scale_y_continuous(labels = scales::percent)
The full list of commands is available at http://your-jenkins/cli
The command for a clean shutdown is http://your-jenkins/safe-shutdown
You may also want to use http://your-jenkins/safe-restart
This is the case you are using Julia:
The analogue of IPython's %matplotlib in Julia is to use the PyPlot package, which gives a Julia interface to Matplotlib including inline plots in IJulia notebooks. (The equivalent of numpy is already loaded by default in Julia.) Given PyPlot, the analogue of %matplotlib inline is using PyPlot, since PyPlot defaults to inline plots in IJulia.
it makes the assignment visible to subprocesses.
$ foo=bar
$ bash -c 'echo $foo'
$ export foo
$ bash -c 'echo $foo'
bar
Chart.js is quite useful, supporting numerous other types of charts as well.
It can be used both with jQuery and without.
It's possible without jQuery too! :)
let countries = ['United States', 'Canada', 'Argentina', 'Armenia', 'Aruba'];_x000D_
_x000D_
// The <ul> that we will add <li> elements to:_x000D_
let myList = document.querySelector('ul.mylist');_x000D_
_x000D_
// Loop over the Array of country names:_x000D_
countries.forEach(function(value, index, array) {_x000D_
// Create an <li> element:_x000D_
let li = document.createElement('li');_x000D_
_x000D_
// Give it the desired classes & attributes:_x000D_
li.classList.add('ui-menu-item');_x000D_
li.setAttribute('role', 'menuitem');_x000D_
_x000D_
// Now create an <a> element:_x000D_
let a = document.createElement('a');_x000D_
_x000D_
// Give it the desired classes & attributes:_x000D_
a.classList.add('ui-all');_x000D_
a.tabIndex = -1;_x000D_
a.innerText = value; // <--- the country name from our Array_x000D_
a.href = "#"_x000D_
_x000D_
// Now add the <a> to the <li>, and add the <li> to the <ul>_x000D_
li.appendChild(a);_x000D_
myList.appendChild(li);_x000D_
});
_x000D_
<ul class="mylist"></ul>
_x000D_
If you are using Angular Reactive Forms you can create a file with a function - a validator. This will not allow only spaces to be entered.
import { AbstractControl } from '@angular/forms';
export function removeSpaces(control: AbstractControl) {
if (control && control.value && !control.value.replace(/\s/g, '').length) {
control.setValue('');
}
return null;
}
and then in your component typescript file use the validator like this for example.
this.formGroup = this.fb.group({
name: [null, [Validators.required, removeSpaces]]
});
See the isDigit(char ch)
method:
https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Character.html
and pass it to the first character of the String using the String.charAt()
method.
Character.isDigit(myString.charAt(0));
Your css is almost correct. You are just missing display: block;
in image css.
Also one typo in your id. It should be <div id="ImageContainer">
img.Image { max-width: 100%; display: block; }_x000D_
div#ImageContainer { width: 600px; }
_x000D_
<div id="ImageContainer">_x000D_
<img src="http://placehold.it/1000x600" class="Image">_x000D_
</div>
_x000D_
This works for me. You can override onUserLeaveHint method https://www.tutorialspoint.com/detect-home-button-press-in-android
@Override
protected void onUserLeaveHint() {
//
super.onUserLeaveHint();
}
You can use this:
$("#id").click(function()
{
$(this).data('clicked', true);
});
Now check it via an if statement:
if($("#id").data('clicked'))
{
// code here
}
For more information you can visit the jQuery website on the .data() function.
I would like to make a addon for tiago's answer:
Suppose you're hiding element using ng-show
and adding a required
attribute on the same:
<div ng-show="false">
<input required name="something" ng-model="name"/>
</div>
will throw an error something like :
An invalid form control with name='' is not focusable
This is because you just cannot impose required
validation on hidden
elements. Using ng-required
makes it easier to conditionally apply required validation which is just awesome!!
public enum MyEnum {
ONE(1),
TWO(2);
private int value;
private MyEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
In short - you can define any number of parameters for the enum as long as you provide constructor arguments (and set the values to the respective fields)
As Scott noted - the official enum documentation gives you the answer. Always start from the official documentation of language features and constructs.
Update: For strings the only difference is that your constructor argument is String
, and you declare enums with TEST("test")
I used tableViewCell to show multiple data, after swipe () right to left on a cell it will show two buttons Approve And reject, there are two methods, the first one is ApproveFunc which takes one argument, and the another one is RejectFunc which also takes one argument.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let Approve = UITableViewRowAction(style: .normal, title: "Approve") { action, index in
self.ApproveFunc(indexPath: indexPath)
}
Approve.backgroundColor = .green
let Reject = UITableViewRowAction(style: .normal, title: "Reject") { action, index in
self.rejectFunc(indexPath: indexPath)
}
Reject.backgroundColor = .red
return [Reject, Approve]
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func ApproveFunc(indexPath: IndexPath) {
print(indexPath.row)
}
func rejectFunc(indexPath: IndexPath) {
print(indexPath.row)
}
Install PIL(Python Image Library) :
then:
from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();
Don't use more commands than necessary, leave away tail, grep and cut. You can do this with only (a simple) awk
PS: giving a block-size en print only de persentage is a bit silly ;-) So leave also away the "-B MB"
df . |awk -F'[multiple field seperators]' '$NF=="Last field must be exactly --> mounted patition" {print $(NF-number from last field)}'
in your case, use:
df . |awk -F'[ %]' '$NF=="/" {print $(NF-2)}'
output: 81
If you want to show the percent symbol, you can leave the -F'[ %]' away and your print field will move 1 field further back
df . |awk '$NF=="/" {print $(NF-1)}'
output: 81%
In your MoviesService you should import FirebaseListObservable in order to define return type FirebaseListObservable<any[]>
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
then get() method should like this-
get (): FirebaseListObservable<any[]>{
return this.db.list('/movies');
}
this get() method will return FirebaseListObervable of movies list
In your MoviesComponent should look like this
export class MoviesComponent implements OnInit {
movies: any[];
constructor(private moviesDb: MoviesService) { }
ngOnInit() {
this.moviesDb.get().subscribe((snaps) => {
this.movies = snaps;
});
}
}
Then you can easily iterate through movies without async pipe as movies[] data is not observable type, your html should be this
ul
li(*ngFor='let movie of movies')
{{ movie.title }}
if you declear movies as a
movies: FirebaseListObservable<any[]>;
then you should simply call
movies: FirebaseListObservable<any[]>;
ngOnInit() {
this.movies = this.moviesDb.get();
}
and your html should be this
ul
li(*ngFor='let movie of movies | async')
{{ movie.title }}
I fixed an error like this changing the places of the routes in routes.php, for example i had something like this:
Route::resource('Mensajes', 'MensajeriaController');
Route::get('Mensajes/modificar', 'MensajeriaController@modificarEstado');
and then I put it like this:
Route::get('Mensajes/modificar', 'MensajeriaController@modificarEstado');
Route::resource('Mensajes', 'MensajeriaController');
This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.
It depends..
SELECT x.col
FROM big_table x
WHERE x.key IN( SELECT key FROM really_big_table );
would not be relatively slow the isn't much to limit size of what the query check to see if they key is in. EXISTS would be preferable in this case.
But, depending on the DBMS's optimizer, this could be no different.
As an example of when EXISTS is better
SELECT x.col
FROM big_table x
WHERE EXISTS( SELECT key FROM really_big_table WHERE key = x.key);
AND id = very_limiting_criteria
You need to used an other worker type class an async one like gevent or tornado see this for more explanation : First explantion :
You may also want to install Eventlet or Gevent if you expect that your application code may need to pause for extended periods of time during request processing
Second one :
The default synchronous workers assume that your application is resource bound in terms of CPU and network bandwidth. Generally this means that your application shouldn’t do anything that takes an undefined amount of time. For instance, a request to the internet meets this criteria. At some point the external network will fail in such a way that clients will pile up on your servers.
If what you want is a way to turn your class into kind of a list without subclassing list
, then just make a method that returns a list:
def MyClass():
def __init__(self):
self.value1 = 1
self.value2 = 2
def get_list(self):
return [self.value1, self.value2...]
>>>print MyClass().get_list()
[1, 2...]
If you meant that print MyClass()
will print a list, just override __repr__
:
class MyClass():
def __init__(self):
self.value1 = 1
self.value2 = 2
def __repr__(self):
return repr([self.value1, self.value2])
EDIT:
I see you meant how to make objects compare. For that, you override the __cmp__
method.
class MyClass():
def __cmp__(self, other):
return cmp(self.get_list(), other.get_list())
For me, the refresh in xcode 5 prefs->accounts was doing nothing. At one point it showed me three profiles so I thought I was one refresh away, but after the next refresh it went back to just one profile, so I abandoned this method.
If anyone gets this far and is still struggling, here's what I did:
When I did this, everything synced up perfectly. It even told me what it was downloading each step of the way like good software does. After the sync completed, I closed xcode 4.6.2, re-opened xcode 5 and went to preferences->accounts and voila, all of my profiles are now available in xocde 5.
I don't think you can round it like that in a single command. Try
ArrayList<BigDecimal> list = new ArrayList<BigDecimal>();
list.add(new BigDecimal("100.12"));
list.add(new BigDecimal("100.44"));
list.add(new BigDecimal("100.50"));
list.add(new BigDecimal("100.75"));
for (BigDecimal bd : list){
System.out.println(bd+" -> "+bd.setScale(0,RoundingMode.HALF_UP).setScale(2));
}
Output:
100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00
I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.
>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')
A little late to the party, but I think many are struggling with this...
I've been searching for this as well. And to get your method/action running async without waiting or blocking the thread, you'll need to queue it via the SynchronizationContext
, so I came up with this solution:
I've made a helper-class for it.
public static class ASyncHelper
{
public static void RunAsync(Func<Task> func)
{
var context = SynchronizationContext.Current;
// you don't want to run it on a threadpool. So if it is null,
// you're not on a UI thread.
if (context == null)
throw new NotSupportedException(
"The current thread doesn't have a SynchronizationContext");
// post an Action as async and await the function in it.
context.Post(new SendOrPostCallback(async state => await func()), null);
}
public static void RunAsync<T>(Func<T, Task> func, T argument)
{
var context = SynchronizationContext.Current;
// you don't want to run it on a threadpool. So if it is null,
// you're not on a UI thread.
if (context == null)
throw new NotSupportedException(
"The current thread doesn't have a SynchronizationContext");
// post an Action as async and await the function in it.
context.Post(new SendOrPostCallback(async state => await func((T)state)), argument);
}
}
Usage/Example:
public partial class Form1 : Form
{
private async Task Initialize()
{
// replace code here...
await Task.Delay(1000);
}
private async Task Run(string myString)
{
// replace code here...
await Task.Delay(1000);
}
public Form1()
{
InitializeComponent();
// you don't have to await nothing.. (the thread must be running)
ASyncHelper.RunAsync(Initialize);
ASyncHelper.RunAsync(Run, "test");
// In your case
ASyncHelper.RunAsync(getWritings);
}
}
This works for Windows.Forms and WPF
Run this program from commandline:
// File: Main.java
public class Main {
public static void main(String[] args) {
System.out.println(System.getProperty("java.home"));
}
}
$ javac Main.java
$ java Main
Bootstrap styling for jQuery UI Autocomplete
.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
display: none;
min-width: 160px;
padding: 4px 0;
margin: 0 0 10px 25px;
list-style: none;
background-color: #ffffff;
border-color: #ccc;
border-color: rgba(0, 0, 0, 0.2);
border-style: solid;
border-width: 1px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
*border-right-width: 2px;
*border-bottom-width: 2px;
}
.ui-menu-item > a.ui-corner-all {
display: block;
padding: 3px 15px;
clear: both;
font-weight: normal;
line-height: 18px;
color: #555555;
white-space: nowrap;
text-decoration: none;
}
.ui-state-hover, .ui-state-active {
color: #ffffff;
text-decoration: none;
background-color: #0088cc;
border-radius: 0px;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
background-image: none;
}
I wrote this a long time ago (from years 1985-1992, with just a few tweaks since then), and just copy and paste the bits needed into each project.
You must call cfmakeraw
on a tty
obtained from tcgetattr
. You cannot zero-out a struct termios
, configure it, and then set the tty
with tcsetattr
. If you use the zero-out method, then you will experience unexplained intermittent failures, especially on the BSDs and OS X. "Unexplained intermittent failures" include hanging in read(3)
.
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
int
set_interface_attribs (int fd, int speed, int parity)
{
struct termios tty;
if (tcgetattr (fd, &tty) != 0)
{
error_message ("error %d from tcgetattr", errno);
return -1;
}
cfsetospeed (&tty, speed);
cfsetispeed (&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
// disable IGNBRK for mismatched speed tests; otherwise receive break
// as \000 chars
tty.c_iflag &= ~IGNBRK; // disable break processing
tty.c_lflag = 0; // no signaling chars, no echo,
// no canonical processing
tty.c_oflag = 0; // no remapping, no delays
tty.c_cc[VMIN] = 0; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
// enable reading
tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
if (tcsetattr (fd, TCSANOW, &tty) != 0)
{
error_message ("error %d from tcsetattr", errno);
return -1;
}
return 0;
}
void
set_blocking (int fd, int should_block)
{
struct termios tty;
memset (&tty, 0, sizeof tty);
if (tcgetattr (fd, &tty) != 0)
{
error_message ("error %d from tggetattr", errno);
return;
}
tty.c_cc[VMIN] = should_block ? 1 : 0;
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
if (tcsetattr (fd, TCSANOW, &tty) != 0)
error_message ("error %d setting term attributes", errno);
}
...
char *portname = "/dev/ttyUSB1"
...
int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
error_message ("error %d opening %s: %s", errno, portname, strerror (errno));
return;
}
set_interface_attribs (fd, B115200, 0); // set speed to 115,200 bps, 8n1 (no parity)
set_blocking (fd, 0); // set no blocking
write (fd, "hello!\n", 7); // send 7 character greeting
usleep ((7 + 25) * 100); // sleep enough to transmit the 7 plus
// receive 25: approx 100 uS per char transmit
char buf [100];
int n = read (fd, buf, sizeof buf); // read up to 100 characters if ready to read
The values for speed are B115200
, B230400
, B9600
, B19200
, B38400
, B57600
, B1200
, B2400
, B4800
, etc. The values for parity are 0
(meaning no parity), PARENB|PARODD
(enable parity and use odd), PARENB
(enable parity and use even), PARENB|PARODD|CMSPAR
(mark parity), and PARENB|CMSPAR
(space parity).
"Blocking" sets whether a read()
on the port waits for the specified number of characters to arrive. Setting no blocking means that a read()
returns however many characters are available without waiting for more, up to the buffer limit.
Addendum:
CMSPAR
is needed only for choosing mark and space parity, which is uncommon. For most applications, it can be omitted. My header file /usr/include/bits/termios.h
enables definition of CMSPAR
only if the preprocessor symbol __USE_MISC
is defined. That definition occurs (in features.h
) with
#if defined _BSD_SOURCE || defined _SVID_SOURCE
#define __USE_MISC 1
#endif
The introductory comments of <features.h>
says:
/* These are defined by the user (or the compiler)
to specify the desired environment:
...
_BSD_SOURCE ISO C, POSIX, and 4.3BSD things.
_SVID_SOURCE ISO C, POSIX, and SVID things.
...
*/
Somewhat related, but I was also looking for a native excel VBA solution since advanced data structures (Dictionaries, etc.) aren't working in my environment. The following implements sorting via a binary tree in VBA:
"0|2|3|4|9"
) which can then be split.I used it for returning a raw sorted enumeration of rows selected for an arbitrarily selected range
Private Enum LeafType: tEMPTY: tTree: tValue: End Enum
Private Left As Variant, Right As Variant, Center As Variant
Private LeftType As LeafType, RightType As LeafType, CenterType As LeafType
Public Sub Add(x As Variant)
If CenterType = tEMPTY Then
Center = x
CenterType = tValue
ElseIf x > Center Then
If RightType = tEMPTY Then
Right = x
RightType = tValue
ElseIf RightType = tTree Then
Right.Add x
ElseIf x <> Right Then
curLeaf = Right
Set Right = New TreeList
Right.Add curLeaf
Right.Add x
RightType = tTree
End If
ElseIf x < Center Then
If LeftType = tEMPTY Then
Left = x
LeftType = tValue
ElseIf LeftType = tTree Then
Left.Add x
ElseIf x <> Left Then
curLeaf = Left
Set Left = New TreeList
Left.Add curLeaf
Left.Add x
LeftType = tTree
End If
End If
End Sub
Public Function GetList$()
Const sep$ = "|"
If LeftType = tValue Then
LeftList$ = Left & sep
ElseIf LeftType = tTree Then
LeftList = Left.GetList & sep
End If
If RightType = tValue Then
RightList$ = sep & Right
ElseIf RightType = tTree Then
RightList = sep & Right.GetList
End If
GetList = LeftList & Center & RightList
End Function
'Sample code
Dim Tree As new TreeList
Tree.Add("0")
Tree.Add("2")
Tree.Add("2")
Tree.Add("-1")
Debug.Print Tree.GetList() 'prints "-1|0|2"
sortedList = Split(Tree.GetList(),"|")
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser()
like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri
in onActivityResult()
like so:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath()
method in my FileUtils.java
is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
var ListByOwner = list.GroupBy(l => l.Owner)
.Select(lg =>
new {
Owner = lg.Key,
Boxes = lg.Count(),
TotalWeight = lg.Sum(w => w.Weight),
TotalVolume = lg.Sum(w => w.Volume)
});
Maybe the container I've created is useful as well https://github.com/qoomon/docker-host
You can simply use container name dns to access host system e.g. curl http://dockerhost:9200, so no need to hassle with any IP address.
The general idea is to add, commit and push your files to the GitHub repo.
First you need to clone your GitHub repo.
Then, you would git add all the files from your other folder: one trick is to specify an alternate working tree when git add'ing your files.
git --work-tree=yourSrcFolder add .
(done from the root directory of your cloned Git repo, then git commit -m "a msg"
, and git push origin master
)
That way, you keep separate your initial source folder, from your Git working tree.
Note that since early December 2012, you can create new files directly from GitHub:
ProTip™: You can pre-fill the filename field using just the URL.
Typing?filename=yournewfile.txt
at the end of the URL will pre-fill the filename field with the nameyournewfile.txt
.
Firstly, the Instagram API endpoint "tags" required OAuth authentication.
You can query results for a particular hashtag (snowy in this case) using the following url
It is rate limited to 5000 (X-Ratelimit-Limit:5000) per hour
https://api.instagram.com/v1/tags/snowy/media/recent
Sample response
{
"pagination": {
"next_max_tag_id": "1370433362010",
"deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id": "1370433362010",
"next_min_id": "1370443976800",
"min_tag_id": "1370443976800",
"next_url": "https://api.instagram.com/v1/tags/snowy/media/recent?access_token=40480112.1fb234f.4866541998fd4656a2e2e2beaa5c4bb1&max_tag_id=1370433362010"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"snowy"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": null,
"created_time": "1370418343",
"link": "http://instagram.com/p/aK1yrGRi3l/",
"likes": {
"count": 1,
"data": [
{
"username": "iri92lol",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"id": "404174490",
"full_name": "Iri"
}
]
},
"images": {
"low_resolution": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_7.jpg",
"width": 612,
"height": 612
}
},
"users_in_photo": [],
"caption": {
"created_time": "1370418353",
"text": "#snowy",
"from": {
"username": "iri92lol",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"id": "404174490",
"full_name": "Iri"
},
"id": "471425773832908504"
},
"user_has_liked": false,
"id": "471425689728724453_404174490",
"user": {
"username": "iri92lol",
"website": "",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"full_name": "Iri",
"bio": "",
"id": "404174490"
}
}
}
You can play around here :
You need to use "Authentication" as OAuth 2 and will be prompted to signin via Instagram. Post that you might have to reneter the "tag-name" in "Template" section.
All the pagination related data is available in the "pagination" parameter in the response and use it's "next_url" to query for the next set of result.
Both are shallow copies. CopyTo method is not a deep copy. Check the following code :
public class TestClass1
{
public string a = "test1";
}
public static void ArrayCopyClone()
{
TestClass1 tc1 = new TestClass1();
TestClass1 tc2 = new TestClass1();
TestClass1[] arrtest1 = { tc1, tc2 };
TestClass1[] arrtest2 = new TestClass1[arrtest1.Length];
TestClass1[] arrtest3 = new TestClass1[arrtest1.Length];
arrtest1.CopyTo(arrtest2, 0);
arrtest3 = arrtest1.Clone() as TestClass1[];
Console.WriteLine(arrtest1[0].a);
Console.WriteLine(arrtest2[0].a);
Console.WriteLine(arrtest3[0].a);
arrtest1[0].a = "new";
Console.WriteLine(arrtest1[0].a);
Console.WriteLine(arrtest2[0].a);
Console.WriteLine(arrtest3[0].a);
}
/* Output is
test1
test1
test1
new
new
new */
Check this
UPDATE some_table SET some_field = REPLACE("Column Name/String", 'Search String', 'Replace String')
Eg with sample string:
UPDATE some_table SET some_field = REPLACE("this is test string", 'test', 'sample')
EG with Column/Field Name:
UPDATE some_table SET some_field = REPLACE(columnName, 'test', 'sample')
You need to delete your old db folder and recreate new one. It will resolve your issue.
So first of all, pandas updates using the index. When an update command does not update anything, check both left-hand side and right-hand side. If you don't update the indices to follow your identification logic, you can do something along the lines of
>>> df.loc[df.filename == 'test2.dat', 'n'] = df2[df2.filename == 'test2.dat'].loc[0]['n']
>>> df
Out[331]:
filename m n
0 test0.dat 12 None
1 test2.dat 13 16
If you want to do this for the whole table, I suggest a method I believe is superior to the previously mentioned ones: since your identifier is filename
, set filename
as your index, and then use update()
as you wanted to. Both merge
and the apply()
approach contain unnecessary overhead:
>>> df.set_index('filename', inplace=True)
>>> df2.set_index('filename', inplace=True)
>>> df.update(df2)
>>> df
Out[292]:
m n
filename
test0.dat 12 None
test2.dat 13 16
I do something like this :
all_lines = ""
ARGV.each do |line|
all_lines << line + "\n"
end
puts all_lines
In SQL Server 2016 you can use new DIE statements.
ALTER TABLE Table_name DROP COLUMN IF EXISTS Column_name
The above query is re-runnable it drops
the column only if it exists
in the table else it will not throw error.
Instead of using big IF
wrappers to check the existence of column
before dropping it you can just run the above DDL
statement
The best way to process command line arguments is the argparse
module.
Use raw_input()
to get user input. If you import the readline module
your users will have line editing and history.