If what you need is UPDATE from SELECT statement you can do something like this:
UPDATE suppliers
SET city = (SELECT customers.city FROM customers
WHERE customers.customer_name = suppliers.supplier_name)
The question is quite old, but what about:
- hosts: 'localhost'
tasks:
- debug:
msg: "{{ ( a | default({})).get('nested', {}).get('var','bar') }}"
It looks less cumbersome to me...
If it works on your localhost but not on your web host:
Some hosting sites block certain outbound SMTP ports. Commenting out the line $mail->IsSMTP();
as noted in the accepted answer may make it work, but it is simply disabling your SMTP configuration, and using the hosting site's email config.
If you are using GoDaddy, there is no way to send mail using a different SMTP. I was using SiteGround, and found that they were allowing SMTP access from ports 25 and 465 only, with an SSL encryption type, so I would look up documentation for your host and go from there.
i was also facing the same problem and tried almost all the things but finally i restarted my server and i found everything started working fine..i don't know how.....i think it was some server side problem that's why my PHP CODE was not giving any error.
They've changed it in JUnit 5 (expected: InvalidArgumentException, actual: invoked method) and code looks like this one:
@Test
public void wrongInput() {
Throwable exception = assertThrows(InvalidArgumentException.class,
()->{objectName.yourMethod("WRONG");} );
}
I use
<td nowrap="nowrap">
_x000D_
to prevent wrap Reference: https://www.w3schools.com/tags/att_td_nowrap.asp
use /// to begin each line of the comment and have the comment contain the appropriate xml for the meta data reader.
///<summary>
/// this method says hello
///</summary>
public void SayHello();
Although personally, I believe that these comments are usually misguided, unless you are developing classes where the code cannot be read by its consumers.
Few years later, I've built this library to do drop files into any HTML element.
You can use it like
const Droppable = require('droppable');
const droppable = new Droppable({
element: document.querySelector('#my-droppable-element')
})
droppable.onFilesDropped((files) => {
console.log('Files were dropped:', files);
});
// Clean up when you're done!
droppable.destroy();
Something like this.
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
EDIT
Working demo.
The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.
Actually I don't think that there is a lot in common between them. Some algorithm use heuristics in their logic (often to make fewer calculations or get faster results). Usually heuristics are used in the so called greedy algorithms.
Heuristics is some "knowledge" that we assume is good to use in order to get the best choice in our algorithm (when a choice should be taken). For example ... a heuristics in chess could be (always take the opponents' queen if you can, since you know this is the stronger figure). Heuristics do not guarantee you that will lead you to the correct answer, but (if the assumptions is correct) often get answer which are close to the best in much shorter time.
Although Bootstrap CDN restored glyphicons to bootstrap.min.css, Bootstrap CDN's Bootswatch css files doesn't include glyphicons.
For example Amelia theme: http://bootswatch.com/amelia/
Default Amelia has glyphicons in this file: http://bootswatch.com/amelia/bootstrap.min.css
But Bootstrap CDN's css file doesn't include glyphicons: http://netdna.bootstrapcdn.com/bootswatch/3.0.0/amelia/bootstrap.min.css
So as @edsioufi mentioned, you should include you should include glphicons css, if you use Bootswatch files from the bootstrap CDN. File: http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css
The closest equivalent of C++ std::map<>
(a tree internally) is C# OrderedDictionary<>
(a tree internally), while C# OrderedDictionary<>
is missing some very important methods from C++ std::map<>
, namely: std::map::find
, std::map::lower_bound
, std::map::upper_bound
, std::map::equal_range
, and std::map
iterators
, which are basically the backbone for the previous 4 methods.
Why those 4 methods are important? Because it gives us the ability to locate the "whereabouts" of a given key, in addition to only being able to check if a key exists, or the SortedDictionary is guaranteed to be ordered.
What is "whereabouts" of a key in a std::map
? The key doesn't necessarily have to exist in the collection, we want to know the location the key might be at, usually between two iterators pointing to two adjacent existing keys respectively in the collection, so we can operate on the range the key falls into in a O(logN)
complexity. Without such 4 methods (with iterators), one has to do an O(N)
iteration through the collection every time a range is queried against a key.
You could achieve this with a simple for
loop:
var min = 12,
max = 100,
select = document.getElementById('selectElementId');
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
JS Perf comparison of both mine and Sime Vidas' answer, run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.
Edited in response to comment from OP:
[How] do [I] apply this to more than one element?
function populateSelect(target, min, max){
if (!target){
return false;
}
else {
var min = min || 0,
max = max || min + 100;
select = document.getElementById(target);
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
}
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);
// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');
// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);
And, finally (after quite a delay...), an approach extending the prototype of the HTMLSelectElement
in order to chain the populate()
function, as a method, to the DOM node:
HTMLSelectElement.prototype.populate = function (opts) {
var settings = {};
settings.min = 0;
settings.max = settings.min + 100;
for (var userOpt in opts) {
if (opts.hasOwnProperty(userOpt)) {
settings[userOpt] = opts[userOpt];
}
}
for (var i = settings.min; i <= settings.max; i++) {
this.appendChild(new Option(i, i));
}
};
document.getElementById('selectElementId').populate({
'min': 12,
'max': 40
});
References:
This code will work on all android versions:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Automatic popping up keyboard on start Activity
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
or
//avoid automatically appear android keyboard when activity start
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
remove the ios::binary
from your modes in your ofstream and use studentPassword.c_str()
instead of (char *)&studentPassword
in your write.write()
You can use
x = Map(json.loads(response))
x.__class__ = MyClass
where
class Map(dict):
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
self[k] = v
if isinstance(v, dict):
self[k] = Map(v)
if kwargs:
# for python 3 use kwargs.items()
for k, v in kwargs.iteritems():
self[k] = v
if isinstance(v, dict):
self[k] = Map(v)
def __getattr__(self, attr):
return self.get(attr)
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __setitem__(self, key, value):
super(Map, self).__setitem__(key, value)
self.__dict__.update({key: value})
def __delattr__(self, item):
self.__delitem__(item)
def __delitem__(self, key):
super(Map, self).__delitem__(key)
del self.__dict__[key]
For a generic, future-proof solution.
You can use font awesome utf cheatsheet
<input type="submit" class="btn btn-success" value=" Login"/>
here is the link for the cheatsheet http://fortawesome.github.io/Font-Awesome/cheatsheet/
You must use some of the C # conversion systems:
string to boolean: True to true
string str = "True";
bool mybool = System.Convert.ToBoolean(str);
boolean to string: true to True
bool mybool = true;
string str = System.Convert.ToString(mybool);
//or
string str = mybool.ToString();
bool.Parse
expects one parameter which in this case is str, even .
Convert.ToBoolean
expects one parameter.
bool.TryParse
expects two parameters, one entry (str) and one out (result).
If TryParse
is true, then the conversion was correct, otherwise an error occurred
string str = "True";
bool MyBool = bool.Parse(str);
//Or
string str = "True";
if(bool.TryParse(str, out bool result))
{
//Correct conversion
}
else
{
//Incorrect, an error has occurred
}
Old question I know. You don't need to convert it. See this function:
function getType( oObj )
{
if( typeof oObj === "object" )
{
return ( oObj === null )?'Null':
// Check if it is an alien object, for example created as {world:'hello'}
( typeof oObj.constructor !== "function" )?'Object':
// else return object name (string)
oObj.constructor.name;
}
// Test simple types (not constructed types)
return ( typeof oObj === "boolean")?'Boolean':
( typeof oObj === "number")?'Number':
( typeof oObj === "string")?'String':
( typeof oObj === "function")?'Function':false;
};
Examples:
function MyObject() {}; // Just for example
console.log( getType( new String( "hello ") )); // String
console.log( getType( new Function() ); // Function
console.log( getType( {} )); // Object
console.log( getType( [] )); // Array
console.log( getType( new MyObject() )); // MyObject
var bTest = false,
uAny, // Is undefined
fTest function() {};
// Non constructed standard types
console.log( getType( bTest )); // Boolean
console.log( getType( 1.00 )); // Number
console.log( getType( 2000 )); // Number
console.log( getType( 'hello' )); // String
console.log( getType( "hello" )); // String
console.log( getType( fTest )); // Function
console.log( getType( uAny )); // false, cannot produce
// a string
Low cost and simple.
No, with eval
is not safe, you can use JSON parser that is much safer: var myObject = JSON.parse(data);
For this use the lib https://github.com/douglascrockford/JSON-js
Take a look at OAuth 2.0 playground.You will get an overview of the protocol.It is basically an environment(like any app) that shows you the steps involved in the protocol.
This will return the string only if the condition is true.
public String myMethod()
{
if(condition)
{
return x;
}
else
return "";
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:titleTextColor="@color/white"
android:background="@color/green" />
Make sure that each element value in the connection string being supplied is correct. In my case, I was getting the same error because the name of the catalog (database name) specified in the connection string was incorrect.
You are using POST method, but are you providing an array of data? E.g.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
Use:
php -i
command or add:
phpinfo();
to get the location of configuration file.
Update these variables according to your need and server
max_input_time = 24000
max_execution_time = 24000
upload_max_filesize = 12000M
post_max_size = 24000M
memory_limit = 12000M
On Linux you will need to restart nginx / apache and phpfpm service so the new ini settings are loaded. On xampp, ammps you can restart these from control panel that comes with such applications.
In my case, it's because I need only a single %s
, i missing values input.
AngularJS provides a simple and concise way to associate routes with controllers and templates using a $routeProvider
object. While recently updating an application to the latest release (1.2 RC1 at the current time) I realized that $routeProvider
isn’t available in the standard angular.js script any longer.
After reading through the change log I realized that routing is now a separate module (a great move I think) as well as animation and a few others. As a result, standard module definitions and config code like the following won’t work any longer if you’re moving to the 1.2 (or future) release:
var app = angular.module('customersApp', []);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
controller: 'customersController',
templateUrl: '/app/views/customers.html'
});
});
How do you fix it?
Simply add angular-route.js in addition to angular.js to your page (grab a version of angular-route.js here – keep in mind it’s currently a release candidate version which will be updated) and change the module definition to look like the following:
var app = angular.module('customersApp', ['ngRoute']);
If you’re using animations you’ll need angular-animation.js and also need to reference the appropriate module:
var app = angular.module('customersApp', ['ngRoute', 'ngAnimate']);
Your Code can be as follows:
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/controllerone', {
controller: 'friendDetails',
templateUrl: 'controller3.html'
}, {
controller: 'friendsName',
templateUrl: 'controller3.html'
}
)
.when('/controllerTwo', {
controller: 'simpleControoller',
templateUrl: 'views.html'
})
.when('/controllerThree', {
controller: 'simpleControoller',
templateUrl: 'view2.html'
})
.otherwise({
redirectTo: '/'
});
});
I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.
What I finally end up doing was replacing the single quote '
with it code '
using a regex after the stringify() method call the following way:
var productToString = JSON.stringify(productObject);
var quoteReplaced = productToString.replace(/'/g, "'");
var anchor = '<a data-product=\'' + quoteReplaced + '\' href=\'#\'>' + productObject.name + '</a>';
// Here you can use the "anchor" variable to update your DOM element.
Here are two approaches. You may want to add handling for when the array is empty.
public static void FindMax()
{
// Advantages:
// * Functional approach
// * Compact code
// Cons:
// * We are indexing into the array twice at each step
// * The Range and IEnumerable add a bit of overhead
// * Many people will find this code harder to understand
int[] array = { 1, 5, 2, 7 };
int maxIndex = Enumerable.Range(0, array.Length).Aggregate((max, i) => array[max] > array[i] ? max : i);
int maxInt = array[maxIndex];
Console.WriteLine($"Maximum int {maxInt} is found at index {maxIndex}");
}
public static void FindMax2()
{
// Advantages:
// * Near-optimal performance
int[] array = { 1, 5, 2, 7 };
int maxIndex = -1;
int maxInt = Int32.MinValue;
// Modern C# compilers optimize the case where we put array.Length in the condition
for (int i = 0; i < array.Length; i++)
{
int value = array[i];
if (value > maxInt)
{
maxInt = value;
maxIndex = i;
}
}
Console.WriteLine($"Maximum int {maxInt} is found at index {maxIndex}");
}
Based on official documentation https://developer.android.com/studio/command-line/variables.html you should change ANDROID_AVD_HOME environment var:
Emulator Environment Variables
By default, the emulator stores configuration files under $HOME/.android/ and AVD data under $HOME/.android/avd/. You can override the defaults by setting the following environment variables. The emulator -avd command searches the avd directory in the order of the values in $ANDROID_AVD_HOME, $ANDROID_SDK_HOME/.android/avd/, and $HOME/.android/avd/. For emulator environment variable help, type emulator -help-environment at the command line. For information about emulator command-line options, see Control the Emulator from the Command Line.
- ANDROID_EMULATOR_HOME: Sets the path to the user-specific emulator configuration directory. The default location is
$ANDROID_SDK_HOME/.android/.- ANDROID_AVD_HOME: Sets the path to the directory that contains all AVD-specific files, which mostly consist of very large disk images. The default location is $ANDROID_EMULATOR_HOME/avd/. You might want to specify a new location if the default location is low on disk space.
After change or set ANDROID_AVD_HOME you will have to move all content inside ~user/.android/avd/ to your new location and change path into ini file of each emulator, just replace it with your new path
None of these answers worked for me. I am using Android studio 3.4.1.
I was able to build the project but Android studio showing this error when I was going to deploy it to mobile device. It turns out it is "instant runs" fault.
Follow this answer: https://stackoverflow.com/a/42695197/3197467
I tried this, it worked for me:
declare @b2 VARBINARY(MAX)
set @b2 = 0x54006800690073002000690073002000610020007400650073007400
SELECT CONVERT(nVARCHAR(1000), @b2, 0);
In my case, I noticed mergedmanifest was missing the receiver. So I had to include:
<receiver
android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>
select *,
(select COUNT(ID) from ProductMaster where ProductMaster.CatID = CategoryMaster.ID) as coun
from CategoryMaster
Well, I still find some room to answer.
In addition to answers from Rob and Nathan, I would add that having client-side validations matters. When you are applying validations on your webforms you must follow these guidelines:
Both types of validations play important roles in their respective scope but the most strongest is the server-side. If you receive 10k users at a single point of time then you would definitely end up filtering the number of requests coming to your webserver. If you find there was a single mistake like invalid email address then they post back the form again and ask your user to correct it which will definitely eat your server resources and bandwidth. So better you apply javascript validation. If javascript is disabled then your server side validation will come to rescue and i bet only a few users might have accidentlly disable it since 99.99% of websites use javascript and its already enabled by default in all modern browsers.
Combine the answer of @mgilson and @gnibbler, I found what I need was this:
d = {"name":"interpolator",
"children":[{'name':key,"size":value} for key,value in sample.items()]}
j = json.dumps(d, indent=4)
f = open('sample.json', 'w')
print >> f, j
f.close()
It this way, I got a pretty-print json file.
The tricks print >> f, j
is found from here:
http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/
To name a few we can use redux-react-session which is having good API for session management like, initSessionService
, refreshFromLocalStorage
, checkAuth
and many other. It also provide some advanced functionality like Immutable JS
.
Alternatively we can leverage react-web-session which provides options like callback
and timeout
.
Remember load jquery before bootstrap js
I just found this :
private static bool TrySetSuppressScriptErrors(WebBrowser webBrowser, bool value)
{
FieldInfo field = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
if (field != null)
{
object axIWebBrowser2 = field.GetValue(webBrowser);
if (axIWebBrowser2 != null)
{
axIWebBrowser2.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, axIWebBrowser2, new object[] { value });
return true;
}
}
return false;
}
usage example to set webBrowser to silent : TrySetSuppressScriptErrors(webBrowser,true)
You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).
Your code could be like:
const myArray = [
{
"id":25,
"name":"Anakin Skywalker",
"createdAt":"2017-04-12T12:48:55.000Z",
"updatedAt":"2017-04-12T12:48:55.000Z"
},
{
"id":1,
"name":"Luke Skywalker",
"createdAt":"2017-04-12T11:25:03.000Z",
"updatedAt":"2017-04-12T11:25:03.000Z"
}
]
const myOrderedArray = _.sortBy(myArray, o => o.name)
Sometime it is fixed by the Padding .. if you can play with that, then, it should fix your problem
<style type=text/css>
YourbuttonByID {Padding: 20px 80px; "for example" padding-left:50px;
padding-right:30px "to fix the text in the middle
without interfering with the text itself"}
</style>
It worked for me
On windows use the name of the table in quotes:
TABLE "user";
or SELECT * FROM "user";
Open Run in your system.
Type %windir%\System32\cliconfg.exe
Click on ok button then check that the "TCP/IP Network Protocol Default Value Setup" pop-up is open.
Highlight TCP/IP under the Enabled protocols window.
Click the Properties button.
Enter the new port number, then click OK.
Place all your layouts inside a ScrollView with width and height set to fill_parent.
You could use
<a href="https://www.facebook.com/sharer/sharer.php?u=#url" target="_blank">Share</a>
Currently there is no sharing option without passing current url as a parameter. You can use an indirect way to achieve this.
Example ASP .Net code:
public partial class Sharer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var referer = Request.UrlReferrer.ToString();
if(string.IsNullOrEmpty(referer))
{
// some error logic
return;
}
Response.Clear();
Response.Redirect("https://www.facebook.com/sharer/sharer.php?u=" + HttpUtility.UrlEncode(referer));
Response.End();
}
}
Try
Date.ParseExact("9/1/2009", "M/d/yyyy", new CultureInfo("en-US"))
If you want to run a few scripts, you can use Set-executionpolicy -ExecutionPolicy Unrestricted
and then reset with Set-executionpolicy -ExecutionPolicy Default
.
Note that execution policy is only checked when you start its execution (or so it seems) and so you can run jobs in the background and reset the execution policy immediately.
# Check current setting
Get-ExecutionPolicy
# Disable policy
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
# Choose [Y]es
Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 example.com | tee ping__example.com.txt }
Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 google.com | tee ping__google.com.txt }
# Can be run immediately
Set-ExecutionPolicy -ExecutionPolicy Default
# [Y]es
Non-Americans take note! If you use Excel with "." as 1000 separator, you need to replace the "," with a "." in the formula, such as:
[>=1000]€ #.##0." K";[<=-1000]-€ #.##0." K";0
The code above will display € 62.123 as "€ 62 K".
git config --global --unset http.proxy
Seems like the symbol was Å
, but since data consists of surnames that shouldn't be public, only first letter was shown and it was done by just $lastname[0]
, which is wrong for multibyte strings and caused the whole hassle. Changed it to mb_substr($lastname, 0, 1)
- works like a charm.
You may try this:
public static void main(String[] args) {
BigDecimal a = new BigDecimal("10.12345");
System.out.println(toPrecision(a, 2));
}
private static BigDecimal toPrecision(BigDecimal dec, int precision) {
String plain = dec.movePointRight(precision).toPlainString();
return new BigDecimal(plain.substring(0, plain.indexOf("."))).movePointLeft(precision);
}
OUTPUT:
10.12
here the writer suggests this:
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException | InterruptedException e) { e.printStackTrace(); }
return false;
}
Possible Questions
read the link. its seems very good
EDIT: in my exp of using it, it's not as fast as this method:
public boolean isOnline() {
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
they are a bit different but in the functionality for just checking the connection to internet the first method may become slow due to the connection variables.
Use .val()
not attr('value')
.
thanks to everyone else for the clues.
I used this method
div.image-thumbnail
{
width: 85px;
height: 85px;
line-height: 85px;
display: inline-block;
text-align: center;
}
div.image-thumbnail img
{
vertical-align: middle;
}
Kotlin Code to read SMS :
1- Add this permission to AndroidManifest.xml :
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
2-Create a BroadCastreceiver Class :
package utils.broadcastreceivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.SmsMessage
import android.util.Log
class MySMSBroadCastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
var body = ""
val bundle = intent?.extras
val pdusArr = bundle!!.get("pdus") as Array<Any>
var messages: Array<SmsMessage?> = arrayOfNulls(pdusArr.size)
// if SMSis Long and contain more than 1 Message we'll read all of them
for (i in pdusArr.indices) {
messages[i] = SmsMessage.createFromPdu(pdusArr[i] as ByteArray)
}
var MobileNumber: String? = messages[0]?.originatingAddress
Log.i(TAG, "MobileNumber =$MobileNumber")
val bodyText = StringBuilder()
for (i in messages.indices) {
bodyText.append(messages[i]?.messageBody)
}
body = bodyText.toString()
if (body.isNotEmpty()){
// Do something, save SMS in DB or variable , static object or ....
Log.i("Inside Receiver :" , "body =$body")
}
}
}
3-Get SMS Permission if Android 6 and above:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
ActivityCompat.checkSelfPermission(context!!,
Manifest.permission.RECEIVE_SMS
) != PackageManager.PERMISSION_GRANTED
) { // Needs permission
requestPermissions(arrayOf(Manifest.permission.RECEIVE_SMS),
PERMISSIONS_REQUEST_READ_SMS
)
} else { // Permission has already been granted
}
4- Add this request code to Activity or fragment :
companion object {
const val PERMISSIONS_REQUEST_READ_SMS = 100
}
5- Override Check permisstion Request result fun :
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
PERMISSIONS_REQUEST_READ_SMS -> {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i("BroadCastReceiver", "PERMISSIONS_REQUEST_READ_SMS Granted")
} else {
// toast("Permission must be granted ")
}
}
}
}
cat > mail.txt <<EOL
To: <email>
Subject: <subject>
Content-Type: text/html
<html>
$(cat <report-table-*.html>)
This report in <a href="<url>">SVN</a>
</html>
EOL
And then:
sendmail -t < mail.txt
You entered an alphanumeric and int, blank delimited in mystr
.
You then tried to convert the first token (blank delimited) into an int
.
The first token was RS which failed to convert to int
, leaving a zero for myprice, and we all know what zero times anything yields.
When you only entered int values the second time, everything worked as you expected.
It was the spurious RS that caused your code to fail.
Horizontal centering is as easy as:
text-align: center
Vertical centering when the container is a known height:
height: 100px;
line-height: 100px;
vertical-align: middle
Vertical centering when the container isn't a known height AND you can set the image in the background:
background: url(someimage) no-repeat center center;
Caveats: this answer only allows exports color settings.
iTerm => Preferences => Profiles => Colors => Load Presets => Export
Import shall be similar.
I didn't want to make this case more difficult and made it with two iterators I have a HashMap with LastName -> FirstName. And my method should delete items with dulicate FirstName.
public static void removeTheFirstNameDuplicates(HashMap<String, String> map)
{
Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
Iterator<Map.Entry<String, String>> iter2 = map.entrySet().iterator();
while(iter.hasNext())
{
Map.Entry<String, String> pair = iter.next();
String name = pair.getValue();
int i = 0;
while(iter2.hasNext())
{
Map.Entry<String, String> nextPair = iter2.next();
if (nextPair.getValue().equals(name))
i++;
}
if (i > 1)
iter.remove();
}
}
If you are running iOS 12 you will need to do an extra step. I've been struggling to make this code work and finally found this on Apple's site: "Important To use this function in iOS 12 and later, enable the Access WiFi Information capability for your app in Xcode. When you enable this capability, Xcode automatically adds the Access WiFi Information entitlement to your entitlements file and App ID." https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo
Use this
Intent i1=new Intent(getApplicationContext(),StartUp_Page.class);
i1.setAction(Intent.ACTION_MAIN);
i1.addCategory(Intent.CATEGORY_HOME);
i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i1);
finish();
If you want to use a gentle approach via a beautiful (for terminal) interactive reporting interface I would suggest using npm-check.
It's less of a hammer and gives you more consequential knowledge of, and control over, your dependency updates.
To give you a taste of what awaits here's a screenshot (scraped from the git page for npm-check):
Just don't include the columns that you want to use the default value for in your insert statement. For instance:
INSERT INTO table1 (field1, field3) VALUES (5, 10);
...will take the default values for field2
and field4
, and assign 5 to field1
and 10 to field3
.
One way I've used it is if I have two implementations of how to do something in a class and I want to choose one at run-time without having to continually go through an if statement i.e.
class Algorithm
{
public:
Algorithm() : m_impFn( &Algorithm::implementationA ) {}
void frequentlyCalled()
{
// Avoid if ( using A ) else if ( using B ) type of thing
(this->*m_impFn)();
}
private:
void implementationA() { /*...*/ }
void implementationB() { /*...*/ }
typedef void ( Algorithm::*IMP_FN ) ();
IMP_FN m_impFn;
};
Obviously this is only practically useful if you feel the code is being hammered enough that the if statement is slowing things done eg. deep in the guts of some intensive algorithm somewhere. I still think it's more elegant than the if statement even in situations where it has no practical use but that's just my opnion.
For completeness, also look into the local storage capabilities & sessionStorage of HTML5. These are supported in the latest versions of all modern browsers, and are much easier to use and less fiddly than cookies.
http://www.w3.org/TR/2009/WD-webstorage-20091222/
https://www.w3.org/TR/webstorage/. (second edition)
Here are some sample code for setting and getting the values using sessionStorage and localStorage :
// HTML5 session Storage
sessionStorage.setItem("variableName","test");
sessionStorage.getItem("variableName");
//HTML5 local storage
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");
http://localhost:(port number of phpmyadmin)/phpmyadmin/
For example: http://localhost:8080/phpmyadmin/
It works great!
In Python, functions are first-class objects, this means: function references can be passed in inputs to other functions and/or methods, and executed from inside them.
Instances of Classes (aka Objects), can be treated as if they were functions: pass them to other methods/functions and call them. In order to achieve this, the __call__
class function has to be specialized.
def __call__(self, [args ...])
It takes as an input a variable number of arguments. Assuming x
being an instance of the Class X
, x.__call__(1, 2)
is analogous to calling x(1,2)
or the instance itself as a function.
In Python, __init__()
is properly defined as Class Constructor (as well as __del__()
is the Class Destructor). Therefore, there is a net distinction between __init__()
and __call__()
: the first builds an instance of Class up, the second makes such instance callable as a function would be without impacting the lifecycle of the object itself (i.e. __call__
does not impact the construction/destruction lifecycle) but it can modify its internal state (as shown below).
Example.
class Stuff(object):
def __init__(self, x, y, range):
super(Stuff, self).__init__()
self.x = x
self.y = y
self.range = range
def __call__(self, x, y):
self.x = x
self.y = y
print '__call__ with (%d,%d)' % (self.x, self.y)
def __del__(self):
del self.x
del self.y
del self.range
>>> s = Stuff(1, 2, 3)
>>> s.x
1
>>> s(7, 8)
__call__ with (7,8)
>>> s.x
7
Consistency is what everyone strongly suggest, the rest is upto you as long as it works.
For beginners its easy to get carried away and we name whatever we want at that time. This make sense at that point but a headache later.
foo
foobar
or foo_bar
is great.
We name our table straight forward as much as possible and only use underscore if they are two different words. studentregistration
to student_registration
like @Zbyszek says, having a simple id
is more than enough for the auto-increment. The simplier the better. Why do you need foo_id
? We had the same problem early on, we named all our columns with the table prefix. like foo_id
, foo_name
, foo_age
. We dropped the tablename now and kept only the col as short as possible.
Since we are using just an id for PK we will be using foo_bar_fk
(tablename is unique, folowed by the unique PK, followed by the _fk
) as foreign key. We don't add id
to the col name because it is said that the name 'id' is always the PK of the given table. So we have just the tablename and the _fk
at the end.
For constrains we remove all underscores and join with camelCase (tablename + Colname + Fk) foobarUsernameFk
(for username_fk col). It's just a way we are following. We keep a documentation for every names structures.
When keeping the col name short, we should also keep an eye on the RESTRICTED names.
+------------------------------------+
| foobar |
+------------------------------------+
| id (PK for the current table) |
| username_fk (PK of username table) |
| location (other column) |
| tel (other column) |
+------------------------------------+
Try moving <uses-permission>
outside the <application>
tag.
I had a similar issue not long time ago and this was how I solved it
.rotated-half-circle {_x000D_
/* Create the circle */_x000D_
width: 40px;_x000D_
height: 40px;_x000D_
border: 10px solid black;_x000D_
border-radius: 50%;_x000D_
/* Halve the circle */_x000D_
border-bottom-color: transparent;_x000D_
border-left-color: transparent;_x000D_
/* Rotate the circle */_x000D_
transform: rotate(-45deg);_x000D_
}
_x000D_
<div class="rotated-half-circle"></div>
_x000D_
There is also a solution:
http://www.welefen.com/php-unicode-to-utf8.html
function entity2utf8onechar($unicode_c){
$unicode_c_val = intval($unicode_c);
$f=0x80; // 10000000
$str = "";
// U-00000000 - U-0000007F: 0xxxxxxx
if($unicode_c_val <= 0x7F){ $str = chr($unicode_c_val); } //U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
else if($unicode_c_val >= 0x80 && $unicode_c_val <= 0x7FF){ $h=0xC0; // 11000000
$c1 = $unicode_c_val >> 6 | $h;
$c2 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2);
} else if($unicode_c_val >= 0x800 && $unicode_c_val <= 0xFFFF){ $h=0xE0; // 11100000
$c1 = $unicode_c_val >> 12 | $h;
$c2 = (($unicode_c_val & 0xFC0) >> 6) | $f;
$c3 = ($unicode_c_val & 0x3F) | $f;
$str=chr($c1).chr($c2).chr($c3);
}
//U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
else if($unicode_c_val >= 0x10000 && $unicode_c_val <= 0x1FFFFF){ $h=0xF0; // 11110000
$c1 = $unicode_c_val >> 18 | $h;
$c2 = (($unicode_c_val & 0x3F000) >>12) | $f;
$c3 = (($unicode_c_val & 0xFC0) >>6) | $f;
$c4 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2).chr($c3).chr($c4);
}
//U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if($unicode_c_val >= 0x200000 && $unicode_c_val <= 0x3FFFFFF){ $h=0xF8; // 11111000
$c1 = $unicode_c_val >> 24 | $h;
$c2 = (($unicode_c_val & 0xFC0000)>>18) | $f;
$c3 = (($unicode_c_val & 0x3F000) >>12) | $f;
$c4 = (($unicode_c_val & 0xFC0) >>6) | $f;
$c5 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2).chr($c3).chr($c4).chr($c5);
}
//U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if($unicode_c_val >= 0x4000000 && $unicode_c_val <= 0x7FFFFFFF){ $h=0xFC; // 11111100
$c1 = $unicode_c_val >> 30 | $h;
$c2 = (($unicode_c_val & 0x3F000000)>>24) | $f;
$c3 = (($unicode_c_val & 0xFC0000)>>18) | $f;
$c4 = (($unicode_c_val & 0x3F000) >>12) | $f;
$c5 = (($unicode_c_val & 0xFC0) >>6) | $f;
$c6 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2).chr($c3).chr($c4).chr($c5).chr($c6);
}
return $str;
}
function entities2utf8($unicode_c){
$unicode_c = preg_replace("/\&\#([\da-f]{5})\;/es", "entity2utf8onechar('\\1')", $unicode_c);
return $unicode_c;
}
Make sure your root index.php
file has the correct permission, its permission must be 0755
or 0644
Try to open Visual Studio as admin.
For it is fixed by using below statement in app.web.scss
$fa-font-path: "../../node_modules/font-awesome/fonts/" !default;
@import "../../node_modules/font-awesome/scss/font-awesome";
Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray
with java8 Stream API.
import org.json.JSONArray;
import org.json.JSONObject;
@Test
public void access_org_JsonArray() {
//Given: array
JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
new HashMap() {{
put("a", 100);
put("b", 200);
}}
),
new JSONObject(
new HashMap() {{
put("a", 300);
put("b", 400);
}}
)));
//Then: convert to List<JSONObject>
List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.collect(Collectors.toList());
// you can access the array elements now
jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
// prints 100, 300
}
If the iteration is only one time, (no need to .collect
)
IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.forEach(item -> {
System.out.println(item);
});
There doesn't seem to be justify-self
, but you can achieve similar result setting appropriate margin
to auto
¹. E. g. for flex-direction: row
(default) you should set margin-right: auto
to align the child to the left.
.container {_x000D_
height: 100px;_x000D_
border: solid 10px skyblue;_x000D_
_x000D_
display: flex;_x000D_
justify-content: flex-end;_x000D_
}_x000D_
.block {_x000D_
width: 50px;_x000D_
background: tomato;_x000D_
}_x000D_
.justify-start {_x000D_
margin-right: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="block justify-start"></div>_x000D_
<div class="block"></div>_x000D_
</div>
_x000D_
¹ This behaviour is defined by the Flexbox spec.
You're removing and then incrementing, which means you'll be one ahead of yourself. Instead, remove in reverse so you never mess up your next item.
for (int i = ChunkList.Count-1; i >=0; i--)
{
if (ChunkList[i].UniqueID == ChunkID)
{
ChunkList.RemoveAt(i);
}
}
<form name="theform">
<input type="text" />
<input type="text" />`enter code here`
<input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>
<script type="text/javascript" language="javascript">
let txt = document.querySelectorAll('[type="text"]');
for (let i = 0; i < txt.length; i++) {
txt[i].oninput = () => {
if (!(txt[0].value == '') && !(txt[1].value == '')) {
submitbutton.removeAttribute('disabled')
}
}
}
</script>
In case of Hybrid apps developed using cordova and angularjs, you can:
1) Rename the .apk file to .zip
2) Extract/Unzip the contents
3) In the assets folder you will get the www folder
I know this post is old, but just wanted to add a comment if somebody should be looking at this post and trying to find a solution for this problem.
You can indeed read the CPU temperature very easily in C# by using a WMI approach.
To get a Celsius value, I have created a wrapper that converts the value returned by WMI and wraps it into an easy to use object.
Please remember to add a reference to the System.Management.dll
in Visual Studio.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace RCoding.Common.Diagnostics.SystemInfo
{
public class Temperature
{
public double CurrentValue { get; set; }
public string InstanceName { get; set; }
public static List<Temperature> Temperatures
{
get
{
List<Temperature> result = new List<Temperature>();
ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature");
foreach (ManagementObject obj in searcher.Get())
{
Double temp = Convert.ToDouble(obj["CurrentTemperature"].ToString());
temp = (temp - 2732) / 10.0;
result.Add(new Temperature { CurrentValue = temp, InstanceName = obj["InstanceName"].ToString() });
}
return result;
}
}
}
}
Update 25.06.2010:
(Just saw that a link was posted to the same kind of solution above... Anyway, I will leave this piece of code if somebody should want to use it :-) )
If you want auto-indent just like Emacs does it on TAB, i.e. indent the current line and move the cursor to the first non-whitespace character, do this:
Insert the following macro code:
reindent-line caret-line-first-column caret-begin-line
Click "Set Shortcut" and press TAB
You'll need to get those bytes
into a MemoryStream
:
Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
bmp = new Bitmap(ms);
}
That uses the Bitmap(Stream stream)
constructor overload.
UPDATE: keep in mind that according to the documentation, and the source code I've been reading through, an ArgumentException
will be thrown on these conditions:
stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.
You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:
1.) change type of ID to int
instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea
First option requires to change every table that has a reference to this table, BUT it's worth it.
I think if you have any data point with apostrophe you can add one apostrophe before the apostrophe
eg. 'This is John's place'
Here MYSQL assumes two sentence 'This is John' 's place'
You can put 'This is John''s place'. I think it should work that way.
While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this
mkdir -p {main,test}/{resources,scala/com/company}
It will create following directory structure under the directory from where it is invoked
+-- main
¦ +-- resources
¦ +-- scala
¦ +-- com
¦ +-- company
+-- test
+-- resources
+-- scala
+-- com
+-- company
The example was taken from this link for creating SBT directory structure
To check if a lateinit var
were initialised or not use a .isInitialized
on the reference to that property:
if (foo::bar.isInitialized) {
println(foo.bar)
}
This checking is only available for the properties that are accessible lexically, i.e. declared in the same type or in one of the outer types, or at top level in the same file.
It is actually very easy. But there is no way you can achieve it directly. You need to select a service side technology. You can use anything for this part. And this is what we call a RESTful API or a SOAP API. It depends on you what to select. I have done many project with both. I would prefer REST. So what will happen you will have some scripts in your web server, and you know the URLs. For example we need to make a user registration. And for this we have
mydomain.com/v1/userregister.php
Now from the android side you will send an HTTP request to the above URL. And the above URL will handle the User Registration and will give you a response that whether the operation succeed or not.
For a complete detailed explanation of the above concept. You can visit the following link.
Simple query without partition clause:
select
sal,
RANK() over(order by sal desc) as Rank,
DENSE_RANK() over(order by sal desc) as DenseRank,
ROW_NUMBER() over(order by sal desc) as RowNumber
from employee
Output:
--------|-------|-----------|----------
sal |Rank |DenseRank |RowNumber
--------|-------|-----------|----------
5000 |1 |1 |1
3000 |2 |2 |2
3000 |2 |2 |3
2975 |4 |3 |4
2850 |5 |4 |5
--------|-------|-----------|----------
The following debug_msg
procedure can be called to simply output a debug message to the console:
DELIMITER $$
DROP PROCEDURE IF EXISTS `debug_msg`$$
DROP PROCEDURE IF EXISTS `test_procedure`$$
CREATE PROCEDURE debug_msg(enabled INTEGER, msg VARCHAR(255))
BEGIN
IF enabled THEN
select concat('** ', msg) AS '** DEBUG:';
END IF;
END $$
CREATE PROCEDURE test_procedure(arg1 INTEGER, arg2 INTEGER)
BEGIN
SET @enabled = TRUE;
call debug_msg(@enabled, 'my first debug message');
call debug_msg(@enabled, (select concat_ws('','arg1:', arg1)));
call debug_msg(TRUE, 'This message always shows up');
call debug_msg(FALSE, 'This message will never show up');
END $$
DELIMITER ;
Then run the test like this:
CALL test_procedure(1,2)
It will result in the following output:
** DEBUG:
** my first debug message
** DEBUG:
** arg1:1
** DEBUG:
** This message always shows up
This can happen if you have a newline (or other control character) in a JSON string literal.
{"foo": "bar
baz"}
If you are the one producing the data, replace actual newlines with escaped ones "\\n"
when creating your string literals.
{"foo": "bar\nbaz"}
I used mvn eclipse:eclipse -Dwtpversion=2.0
in command line in the folder where I had my pom.xml. Then I refreshed the project in eclipse IDE. After that I was able to add my project.
you need to import the function so the program know what that is here is example:
import os
import pyttsx3
i had the same problem first then i import the function and it work so i would really recommend to try it
$this->load->library('excel');
$file_name = 'Demo';
$arrHeader = array('Name', 'Mobile');
$arrRows = array(0=>array('Name'=>'Jayant','Mobile'=>54545), 1=>array('Name'=>'Jayant1', 'Mobile'=>44454), 2=>array('Name'=>'Jayant2','Mobile'=>111222), 3=>array('Name'=>'Jayant3', 'Mobile'=>99999));
$this->excel->getActiveSheet()->fromArray($arrHeader,'','A1');
$this->excel->getActiveSheet()->fromArray($arrRows);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$file_name.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save('php://output');
$(function () {
$('.datetimepicker').datetimepicker(
{
format: 'Y-m-d h:m:s'
}
);
});`
I have the almost the same situation as yours; that if the screen width is less than the my specified width it should hide the div. This is the jquery code I used that worked for me.
$(window).resize(function() {
if ($(this).width() < 1024) {
$('.divIWantedToHide').hide();
} else {
$('.divIWantedToHide').show();
}
});
If you're using MySQL, there is a method REGEXP that you can use...
http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp
So then you would use:
SELECT * FROM `shirts` WHERE `colors` REGEXP '\b1\b'
For a long time, DOM3 mutation events were the best available solution, but they have been deprecated for performance reasons. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver
(or as the vendor-prefixed WebKitMutationObserver
in old versions of Chrome):
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
console.log(mutations, observer);
// ...
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
attributes: true
//...
});
This example listens for DOM changes on document
and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:
childList
- Set to
true
if mutations to target's children are to be observed.attributes
- Set to
true
if mutations to target's attributes are to be observed.characterData
- Set to
true
if mutations to target's data are to be observed.subtree
- Set to
true
if mutations to not just target, but also target's descendants are to be observed.attributeOldValue
- Set to
true
ifattributes
is set to true and target's attribute value before the mutation needs to be recorded.characterDataOldValue
- Set to
true
ifcharacterData
is set to true and target's data before the mutation needs to be recorded.attributeFilter
- Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.
(This list is current as of April 2014; you may check the specification for any changes.)
The error is telling you that x
doesn’t even exist! It hasn’t been declared, which is different than being assigned a value.
var x; // declaration
x = 2; // assignment
If you declared x
, you wouldn’t get an error. You would get an alert that says undefined
because x
exists/has been declared but hasn’t been assigned a value.
To check if the variable has been declared, you can use typeof
, any other method of checking if a variable exists will raise the same error you got initially.
if(typeof x !== "undefined") {
alert(x);
}
This is checking the type of the value stored in x
. It will only return undefined
when x
hasn’t been declared OR if it has been declared and was not yet assigned.
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
I found a very simple method that works well:
<input type="text" onclick="this.focus();this.select()">
You can just split your string like that using this regular expression
String l = "sofia, malgré tout aimait : la laitue et le choux !" <br/>
l.split("[[ ]*|[,]*|[\\.]*|[:]*|[/]*|[!]*|[?]*|[+]*]+");
To extract a single number from a string you can use re.search()
, which returns the first match (or None
):
>>> import re
>>> string = '3158 reviews'
>>> int(re.search(r'\d+', string).group(0))
3158
In Python 3.6+ you can also index into a match object instead of using group()
:
>>> int(re.search(r'\d+', string)[0])
3158
This is many years late but since I found the solution I'll post it here. By using maps it is possible to do what was asked:
map $http_host $variable_name {
hostnames;
default /ap/;
example.com /api/;
*.example.org /whatever/;
}
server {
location $variable_name/test {
proxy_pass $auth_proxy;
}
}
If you need to share the same endpoint across multiple servers, you can also reduce the cost by simply defaulting the value:
map "" $variable_name {
default /test/;
}
Map can be used to initialise a variable based on the content of a string and can be used inside http
scope allowing variables to be global and sharable across servers.
I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.
That means:
then link the two together:
public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException
{
FileReader fr = null;
try {
fr = new FileReader(source);
XMLReader reader = new NamespaceFilterXMLReader();
InputSource is = new InputSource(fr);
SAXSource ss = new SAXSource(reader, is);
return unmarshaller.unmarshal(ss);
} catch (SAXException e) {
//not technically a jaxb exception, but close enough
throw new JAXBException(e);
} catch (ParserConfigurationException e) {
//not technically a jaxb exception, but close enough
throw new JAXBException(e);
} finally {
FileUtil.close(fr); //replace with this some safe close method you have
}
}
file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))
This is solve your encode error
also.
VBA is not VB/VB.NET
The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:
Do While counter < 20
counter = counter + 1
Loop
(But a For..Next might be more appropriate here.)
Happy coding.
If you want to be able to specify the seed, you just need to replace the calls to getSeconds()
and getMinutes()
. You could pass in an int and use half of it mod 60 for the seconds value and the other half modulo 60 to give you the other part.
That being said, this method looks like garbage. Doing proper random number generation is very hard. The obvious problem with this is that the random number seed is based on seconds and minutes. To guess the seed and recreate your stream of random numbers only requires trying 3600 different second and minute combinations. It also means that there are only 3600 different possible seeds. This is correctable, but I'd be suspicious of this RNG from the start.
If you want to use a better RNG, try the Mersenne Twister. It is a well tested and fairly robust RNG with a huge orbit and excellent performance.
EDIT: I really should be correct and refer to this as a Pseudo Random Number Generator or PRNG.
"Anyone who uses arithmetic methods to produce random numbers is in a state of sin."
--- John von Neumann
I solve this issue deleting the 10 packages in my android sdk manage.
for frequency distribution of a variable with excessive values you can collapse down the values in classes,
Here I excessive values for employrate
variable, and there's no meaning of it's frequency distribution with direct values_count(normalize=True)
country employrate alcconsumption
0 Afghanistan 55.700001 .03
1 Albania 11.000000 7.29
2 Algeria 11.000000 .69
3 Andorra nan 10.17
4 Angola 75.699997 5.57
.. ... ... ...
208 Vietnam 71.000000 3.91
209 West Bank and Gaza 32.000000
210 Yemen, Rep. 39.000000 .2
211 Zambia 61.000000 3.56
212 Zimbabwe 66.800003 4.96
[213 rows x 3 columns]
frequency distribution with values_count(normalize=True)
with no classification,length of result here is 139 (seems meaningless as a frequency distribution):
print(gm["employrate"].value_counts(sort=False,normalize=True))
50.500000 0.005618
61.500000 0.016854
46.000000 0.011236
64.500000 0.005618
63.500000 0.005618
58.599998 0.005618
63.799999 0.011236
63.200001 0.005618
65.599998 0.005618
68.300003 0.005618
Name: employrate, Length: 139, dtype: float64
putting classification we put all values with a certain range ie.
0-10 as 1, 11-20 as 2 21-30 as 3, and so forth.
gm["employrate"]=gm["employrate"].str.strip().dropna()
gm["employrate"]=pd.to_numeric(gm["employrate"])
gm['employrate'] = np.where(
(gm['employrate'] <=10) & (gm['employrate'] > 0) , 1, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=20) & (gm['employrate'] > 10) , 1, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=30) & (gm['employrate'] > 20) , 2, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=40) & (gm['employrate'] > 30) , 3, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=50) & (gm['employrate'] > 40) , 4, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=60) & (gm['employrate'] > 50) , 5, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=70) & (gm['employrate'] > 60) , 6, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=80) & (gm['employrate'] > 70) , 7, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=90) & (gm['employrate'] > 80) , 8, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=100) & (gm['employrate'] > 90) , 9, gm['employrate']
)
print(gm["employrate"].value_counts(sort=False,normalize=True))
after classification we have a clear frequency distribution.
here we can easily see, that 37.64%
of countries have employ rate between 51-60%
and 11.79%
of countries have employ rate between 71-80%
5.000000 0.376404
7.000000 0.117978
4.000000 0.179775
6.000000 0.264045
8.000000 0.033708
3.000000 0.028090
Name: employrate, dtype: float64
Try following
ALTER TABLE <TABLE_NAME> DROP CONSTRAINT <FOREIGN_KEY_NAME>
The GO command isn't a Transact-SQL statement, but a special command recognized by several MS utilities including SQL Server Management Studio code editor.
The GO command is used to group SQL commands into batches which are sent to the server together. The commands included in the batch, that is, the set of commands since the last GO command or the start of the session, must be logically consistent. For example, you can't define a variable in one batch and then use it in another since the scope of the variable is limited to the batch in which it's defined.
For more information, see http://msdn.microsoft.com/en-us/library/ms188037.aspx.
Extending Django User Model (UserProfile) like a Pro
I've found this very useful: link
An extract:
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User)
department = models.CharField(max_length=100)
>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.employee.department
OLD: Create a global instance of _MyHomePageState. Use this instance in _SubState as _myHomePageState.setState
NEW: No need to create global instance. Instead just pass the parent instance to the child widget
CODE UPDATED AS PER FLUTTER 0.8.2:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
EdgeInsets globalMargin =
const EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0);
TextStyle textStyle = const TextStyle(
fontSize: 100.0,
color: Colors.black,
);
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int number = 0;
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('SO Help'),
),
body: new Column(
children: <Widget>[
new Text(
number.toString(),
style: textStyle,
),
new GridView.count(
crossAxisCount: 2,
shrinkWrap: true,
scrollDirection: Axis.vertical,
children: <Widget>[
new InkResponse(
child: new Container(
margin: globalMargin,
color: Colors.green,
child: new Center(
child: new Text(
"+",
style: textStyle,
),
)),
onTap: () {
setState(() {
number = number + 1;
});
},
),
new Sub(this),
],
),
],
),
floatingActionButton: new FloatingActionButton(
onPressed: () {
setState(() {});
},
child: new Icon(Icons.update),
),
);
}
}
class Sub extends StatelessWidget {
_MyHomePageState parent;
Sub(this.parent);
@override
Widget build(BuildContext context) {
return new InkResponse(
child: new Container(
margin: globalMargin,
color: Colors.red,
child: new Center(
child: new Text(
"-",
style: textStyle,
),
)),
onTap: () {
this.parent.setState(() {
this.parent.number --;
});
},
);
}
}
Just let me know if it works.
I have a solution below and its works for me:
app.controller('LoginController', ['$http', '$scope', function ($scope, $http) {
$scope.login = function (credentials) {
$http({
method: 'jsonp',
url: 'http://mywebservice',
params: {
format: 'jsonp',
callback: 'JSON_CALLBACK'
}
}).then(function (response) {
alert(response.data);
});
}
}]);
in 'http://mywebservice' there must be need a callback parameter which return JSON_CALLBACK with data.
There is a sample example below which works perfect
$scope.url = "https://angularjs.org/greet.php";
$http({
method: 'jsonp',
url: $scope.url,
params: {
format: 'jsonp',
name: 'Super Hero',
callback: 'JSON_CALLBACK'
}
}).then(function (response) {
alert(response.data);
});
example output:
{"name":"Super Hero","salutation":"Apa khabar","greeting":"Apa khabar Super Hero!"}
In addition to the answer by fenix2222 (which worked for me) I had to modify the last line to:
config.Save(ConfigurationSaveMode.Modified);
Without this, the new value was still being written to the config file but the old value was retrieved when debugging.
This has been working for me:
1. Set credential hepler to store
$ git config --global credential.helper store
2. then verify if you want:
$ git config --global credential.helper
store
Simple example when using git bash quoted from Here (works for current repo only, use --global
for all repos)
$ git config credential.helper store
$ git push http://example.com/repo.git
Username: < type your username >
Password: < type your password >
[several days later]
$ git push http://example.com/repo.git
[your credentials are used automatically]
Will work for VS Code too.
More detailed example and advanced usage here.
Note: Username & Passwords are not encrypted and stored in plain text format so use it on your personal computer only.
Alternatively, you can also use a special function known as the linear-gradient() function to split browser screen into two equal halves. Check out the following code snippet:
body
{
background-image:linear-gradient(90deg, lightblue 50%, skyblue 50%);
}
Here, linear-gradient() function accepts three arguments
90deg
for vertical division of screen.( Similarly, you can use 180deg
for horizontal division of screen)lightblue
color is used to represent the left half of the screen.skyblue
color has been used to represent the right half of the split screen.
Here, 50%
has been used for equal division of the browser screen. You can use any other value if you don't want an equal division of the screen.
Hope this helps. :)
Happy Coding!Use String#replace()
.
To replace them with spaces (as per your question title):
System.out.println("I don't like these \"double\" quotes".replace("\"", " "));
The above can also be done with characters:
System.out.println("I don't like these \"double\" quotes".replace('"', ' '));
To remove them (as per your example):
System.out.println("I don't like these \"double\" quotes".replace("\"", ""));
If you don't want duplicates in a list, use a HashSet
. That way it will be clear to anyone else reading your code what your intention was and you'll have less code to write since HashSet
already handles what you are trying to do.
Create PROCEDURE Stored_Procedure_Name_2
(
@param1 int = 5 ,
@param2 varchar(max),
@param3 varchar(max)
)
AS
DECLARE @Table TABLE
(
/*TABLE DEFINITION*/
id int,
name varchar(max),
address varchar(max)
)
INSERT INTO @Table
EXEC Stored_Procedure_Name_1 @param1 , @param2 = 'Raju' ,@param3 =@param3
SELECT id ,name ,address FROM @Table
Eric pretty much nailed it. We (Bitnami) are a popular provider of free AMIs for popular applications and development frameworks (PHP, Joomla, Drupal, you get the idea). I can tell you that EBS-backed AMIs are significantly more popular than S3-backed. In general I think s3-backed instances are used for distributed, time-limited jobs (for example, large scale processing of data) where if one machine fails, another one is simply spinned up. EBS-backed AMIS tend to be used for 'traditional' server tasks, such as web or database servers that keep state locally and thus require the data to be available in the case of crashing.
One aspect I did not see mentioned is the fact that you can take snapshots of an EBS-backed instance while running, effectively allowing you to have very cost-effective backups of your infrastructure (the snapshots are block-based and incremental)
<script>
var listh = document.getElementById( 'list-home-list' );
var hb = document.getElementsByTagName('hb');
$("#list-home-list").click(function(){
$(this).style.color = '#2C2E33';
hb.style.color = 'white';
});
</script>
1: Prototype.observe
uses Element.addEventListener (see the source code)
2: You can override Element.addEventListener
to remember the added listeners (handy property EventListenerList
was removed from DOM3 spec proposal). Run this code before any event is attached:
(function() {
Element.prototype._addEventListener = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(a,b,c) {
this._addEventListener(a,b,c);
if(!this.eventListenerList) this.eventListenerList = {};
if(!this.eventListenerList[a]) this.eventListenerList[a] = [];
this.eventListenerList[a].push(b);
};
})();
Read all the events by:
var clicks = someElement.eventListenerList.click;
if(clicks) clicks.forEach(function(f) {
alert("I listen to this function: "+f.toString());
});
And don't forget to override Element.removeEventListener
to remove the event from the custom Element.eventListenerList
.
3: the Element.onclick
property needs special care here:
if(someElement.onclick)
alert("I also listen tho this: "+someElement.onclick.toString());
4: don't forget the Element.onclick
content attribute: these are two different things:
someElement.onclick = someHandler; // IDL attribute
someElement.setAttribute("onclick","otherHandler(event)"); // content attribute
So you need to handle it, too:
var click = someElement.getAttribute("onclick");
if(click) alert("I even listen to this: "+click);
The Visual Event bookmarklet (mentioned in the most popular answer) only steals the custom library handler cache:
It turns out that there is no standard method provided by the W3C recommended DOM interface to find out what event listeners are attached to a particular element. While this may appear to be an oversight, there was a proposal to include a property called eventListenerList to the level 3 DOM specification, but was unfortunately been removed in later drafts. As such we are forced to looked at the individual Javascript libraries, which typically maintain a cache of attached events (so they can later be removed and perform other useful abstractions).
As such, in order for Visual Event to show events, it must be able to parse the event information out of a Javascript library.
Element overriding may be questionable (i.e. because there are some DOM specific features like live collections, which can not be coded in JS), but it gives the eventListenerList support natively and it works in Chrome, Firefox and Opera (doesn't work in IE7).
I use a few methods depending. In the same stylesheet i use: @media (max-width: 450px), or for separate make sure you have the link in the header correctly. I had a look at your fixmeup and you have a confusing array of links to css. It acts as you say also on HTC desire S.
For everyone coming here for having similar question, the following works great and I have it in my library the last years:
(function(g3, $, window, document, undefined){
g3.utils = g3.utils || {};
/********************************Function type()********************************
* Returns a lowercase string representation of an object's constructor.
* @module {g3.utils}
* @function {g3.utils.type}
* @public
* @param {Type} 'obj' is any type native, host or custom.
* @return {String} Returns a lowercase string representing the object's
* constructor which is different from word 'object' if they are not custom.
* @reference http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
* http://stackoverflow.com/questions/3215046/differentiating-between-arrays-and-hashes-in-javascript
* http://javascript.info/tutorial/type-detection
*******************************************************************************/
g3.utils.type = function (obj){
if(obj === null)
return 'null';
else if(typeof obj === 'undefined')
return 'undefined';
return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
};
}(window.g3 = window.g3 || {}, jQuery, window, document));
First you check your user agent OS Linux or windows or another. Then Your OS Windows Then this code use:
public function win_os(){
ob_start();
system('ipconfig-a');
$mycom=ob_get_contents(); // Capture the output into a variable
ob_clean(); // Clean (erase) the output buffer
$findme = "Physical";
$pmac = strpos($mycom, $findme); // Find the position of Physical text
$mac=substr($mycom,($pmac+36),17); // Get Physical Address
return $mac;
}
And your OS Linux Ubuntu or Linux then this code use:
public function unix_os(){
ob_start();
system('ifconfig -a');
$mycom = ob_get_contents(); // Capture the output into a variable
ob_clean(); // Clean (erase) the output buffer
$findme = "Physical";
//Find the position of Physical text
$pmac = strpos($mycom, $findme);
$mac = substr($mycom, ($pmac + 37), 18);
return $mac;
}
This code may be work OS X.
UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[labelName sizeToFit];
labelName.numberOfLines = 0;
labelName.text = @"Your String...";
[self.view addSubview:labelName];
SELECT (SELECT COALESCE(SUM(London), 0) FROM CASH) + (SELECT COALESCE(SUM(London), 0) FROM CHEQUE) as result
'And so on and so forth.
"The COALESCE function basically says "return the first parameter, unless it's null in which case return the second parameter" - It's quite handy in these scenarios." Source
There is a basic difference between .append()
and .after()
and .prepend()
and .before()
.
.append()
adds the parameter element inside the selector element's tag at the very end whereas the .after()
adds the parameter element after the element's tag.
The vice-versa is for .prepend()
and .before()
.
Download the map file and the uncompressed version of jQuery.
Put them with the minified version:
Include minified version into your HTML:
Check in Google Chrome:
Get familiar with Debugging JavaScript
When the JVM loads classes, or otherwise sees a literal string, or some code intern
s a string, it adds the string to a mostly-hidden lookup table that has one copy of each such string. If another copy is added, the runtime arranges it so that all the literals refer to the same string object. This is called "interning". If you say something like
String s = "test";
return (s == "test");
it'll return true
, because the first and second "test" are actually the same object. Comparing interned strings this way can be much, much faster than String.equals
, as there's a single reference comparison rather than a bunch of char
comparisons.
You can add a string to the pool by calling String.intern()
, which will give you back the pooled version of the string (which could be the same string you're interning, but you'd be crazy to rely on that -- you often can't be sure exactly what code has been loaded and run up til now and interned the same string). The pooled version (the string returned from intern
) will be equal to any identical literal. For example:
String s1 = "test";
String s2 = new String("test"); // "new String" guarantees a different object
System.out.println(s1 == s2); // should print "false"
s2 = s2.intern();
System.out.println(s1 == s2); // should print "true"
How about achieving this using only HTML attribute 'disabled'
<form>
<fieldset disabled>
<div class="row">
<input type="text" placeholder="">
<textarea></textarea>
<select></select>
</div>
<div class="pull-right">
<button class="button-primary btn-sm" type="submit">Submit</button>
</div>
</fieldset>
</form>
Just by putting disabled in the fieldset all the fields inside of that fieldset get disabled.
$('fieldset').attr('disabled', 'disabled');
I would say the answer is: you can't. (or at least: you shouldn't). This is not what Webpack is supposed to do. Webpack is a bundler, and it should not be used for other tasks (in this case: copying static files is another task). You should use a tool like Grunt or Gulp to do such tasks. It is very common to integrate Webpack as a Grunt task or as a Gulp task. They both have other tasks useful for copying files like you described, for example, grunt-contrib-copy or gulp-copy.
For other assets (not the index.html
), you can just bundle them in with Webpack (that is exactly what Webpack is for). For example, var image = require('assets/my_image.png');
. But I assume your index.html
needs to not be a part of the bundle, and therefore it is not a job for the bundler.
Let me introduce easy GUI/idiot proof approach that you can take in these situations.
myRepo_temp
myRepo_original
).myRepo_temp
and myRepo_original
)This is useful for example if you want partially reverse some changes as you can copy stuff from one to another folder.
Probably the machine or web.config in prod has the settings in the configuration; you probably won't need the proxy tag.
<system.net>
<defaultProxy useDefaultCredentials="true" >
<proxy usesystemdefault="False"
proxyaddress="http://<ProxyLocation>:<port>"
bypassonlocal="True"
autoDetect="False" />
</defaultProxy>
</system.net>
map
is implemented from balanced binary search tree
(usually a rb_tree
), since all the member in balanced binary search tree
is sorted so is map;
hash_map
is implemented from hashtable
.Since all the member in hashtable
is unsorted so the members in hash_map(unordered_map)
is not sorted.
hash_map
is not a c++ standard library, but now it renamed to unordered_map
(you can think of it renamed) and becomes c++ standard library since c++11 see this question Difference between hash_map and unordered_map? for more detail.
Below i will give some core interface from source code of how the two type map is implemented.
The below code is just to show that, map is just a wrapper of an balanced binary search tree
, almost all it's function is just invoke the balanced binary search tree
function.
template <typename Key, typename Value, class Compare = std::less<Key>>
class map{
// used for rb_tree to sort
typedef Key key_type;
// rb_tree node value
typedef std::pair<key_type, value_type> value_type;
typedef Compare key_compare;
// as to map, Key is used for sort, Value used for store value
typedef rb_tree<key_type, value_type, key_compare> rep_type;
// the only member value of map (it's rb_tree)
rep_type t;
};
// one construct function
template<typename InputIterator>
map(InputIterator first, InputIterator last):t(Compare()){
// use rb_tree to insert value(just insert unique value)
t.insert_unique(first, last);
}
// insert function, just use tb_tree insert_unique function
//and only insert unique value
//rb_tree insertion time is : log(n)+rebalance
// so map's insertion time is also : log(n)+rebalance
typedef typename rep_type::const_iterator iterator;
std::pair<iterator, bool> insert(const value_type& v){
return t.insert_unique(v);
};
hash_map
:hash_map
is implemented from hashtable
whose structure is somewhat like this:
In the below code, i will give the main part of hashtable
, and then gives hash_map
.
// used for node list
template<typename T>
struct __hashtable_node{
T val;
__hashtable_node* next;
};
template<typename Key, typename Value, typename HashFun>
class hashtable{
public:
typedef size_t size_type;
typedef HashFun hasher;
typedef Value value_type;
typedef Key key_type;
public:
typedef __hashtable_node<value_type> node;
// member data is buckets array(node* array)
std::vector<node*> buckets;
size_type num_elements;
public:
// insert only unique value
std::pair<iterator, bool> insert_unique(const value_type& obj);
};
Like map's
only member is rb_tree
, the hash_map's
only member is hashtable
. It's main code as below:
template<typename Key, typename Value, class HashFun = std::hash<Key>>
class hash_map{
private:
typedef hashtable<Key, Value, HashFun> ht;
// member data is hash_table
ht rep;
public:
// 100 buckets by default
// it may not be 100(in this just for simplify)
hash_map():rep(100){};
// like the above map's insert function just invoke rb_tree unique function
// hash_map, insert function just invoke hashtable's unique insert function
std::pair<iterator, bool> insert(const Value& v){
return t.insert_unique(v);
};
};
Below image shows when a hash_map have 53 buckets, and insert some values, it's internal structure.
The below image shows some difference between map and hash_map(unordered_map), the image comes from How to choose between map and unordered_map?:
The easiest way is
find . -type f -name '*.extension' 2>/dev/null | xargs grep -i string
Edit:
add 2>/dev/null
to kill the error output
To include more file extensions and grep for password throughout the system:
find / -type f \( -name '*.conf' -o -name "*.log" -o -name "*.bak" \) 2>/dev/null |
xargs grep -i password
None of the posted solutions worked for me.
I had to vi
into my Makefile and edit the path so that the path to the include
folder and the OS subsystem (in my case, -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux
) was correct. This allowed me to run make
and make install
without issues.
Put it inside your <footer>
by all means, but the most fitting element is the small element.
The HTML5 spec for this says:
Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or for satisfying licensing requirements.
If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.
For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11
To edit the Compatibility View list:
Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.
Are you familiar with other functional languages? i.e. are you trying to learn how python does functional programming, or are you trying to learn about functional programming and using python as the vehicle?
Also, do you understand list comprehensions?
map(f, sequence)
is directly equivalent (*) to:
[f(x) for x in sequence]
In fact, I think map()
was once slated for removal from python 3.0 as being redundant (that didn't happen).
map(f, sequence1, sequence2)
is mostly equivalent to:
[f(x1, x2) for x1, x2 in zip(sequence1, sequence2)]
(there is a difference in how it handles the case where the sequences are of different length. As you saw, map()
fills in None when one of the sequences runs out, whereas zip()
stops when the shortest sequence stops)
So, to address your specific question, you're trying to produce the result:
foos[0], bars
foos[1], bars
foos[2], bars
# etc.
You could do this by writing a function that takes a single argument and prints it, followed by bars:
def maptest(x):
print x, bars
map(maptest, foos)
Alternatively, you could create a list that looks like this:
[bars, bars, bars, ] # etc.
and use your original maptest:
def maptest(x, y):
print x, y
One way to do this would be to explicitely build the list beforehand:
barses = [bars] * len(foos)
map(maptest, foos, barses)
Alternatively, you could pull in the itertools
module. itertools
contains many clever functions that help you do functional-style lazy-evaluation programming in python. In this case, we want itertools.repeat
, which will output its argument indefinitely as you iterate over it. This last fact means that if you do:
map(maptest, foos, itertools.repeat(bars))
you will get endless output, since map()
keeps going as long as one of the arguments is still producing output. However, itertools.imap
is just like map()
, but stops as soon as the shortest iterable stops.
itertools.imap(maptest, foos, itertools.repeat(bars))
Hope this helps :-)
(*) It's a little different in python 3.0. There, map() essentially returns a generator expression.
GlobalConfiguration.Configure API is available in "Microsoft.AspNet.WebApi.WebHost" version="5.2.3"
and not in "Microsoft.AspNet.WebApi.WebHost" version="4.0.0"
I used this line to locate and edit the permissions under xampp:
chmod 777 ~/.bitnami/stackman/machines/xampp/volumes/root/htdocs/folder
It is cd
for "current directory".
aList=[1,2,3]
i=0
for item in aList:
if i<2:
aList.remove(item)
i+=1
aList
[2]
The moral is when modifying a list in a loop driven by the list, takes two steps:
aList=[1,2,3]
i=0
for item in aList:
if i<2:
aList[i]="del"
i+=1
aList
['del', 'del', 3]
for i in range(2):
del aList[0]
aList
[3]
Modifying the example here:
You can use legend_out = False
import seaborn as sns
sns.set(style="whitegrid")
titanic = sns.load_dataset("titanic")
g = sns.factorplot("class", "survived", "sex",
data=titanic, kind="bar",
size=6, palette="muted",
legend_out=False)
g.despine(left=True)
g.set_ylabels("survival probability")
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind
functions to each result callback; the order of parameters is: (success, failure)
. So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: @get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401
You'll want to use the formatting macros from inttypes.h.
See this question: Cross platform format string for variables of type size_t?
Abstraction is hiding the information or providing only necessary details to the client.
e.g Car Brakes- You just know that pressing the pedals will stop the vehicle but you don't need to know how it works internally.
Advantage of Abstraction Tomorrow if brake implementation changes from drum brake to disk brake, as a client, you don't need to change(i.e your code will not change)
Encapsulation is binding the data and behaviors together in a single unit. Also it is a language mechanism for restricting access to some components(this can be achieved by access modifiers like private,protected etc.)
For e.g. Class has attributes(i.e data) and behaviors (i.e methods that operate on that data)
I didn't have much luck with many of these solutions on all browsers. This is the solution that worked for me.
For router changes:
router.events.subscribe((val) => {
setTimeout(() => {
if (this.searchElement) {
this.searchElement.nativeElement.focus();
}
}, 1);
})
Then ngAfterViewInit()
for the onload scenario.
As per @Nitsew's answer, Create your personal access token and use your token as your username and enter with blank password.
Later you won't need any credentials to access all your private repo(s).
In webkit-based browsers(Safari and Chrome), -webkit-transform
is ignored on inline elements.. Set display: inline-block;
to make it work. For demonstration/testing purposes, you may also want to use a negative angle or a transformation-origin
lest the text is rotated out of the visible area.
Clarifications to the preceding posts:
References are NOT a guarantee of getting a non-null pointer. (Though we often treat them as such.)
While horrifically bad code, as in take you out behind the woodshed bad code, the following will compile & run: (At least under my compiler.)
bool test( int & a)
{
return (&a) == (int *) NULL;
}
int
main()
{
int * i = (int *)NULL;
cout << ( test(*i) ) << endl;
};
The real issue I have with references lies with other programmers, henceforth termed IDIOTS, who allocate in the constructor, deallocate in the destructor, and fail to supply a copy constructor or operator=().
Suddenly there's a world of difference between foo(BAR bar) and foo(BAR & bar). (Automatic bitwise copy operation gets invoked. Deallocation in destructor gets invoked twice.)
Thankfully modern compilers will pick up this double-deallocation of the same pointer. 15 years ago, they didn't. (Under gcc/g++, use setenv MALLOC_CHECK_ 0 to revisit the old ways.) Resulting, under DEC UNIX, in the same memory being allocated to two different objects. Lots of debugging fun there...
More practically:
First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));
Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
In Express 3.x you could use express.bodyParser
middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:
You need to define a route to handle form posts:
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/path/to/temporary/directory/to/store/uploaded/files"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.png");
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.
In order to show the uploaded image, assuming you already have an HTML page containing an img element:
<img src="/image.png" />
you can define another route in your express app and use res.sendFile
to serve the stored image:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
Tools->Preferences->Syntax coloring->Scheme changed to "Spyder Dark"
As Alex Gray points out in a comment above, "all of the corresponding IDs are actually on the extensions page within the browser".
However, you must click the Developer Mode checkbox at top of Extensions page to see them.
It worked using PSCP. Instructions:
set PATH=<path to the pscp.exe file>
pscp
use the following command to copy file form remote server to the local system
pscp [options] [user@]host:source target
So to copy the file /etc/hosts
from the server example.com
as user fred
to the file
c:\temp\example-hosts.txt
, you would type:
pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt
from jQuery v1.6 use prop
to check that is checkd or not
$('input:radio').prop('checked') // will return true or false
and to make it checkd use
$("input").prop("checked", true);
Don't know what your problem is but:
function date_compare($d1, $d2)
{
$d1 = explode('_', $d1);
$d2 = explode('_', $d2);
$d1 = array_reverse($d1);
$d2 = array_reverse($d2);
if (strtotime(implode('-', $d1)) > strtotime(implode('-', $d2)))
{
return $d2;
}
else
{
return $d1;
}
}
Many DNS servers refuse ‘ANY’ queries. So the only way is to query for every type individually. Luckily there are sites that make this simpler. For example, https://www.nslookup.io shows the most popular record types by default, and has support for all existing record types.
this is my working batch
publish-my-website.bat
SET MSBUILD_PATH="C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin"
SET PUBLISH_DIRECTORY="C:\MyWebsitePublished"
SET PROJECT="D:\Github\MyWebSite.csproj"
cd /d %MSBUILD_PATH%
MSBuild %PROJECT% /p:DeployOnBuild=True /p:DeployDefaultTarget=WebPublish /p:WebPublishMethod=FileSystem /p:DeleteExistingFiles=True /p:publishUrl=%PUBLISH_DIRECTORY%
Note that I installed Visual Studio on server to be able to run MsBuild.exe
because the MsBuild.exe
in .Net Framework folders don't work.
Tapestry pages and components are simple POJO's(Plain Old Java Object) consisting of getters and setters for easy access to Java language features.
I should like to contribute the modern answer. This involves using java.time
, the modern Java date and time API, and not the old Date
nor Calendar
except where there’s no way to avoid it.
Your issue is very likely really a timezone issue. When it is Tue Aug 09 00:00:00 IST 2011, in time zones west of IST midnight has not yet been reached. It is still Aug 8. If for example your API for putting the date into Excel expects UTC, the date will be the day before the one you intended. I believe the real and good solution is to produce a date-time of 00:00 UTC (or whatever time zone or offset is expected and used at the other end).
LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
ZonedDateTime utcDateDime = yourDate.atStartOfDay(ZoneOffset.UTC);
System.out.println(utcDateDime);
This prints
2018-02-27T00:00Z
Z
means UTC (think of it as offset zero from UTC or Zulu time zone). Better still, of course, if you could pass the LocalDate
from the first code line to Excel. It doesn’t include time-of-day, so there is no confusion possible. On the other hand, if you need an old-fashioned Date
object for that, convert just before handing the Date
on:
Date oldfashionedDate = Date.from(utcDateDime.toInstant());
System.out.println(oldfashionedDate);
On my computer this prints
Tue Feb 27 01:00:00 CET 2018
Don’t be fooled, it is correct. My time zone (Central European Time) is at offset +01:00 from UTC in February (standard time), so 01:00:00 here is equal to 00:00:00 UTC. It’s just Date.toString()
grabbing the JVMs time zone and using it for producing the string.
How can I set it to something like 5:30 pm?
To answer your direct question directly, if you have a ZonedDateTime
, OffsetDateTime
or LocalDateTime
, in all of these cases the following will accomplish what you asked for:
yourDateTime = yourDateTime.with(LocalTime.of(17, 30));
If yourDateTime
was a LocalDateTime
of 2018-02-27T00:00
, it will now be 2018-02-27T17:30
. Similarly for the other types, only they include offset and time zone too as appropriate.
If you only had a date, as in the first snippet above, you can also add time-of-day information to it:
LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
LocalDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30));
For most purposes you should prefer to add the time-of-day in a specific time zone, though, for example
ZonedDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30))
.atZone(ZoneId.of("Asia/Kolkata"));
This yields 2018-02-27T17:30+05:30[Asia/Kolkata]
.
Date
and Calendar
vs java.time
The Date
class that you use as well as Calendar
and SimpleDateFormat
used in the other answers are long outdated, and SimpleDateFormat
in particular has proven troublesome. In all cases the modern Java date and time API is so much nicer to work with. Which is why I wanted to provide this answer to an old question that is still being visited.
Link: Oracle Tutorial Date Time, explaining how to use java.time
.
Sounds correct but some issues maybe creates executing this query: I would suggest:
$this->db->where( "$accommodation BETWEEN $minvalue AND $maxvalue", NULL, FALSE );
Because it's an integer. You need to declare them as floating point numbers or decimals, or cast to such in the calculation.
For SQL Server 2012:
SELECT name, modify_date, create_date, type
FROM sys.procedures
WHERE name like '%XXX%'
ORDER BY modify_date desc
Here is a hack to disable "paste" popup. You have to override EditText
method:
@Override
public int getSelectionStart() {
for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
if (element.getMethodName().equals("canPaste")) {
return -1;
}
}
return super.getSelectionStart();
}
Similar can be done for the other actions.
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.
It's possible to access the private data of class directly in main and other's function...
here is a small code...
class GIFT
{
int i,j,k;
public:
void Fun()
{
cout<< i<<" "<< j<<" "<< k;
}
};
int main()
{
GIFT *obj=new GIFT(); // the value of i,j,k is 0
int *ptr=(int *)obj;
*ptr=10;
cout<<*ptr; // you also print value of I
ptr++;
*ptr=15;
cout<<*ptr; // you also print value of J
ptr++;
*ptr=20;
cout<<*ptr; // you also print value of K
obj->Fun();
}
Did you run mongod
before running mongo
?
I followed installation instructions for mongodb from http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/ and I had the same error as you only when I ran mongo
before actually running the mongo process with mongod
. I thought installing mongodb would also launch it but you need to launch it manually with mongod
before you do anything else that needs mongodb.
Behaviour subjects. I wrote a blog about that.
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
private noId = new BehaviorSubject<number>(0);
defaultId = this.noId.asObservable();
newId(urlId) {
this.noId.next(urlId);
}
In this example i am declaring a noid behavior subject of type number. Also it is an observable. And if "something happend" this will change with the new(){} function.
So, in the sibling's components, one will call the function, to make the change, and the other one will be affected by that change, or vice-versa.
For example, I get the id from the URL and update the noid from the behavior subject.
public getId () {
const id = +this.route.snapshot.paramMap.get('id');
return id;
}
ngOnInit(): void {
const id = +this.getId ();
this.taskService.newId(id)
}
And from the other side, I can ask if that ID is "what ever i want" and make a choice after that, in my case if i want to delte a task, and that task is the current url, it have to redirect me to the home:
delete(task: Task): void {
//we save the id , cuz after the delete function, we gonna lose it
const oldId = task.id;
this.taskService.deleteTask(task)
.subscribe(task => { //we call the defaultId function from task.service.
this.taskService.defaultId //here we are subscribed to the urlId, which give us the id from the view task
.subscribe(urlId => {
this.urlId = urlId ;
if (oldId == urlId ) {
// Location.call('/home');
this.router.navigate(['/home']);
}
})
})
}
datetime.datetime.fromtimestamp()
is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp()
expects Unix timestamp, in seconds.
Do it like that:
>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
and the result is:
>>> date
datetime.datetime(2012, 3, 16, 1, 0)
Does it answer your question?
EDIT: J.F. Sebastian correctly suggested to use true division by 1e3
(float 1000
). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int
when dividing (using /
operator) int
by int
(this is called floor division). By replacing the divisor 1000
(being an int
) with the 1e3
divisor (being representation of 1000
as float) or with float(1000)
(or 1000.
etc.), the division becomes true division. Python 2.x returns float
when dividing int
by float
, float
by int
, float
by float
etc. And when there is some fractional part in the timestamp passed to fromtimestamp()
method, this method's result also contains information about that fractional part (as the number of microseconds).
Grab it from here
Just choose required version and click 'Binary'. e.g direct link to version 2.5
string tail = test.Substring(test.LastIndexOf('-') + 1);
My answer is like above Aggregate solution but should be less call-stack heavy since there are no explicit delegate calls:
public static string ToCommaDelimitedString<T>(this IEnumerable<T> items)
{
StringBuilder sb = new StringBuilder();
foreach (var item in items)
{
sb.Append(item.ToString());
sb.Append(',');
}
if (sb.Length >= 1) sb.Length--;
return sb.ToString();
}
Of course, one can extend the signature to be delimiter-independent. I'm really not a fan of the sb.Remove() call and I'd like to refactor it to be a straight-up while-loop over an IEnumerable and use MoveNext() to determine whether or not to write a comma. I'll fiddle around and post that solution if I come upon it.
Here's what I wanted initially:
public static string ToDelimitedString<T>(this IEnumerable<T> source, string delimiter, Func<T, string> converter)
{
StringBuilder sb = new StringBuilder();
var en = source.GetEnumerator();
bool notdone = en.MoveNext();
while (notdone)
{
sb.Append(converter(en.Current));
notdone = en.MoveNext();
if (notdone) sb.Append(delimiter);
}
return sb.ToString();
}
No temporary array or list storage required and no StringBuilder
Remove()
or Length--
hack required.
In my framework library I made a few variations on this method signature, every combination of including the delimiter
and the converter
parameters with usage of ","
and x.ToString()
as defaults, respectively.
Stored Procedure.........
CREATE PROCEDURE usp_InsertContract
@ContractNumber varchar(7)
AS
BEGIN
INSERT into [dbo].[Contracts] (ContractNumber)
VALUES (@ContractNumber)
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
END
C#
pvCommand.CommandType = CommandType.StoredProcedure;
pvCommand.Parameters.Clear();
pvCommand.Parameters.Add(new SqlParameter("@ContractNumber", contractNumber));
object uniqueId;
int id;
try
{
uniqueId = pvCommand.ExecuteScalar();
id = Convert.ToInt32(uniqueId);
}
catch (Exception e)
{
Debug.Print(" Message: {0}", e.Message);
}
}
EDIT: "I still get back a DBNull value....Object cannot be cast from DBNull to other types. I'll take this up again tomorrow. I'm off to my other job,"
I believe the Id column in your SQL Table isn't a identity column.
As to me, easier: (int) (a +.5) // a is a Float. Return rounded value.
Not dependent on Java Math.round() types
You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);
, you just need to get rid of default sum(max_count)
. No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL
as the value for every cell in that column.
So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.
You also have the option to always COALESCE
the column to your desired default and leave it NULL
for now. This option fails when you want NULL
to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE
.
If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.
I assume you want to pass the Order ID in. So:
CREATE PROCEDURE [dbo].[Procedure_Name]
(
@OrderID INT
) AS
BEGIN
Declare @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END
You can also use the struct module to do this:
>>> struct.unpack("<L", "y\xcc\xa6\xbb")[0]
3148270713L
This is what I did:
Very simply put:
=IF(C7>100,"Profit",IF(C7=100,"Quota Met","Loss"))
The first IF
Statement, if true will input Profit, and if false will lead on to the next IF
statement and so forth :)
I only have basic formula knowledge but it's working so I will accept I am right!
You can sort an array using usort function.
$array = array(
array('price'=>'1000.50','product'=>'product 1'),
array('price'=>'8800.50','product'=>'product 2'),
array('price'=>'200.0','product'=>'product 3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
usort($array, "cmp");
print_r($array);
Output :
Array
(
[0] => Array
(
[price] => 134.50
[product] => product 1
)
[1] => Array
(
[price] => 2033.0
[product] => product 3
)
[2] => Array
(
[price] => 8340.50
[product] => product 2
)
)
Try this
ALTER TABLE table_name ALTER COLUMN col_name data_type NOT NULL;
You can also use printf style of formatting arguments. It is available in at least Chrome, Firefox/Firebug and node.js.
var name = prompt("what is your name?");
console.log("story %s story", name);
It also supports %d for formatting numbers
You can use the following method which uses Jackson library
public static <T> List<T> convertToList(String jsonString, Class<T> target) {
if(StringUtils.isEmpty(jsonString)) return List.of();
return new ObjectMapper().readValue(jsonString, new ObjectMapper().getTypeFactory().
constructCollectionType(List.class, target));
} catch ( JsonProcessingException | JSONException e) {
e.printStackTrace();
return List.of();
}
}
There is no such thing as importing in MS SQL. I understand what you mean. It is so simple. Whenever you get/have a something.SQL file, you should just double click and it will directly open in your MS SQL Studio.
In MinGW, I had to install the following things:
Basic Setup -> mingw32-base
Basic Setup -> mingw32-gcc-g++
Basic Setup -> msys-base
And in Eclipse, go to
Windows -> Preferences -> C/C++ -> Build -> Environment
And set the following environment variables (with "Append variables to native environment" option set):
MINGW_HOME C:\MinGW
PATH C:\MinGW\bin;C:\MinGW\msys\1.0\bin
Click "Apply" and then "OK".
This worked for me, as far as I can tell.
What about -mmin
?
find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
-exec rm -f {} \;
From man find:
-mmin n File's data was last modified n minutes ago.
Also, make sure to test this first!
... -exec echo rm -f '{}' \; ^^^^ Add the 'echo' so you just see the commands that are going to get run instead of actual trying them first.
match_parent
is not supported by ConstraintLayout
. Set width to 0dp
to let it match constraints.