You should be able to do that with the Batch Task plugin.
An alternative can also be Post build task plugin.
PHP syntax is little different in case of concatenation from JavaScript.
Instead of (+) plus
a (.) period
is used for string concatenation.
<?php
$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
$selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
$selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;
?>
Your output is correct. Denote the white characters of " Hello" and " This" at the beginning.
Another issue is with your methodology. Use the Arrays.sort()
method:
String[] strings = { " Hello ", " This ", "Is ", "Sorting ", "Example" };
Arrays.sort(strings);
Output:
Hello
This
Example
Is
Sorting
Here the third element of the array "is" should be "Is", otherwise it will come in last after sorting. Because the sort method internally uses the ASCII value to sort elements.
add list using
<asp:ListItem Value="United States" Text="Canada"></asp:ListItem>
and then try
DropDownList1.SelectedItem.Text
I found your mistake.
<asp:ListItem>United States</asp:ListItem>
change this to
<asp:ListItem>United States1</asp:ListItem>
Then you will got the actual value.
What was the issue is, there are two same values in your dropdown, when page postback, it take first value as selected and give the result accordingly. if you noticed when after postback United State Value is selected
Slightly getting away from the original question, but I found an answer to Stack Overflow question Get int value from enum useful. Create a static class with public const int
properties, allowing you to easily collect together a bunch of related int
constants, and then not have to cast them to int
when using them.
public static class Question
{
public static readonly int Role = 2;
public static readonly int ProjectFunding = 3;
public static readonly int TotalEmployee = 4;
public static readonly int NumberOfServers = 5;
public static readonly int TopBusinessConcern = 6;
}
Obviously, some of the enum type functionality will be lost, but for storing a bunch of database id constants, it seems like a pretty tidy solution.
You can just target the id directly:
var value = $('#b').val();
If you have more than one element with that id in the same page, it won't work properly anyway. You have to make sure that the id is unique.
If you actually are using the code for different pages, and only want to find the element on those pages where the id:s are nested, you can just use the descendant operator, i.e. space:
var value = $('#a #b').val();
use isinstance(v, type_name)
or type(v) is type_name
or type(v) == type_name
,
where type_name can be one of the following:
and, of course,
The {{variable}}
is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text.
Having said that, you can put this kind of substitution into your JavaScript.
<script type="text/javascript">
var a = "{{someDjangoVariable}}";
</script>
This gives you "dynamic" javascript.
void foo<TOne, TTwo>()
where TOne : BaseOne
where TTwo : BaseTwo
More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx
corona is nice. From the tutorial:
corona::Image* image = corona::OpenImage("img.jpg", corona::PF_R8G8B8A8);
if (!image) {
// error!
}
int width = image->getWidth();
int height = image->getHeight();
void* pixels = image->getPixels();
// we're guaranteed that the first eight bits of every pixel is red,
// the next eight bits is green, and so on...
typedef unsigned char byte;
byte* p = (byte*)pixels;
for (int i = 0; i < width * height; ++i) {
byte red = *p++;
byte green = *p++;
byte blue = *p++;
byte alpha = *p++;
}
pixels would be a one dimensional array, but you could easily convert a given x and y position to a position in a 1D array. Something like pos = (y * width) + x
Improving on the answer of @Adiii - It Will Cleanup The Phone Number and Remove All Duplicates
Declare a Global Variable
// Hash Maps
Map<String, String> namePhoneMap = new HashMap<String, String>();
Then Use The Function Below
private void getPhoneNumbers() {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
// Loop Through All The Numbers
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Cleanup the phone number
phoneNumber = phoneNumber.replaceAll("[()\\s-]+", "");
// Enter Into Hash Map
namePhoneMap.put(phoneNumber, name);
}
// Get The Contents of Hash Map in Log
for (Map.Entry<String, String> entry : namePhoneMap.entrySet()) {
String key = entry.getKey();
Log.d(TAG, "Phone :" + key);
String value = entry.getValue();
Log.d(TAG, "Name :" + value);
}
phones.close();
}
Remember in the above example the key is phone number and value is a name so read your contents like 998xxxxx282->Mahatma Gandhi instead of Mahatma Gandhi->998xxxxx282
Can I recommend doing it this way, define your test like this:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {
@Test
public void testContext(){
}
@Configuration
@PropertySource("classpath:/myprops.properties")
@ImportResource({"classpath:context.xml" })
public static class MyContextConfiguration{
}
}
with the following content in myprops.properties file:
spring.profiles.active=localtest
With this your second properties file should get resolved:
META-INF/spring/config_${spring.profiles.active}.properties
I'm the maintainer of Mongoose. findById()
is a built-in method on Mongoose models. findById(id)
is equivalent to findOne({ _id: id })
, with one caveat: findById()
with 0 params is equivalent to findOne({ _id: null })
.
You can read more about findById()
on the Mongoose docs and this findById()
tutorial.
My favorite:
https://inloop.github.io/sqlite-viewer/
No installation needed. Just drop the file.
i just found this site that give a cool themes for the select box http://gregfranko.com/jquery.selectBoxIt.js/
and you can try this themes if your problem with the overall look blue - yellow - grey
MSDeploy can migrate all content, config, etc. that is what the IIS team recommends. http://www.iis.net/extensions/WebDeploymentTool
To create a package, run the following command (replace Default Web Site with your web site name):
msdeploy.exe -verb:sync -source:apphostconfig="Default Web Site" -dest:package=c:\dws.zip > DWSpackage7.log
To restore the package, run the following command:
msdeploy.exe -verb:sync -source:package=c:\dws.zip -dest:apphostconfig="Default Web Site" > DWSpackage7.log
back to 2017:
use URL.createObjectURL( file ) to create local link to file system that user select;
don't forgot to free memory by using URL.revokeObjectURL()
You could use two separate configs. One as the input with optional properties (that will have default values), and another with only the required properties. This can be made convenient with &
and Required
:
interface DefaultedFuncConfig {
b?: boolean;
}
interface MandatoryFuncConfig {
a: boolean;
}
export type FuncConfig = MandatoryFuncConfig & DefaultedFuncConfig;
export const func = (config: FuncConfig): Required<FuncConfig> => ({
b: true,
...config
});
// will compile
func({ a: true });
func({ a: true, b: true });
// will error
func({ b: true });
func({});
On linux, /etc/apache2/mods-enabled/php5.conf dans php5.load
exists. If not, enables this modules (may require to sudo apt-get install libapache2-mod-php5
).
With MVC data transfer objects are often used to map domain models to simpler objects that will ultimately get displayed by the view.
From Wikipedia:
Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.
You can raise a notice in Postgres
as follows:
raise notice 'Value: %', deletedContactId;
Read here
The most upvoted Override push method solution by @canon has some side-effects that were inconvenient in my case:
It makes the push property descriptor different (writable
and configurable
should be set true
instead of false
), which causes exceptions in a later point.
It raises the event multiple times when push()
is called once with multiple arguments (such as myArray.push("a", "b")
), which in my case was unnecessary and bad for performance.
So this is the best solution I could find that fixes the previous issues and is in my opinion cleaner/simpler/easier to understand.
Object.defineProperty(myArray, "push", {
configurable: true,
enumerable: false,
writable: true, // Previous values based on Object.getOwnPropertyDescriptor(Array.prototype, "push")
value: function (...args)
{
let result = Array.prototype.push.apply(this, args); // Original push() implementation based on https://github.com/vuejs/vue/blob/f2b476d4f4f685d84b4957e6c805740597945cde/src/core/observer/array.js and https://github.com/vuejs/vue/blob/daed1e73557d57df244ad8d46c9afff7208c9a2d/src/core/util/lang.js
RaiseMyEvent();
return result; // Original push() implementation
}
});
Please see comments for my sources and for hints on how to implement the other mutating functions apart from push: 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'.
I think this will help
<directoryBrowse enabled="false" />
<defaultDocument>
<files>
<clear />
<add value="index.aspx" />
<add value="Default.htm" />
<add value="Default.asp" />
<add value="index.htm" />
<add value="index.html" />
<add value="iisstart.htm" />
<add value="default.aspx" />
<add value="index.php" />
</files>
</defaultDocument>
</system.webServer>
A wildcard *
can be translated as .*
or .*?
regex pattern.
You might need to use a singleline mode to match newline symbols, and in this case, you can use (?s)
as part of the regex pattern.
You can set it for the whole or part of the pattern:
X* = > @"X(?s:.*)"
*X = > @"(?s:.*)X"
*X* = > @"(?s).*X.*"
*X*YZ* = > @"(?s).*X.*YZ.*"
X*YZ*P = > @"(?s:X.*YZ.*P)"
I've created a clearable textbox in just CSS. It requires no javascript code to make it work
below is the demo link
Try renaming your 'proguard-rules.txt' file to 'proguard-android.txt' and remove the reference to 'proguard-rules.txt' in your gradle file. The getDefaultProguardFile(...)
call references a different default proguard file, one provided by Google and not that in your project. So remove this as well, so that here the gradle file reads:
buildTypes {
release {
runProguard true
proguardFile 'proguard-android.txt'
}
}
You did not provide your validate.php
code so I'm confused. You have to pass the data in JSON Format when when mail is success.
You can use json_encode(); PHP function for that.
Add json_encdoe
in validate.php in last
mail($to, $subject, $message, $headers);
echo json_encode(array('success'=>'true'));
JS Code
success: function(data){
if(data.success == true){
alert('success');
}
Hope it works
Just specify it in shared.loader
or common.loader
property of /conf/catalina.properties
.
If you are using jQuery, use the jQuery.trim()
function. For example:
if( jQuery.trim(StringVariable) == '')
After 27 years, I too, am uncomfortable developing in an IDE. I tried these suggestions (above) - and probably just didn't follow everything right -- so I did a web-search and found what worked for me at 'http://incise.org/android-development-on-the-command-line.html'.
The answer seemed to be a combination of all the answers above (please tell me if I'm wrong and accept my apologies if so).
As mentioned above, eclipse/adt does not create the necessary ant files. In order to compile without eclipse IDE (and without creating ant scripts):
1) Generate build.xml in your top level directory:
android list targets (to get target id used below)
android update project --target target_id --name project_name --path top_level_directory
** my sample project had a target_id of 1 and a project name of 't1', and
I am building from the top level directory of project
my command line looks like android update project --target 1 --name t1 --path `pwd`
2) Next I compile the project. I was a little confused by the request to not use 'ant'. Hopefully -- requester meant that he didn't want to write any ant scripts. I say this because the next step is to compile the application using ant
ant target
this confused me a little bit, because i thought they were talking about the
android device, but they're not. It's the mode (debug/release)
my command line looks like ant debug
3) To install the apk onto the device I had to use ant again:
ant target install
** my command line looked like ant debug install
4) To run the project on my android phone I use adb.
adb shell 'am start -n your.project.name/.activity'
** Again there was some confusion as to what exactly I had to use for project
My command line looked like adb shell 'am start -n com.example.t1/.MainActivity'
I also found that if you type 'adb shell' you get put to a cli shell interface
where you can do just about anything from there.
3A) A side note: To view the log from device use:
adb logcat
3B) A second side note: The link mentioned above also includes instructions for building the entire project from the command.
Hopefully, this will help with the question. I know I was really happy to find anything about this topic here.
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
Try to do an UPDATE. If it doesn't modify any row that means it didn't exist, so do an insert. Obviously, you do this inside a transaction.
You can of course wrap this in a function if you don't want to put the extra code on the client side. You also need a loop for the very rare race condition in that thinking.
There's an example of this in the documentation: http://www.postgresql.org/docs/9.3/static/plpgsql-control-structures.html, example 40-2 right at the bottom.
That's usually the easiest way. You can do some magic with rules, but it's likely going to be a lot messier. I'd recommend the wrap-in-function approach over that any day.
This works for single row, or few row, values. If you're dealing with large amounts of rows for example from a subquery, you're best of splitting it into two queries, one for INSERT and one for UPDATE (as an appropriate join/subselect of course - no need to write your main filter twice)
document.getElementById("xyz").style.padding-top = '10px';
will be
document.getElementById("xyz").style["paddingTop"] = '10px';
The answer given by @ray above works perfectly, but make sure you are using the right path to open up the file. If you right click on your icon and click properties, you should see where the actual path is, just copy past that and it should work.
This is a simple Node.js solution that works in the new version 4.x (maybe also 3.x) of Selenium.
const { Builder } = require('selenium-webdriver')
const chrome = require('selenium-webdriver/chrome');
let driver = await new Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless()).build()
await driver.get('https://example.com')
const { Builder } = require('selenium-webdriver')
const firefox = require('selenium-webdriver/firefox');
let driver = await new Builder().forBrowser('firefox').setFirefoxOptions(new firefox.Options().headless()).build()
await driver.get('https://example.com')
The whole thing just runs in the background. It is exactly what we want.
Judging from the error message the value of i was the empty string when you executed it, not 0.
I did this:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AutoDealer</title>
<style>
.container{
width: 860px;
height: 1074px;
margin-right: auto;
margin-left: auto;
border: 1px solid red;
}
.nav{
}
.wrapper{
display: block;
overflow: hidden;
border: 1px solid green;
}
.otherWrapper{
display: block;
overflow: hidden;
border: 1px solid green;
float:left;
}
.left{
width: 399px;
float: left;
background-color: pink;
}
.bottom{
clear: both;
width: 399px;
background-color: yellow;
}
.right{
height:350px;
width: 449px;
overflow: hidden;
background-color: blue;
overflow: hidden;
float:right;
}
</style>
</head>
<body>
<div class="container">
<div class="nav"></div>
<div class="wrapper">
<div class="otherWrapper">
<div class="left">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies aliquet tellus sit amet ultrices. Sed faucibus, nunc vitae accumsan laoreet, enim metus varius nulla, ac ultricies felis ante venenatis justo. In hac habitasse platea dictumst. In cursus enim nec urna molestie, id mattis elit mollis. In sed eros eget nibh congue vehicula. Nunc vestibulum enim risus, sit amet suscipit dui auctor et. Morbi orci magna, accumsan at turpis a, scelerisque congue eros. Morbi non mi vel nibh varius blandit sed et urna.</p>
</div>
<div class="bottom">
<p>ucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesq</p></div>
</div>
<div class="right">
<p>Quisque vulputate mi id turpis luctus, quis laoreet nisi vestibulum. Morbi facilisis erat vitae augue ornare convallis. Fusce sit amet magna rutrum, hendrerit purus vitae, congue justo. Nam non mi eget purus ultricies lacinia. Fusce ante nisl, efficitur venenatis urna ut, pellentesque egestas nisl. In ut faucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesque maximus. Quisque a tempus lectus.</p>
</div>
</div>
</div>
</body>
So basically I just made another div to wrap the pink and yellow, and I make that div have a float:left on it. The blue div has a float:right on it.
You can do it via cmd.
Open cmd in administrator mode. Change directory to C:/xampp/apache/bin. Run the command as httpd.exe -k install
.
Your Apache server service will be installed. You can start it from services.
Change directory to C:/xampp/mysql/bin. Run the command as mysqld --install
. Your MySQL service will be installed. You can start it from services.
Note: Make sure the selected Apache and MySQL services are set to start automatically.
You're done. There isn't any need to launch the XAMPP control panel
I think your date data should look like 2013-08-14.
<?php
$yrdata= strtotime('2013-08-14');
echo date('M-Y', $yrdata);
?>
// Output is Aug-2013
I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.
If you want to count specific words
function countWholeWords(text, keyword) {
const times = text.match(new RegExp(`\\b${keyword}\\b`, 'gi'));
if (times) {
console.log(`${keyword} occurs ${times.length} times`);
} else {
console.log(keyword + " does not occurs")
}
}
const text = `
In a professional context it often happens that private or corporate clients corder a publication to be
made and presented with the actual content still not being ready. Think of a news blog that's
filled with content hourly on the day of going live. However, reviewers tend to be distracted
by comprehensible content, say, a random text copied from a newspaper or the internet.
`
const wordsYouAreLookingFor = ["random", "cat", "content", "reviewers", "dog", "with"]
wordsYouAreLookingFor.forEach((keyword) => countWholeWords(text, keyword));
// random occurs 1 times
// cat does not occurs
// content occurs 3 times
// reviewers occurs 1 times
// dog does not occurs
// with occurs 2 times
As of MySql 5.1 version reference
BIT(M) = approximately (M+7)/8 bytes,
BIT(1) = (1+7)/8 = 1 bytes (8 bits)
=========================================================================
TINYINT(1) take 8 bits.
https://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html#data-types-storage-reqs-numeric
Adding a StreamHandler without arguments goes to stderr instead of stdout. If some other process has a dependency on the stdout dump (i.e. when writing an NRPE plugin), then make sure to specify stdout explicitly or you might run into some unexpected troubles.
Here's a quick example reusing the assumed values and LOGFILE from the question:
import logging
from logging.handlers import RotatingFileHandler
from logging import handlers
import sys
log = logging.getLogger('')
log.setLevel(logging.DEBUG)
format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(format)
log.addHandler(ch)
fh = handlers.RotatingFileHandler(LOGFILE, maxBytes=(1048576*5), backupCount=7)
fh.setFormatter(format)
log.addHandler(fh)
use gcc -B lib_path_containing_crt?.o
Think of HTTP as a person(A) who has SHORT TERM MEMORY LOSS and forgets every person as soon as that person goes out of sight.
Now, to remember different persons, A takes a photo of that person and keeps it. Each Person's pic has an ID number. When that person comes again in sight, that person tells it's ID number to A and A finds their picture by ID number. And voila !!, A knows who is that person.
Same is with HTTP. It is suffering from SHORT TERM MEMORY LOSS. It uses Sessions to record everything you did while using a website, and then, when you come again, it identifies you with the help of Cookies(Cookie is like a token). Picture is the Session here, and ID is the Cookie here.
I would not typecast away the const in the last line since it is there for a reason. If you can't live with a const char* then you better copy the char array like:
char* char_type = new char[temp_str.length()];
strcpy(char_type, temp_str.c_str());
Couldn't you use the server variables to do this?
Or would this work?:
unset($_GET['page']);
$url = $_SERVER['SCRIPT_NAME'] ."?".http_build_query($_GET);
Just a thought.
"Editor's" note: This post may contain outdated information. Please see comments and this question regarding changes in Git since 1.6.1.
Symlinked directories:
It's important to note what happens when there is a directory which is a soft link. Any Git pull with an update removes the link and makes it a normal directory. This is what I learnt hard way. Some insights here and here.
Example
Before
ls -l
lrwxrwxrwx 1 admin adm 29 Sep 30 15:28 src/somedir -> /mnt/somedir
git add/commit/push
It remains the same
After git pull
AND some updates found
drwxrwsr-x 2 admin adm 4096 Oct 2 05:54 src/somedir
I know this is old but you can directly browse it using this paths..
SQL Server 2019 C:\Windows\SysWOW64\SQLServerManager15.msc
SQL Server 2017 C:\Windows\SysWOW64\SQLServerManager14.msc
SQL Server 2016 C:\Windows\SysWOW64\SQLServerManager13.msc
SQL Server 2014 C:\Windows\SysWOW64\SQLServerManager12.msc
SQL Server 2012 C:\Windows\SysWOW64\SQLServerManager11.msc
SQL Server 2008 C:\Windows\SysWOW64\SQLServerManager10.msc
source is from ms site https://msdn.microsoft.com/en-us/library/ms174212.aspx
One can also specify %systemroot%
for the path of Windows directory. For example:
SQL Server 2019: %systemroot%\SysWOW64\SQLServerManager15.msc
You can also install R from this page:
https://cran.r-project.org/bin/macosx/
It works out of the box
For me the following solution worked Unable to stop MySQL on OS X 10.10
To stop the auto start I used:
sudo launchctl unload -w /Library/LaunchDaemons/com.mysql.mysql.plist
And to kill the service I used:
sudo pkill mysqld
One possible solution is to add a class to every option
<select name="export_type" id="export_type">
<option class="export_option" value="pdf">PDF</option>
<option class="export_option" value="xlsx">Excel</option>
<option class="export_option" value="docx">DocX</option>
</select>
and then use the click handler for this class
$(document).ready(function () {
$(".export_option").click(function (e) {
//alert('click');
});
});
UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome. Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.
If you are using eclipse there is a "Skip Tests" checkbox on the configuration page.
Run configurations ? Maven Build ? New ? Main tab ? Skip Tests
.process-list:after{
content: "\2191";
position: absolute;
top:50%;
right:-8px;
background-color: #ea1f41;
width:35px;
height: 35px;
border:2px solid #ffffff;
border-radius: 5px;
color: #ffffff;
z-index: 10000;
-webkit-transform: rotate(50deg) translateY(-50%);
-moz-transform: rotate(50deg) translateY(-50%);
-ms-transform: rotate(50deg) translateY(-50%);
-o-transform: rotate(50deg) translateY(-50%);
transform: rotate(50deg) translateY(-50%);
}
you can check this code . i hope you will easily understand.
It took me a little more than just one method in the struct like the swift book called for but I set up next functions in the enum
. I would have used a protocol I'm not sure why but having rank set as int messes it up.
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "Queen"
case .King:
return "King"
default:
return String(self.toRaw())
}
}
mutating func next() -> Rank {
var rank = self
var rawrank = rank.toRaw()
var nrank: Rank = self
rawrank = rawrank + 1
if let newRank = Rank.fromRaw(rawrank) {
println("\(newRank.simpleDescription())")
nrank = newRank
} else {
return self
}
return nrank
}
}
enum Suit {
case Spades, Hearts, Diamonds, Clubs
func color() -> String {
switch self {
case .Spades, .Clubs:
return "black"
default:
return "red"
}
}
func simpleDescription() -> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
mutating func next() -> Suit {
switch self {
case .Spades:
return Hearts
case .Hearts:
return Diamonds
case .Diamonds:
return Clubs
case .Clubs:
return Spades
}
}
}
struct Card {
var rank: Rank
var suit: Suit
func deck() -> Card[] {
var tRank = self.rank
var tSuit = self.suit
let tcards = 52 // we start from 0
var cards: Card[] = []
for i in 0..tcards {
var card = Card(rank: tRank, suit: tSuit)
cards.append(card)
tRank = tRank.next()
tSuit = tSuit.next()
}
return cards
}
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
var card = Card(rank: .Ace, suit: .Spades)
var deck = card.deck()
I used a little general knowledge but that can be easily rectified by multiplying suits by rank (if you aren't using a standard deck of cards and you'd have to change the enums accordingly and if basically just steps through the different enums. To save time I used ranks rawValues
you could do the same for suits if you wanted. However, the example did not have it so I decided to figure it out without changing suits rawValue
I agree with many here, but I also think it depends.
Recently I did this code:
private void animate(FlowLayoutPanel element, int start, int end)
{
bool asc = end > start;
element.Show();
while (start != end) {
start += asc ? 1 : -1;
element.Height = start;
Thread.Sleep(1);
}
if (!asc)
{
element.Hide();
}
element.Focus();
}
It was a simple animate-function, and I used Thread.Sleep
on it.
My conclusion, if it does the job, use it.
The sqlite team published an article explaining when to use sqlite that is great read. Basically, you want to avoid using sqlite when you have a lot of write concurrency or need to scale to terabytes of data. In many other cases, sqlite is a surprisingly good alternative to a "traditional" database such as MySQL.
It seems that all other answers assume the path given to the function is always a directory. This variant works to remove directories as well as single files:
/**
* Recursively delete a file or directory. Use with care!
*
* @param string $path
*/
function recursiveRemove($path) {
if (is_dir($path)) {
foreach (scandir($path) as $entry) {
if (!in_array($entry, ['.', '..'])) {
recursiveRemove($path . DIRECTORY_SEPARATOR . $entry);
}
}
rmdir($path);
} else {
unlink($path);
}
}
Most succinctly, this forces content to wrap inside of a "pre" tag without breaking words. Cheers!
pre {
white-space: pre-wrap;
word-break: keep-all
}
Actually you have selected Android from the tab change it to project.
Steps
Then you will found all folders.
You are looking for JavaScript's String
method substring
e.g.
'Hiya how are you'.substring(0,8);
Which returns the string starting at the first character and finishing before the 9th character - i.e. 'Hiya how'.
If using a StackTraceElement, use:
String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
System.out.println(simpleClassName);
If you connect the DidEndOnExit event of the text field to an action (IBAction) in InterfaceBuilder, it will be messaged when the user dismisses the keyboard (with the return key) and the sender will be a reference to the UITextField that fired the event.
For example:
-(IBAction)userDoneEnteringText:(id)sender
{
UITextField theField = (UITextField*)sender;
// do whatever you want with this text field
}
Then, in InterfaceBuilder, link the DidEndOnExit event of the text field to this action on your controller (or whatever you're using to link events from the UI). Whenever the user enters text and dismisses the text field, the controller will be sent this message.
I find this at google: https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html
It mentiones that we need to
gradle-wrapper.properties
by distributionUrl=\https\://services.gradle.org/distributions/gradle-4.1-all.zip
repositories { google() }
and dependencies { classpath 'com.android.tools.build:gradle:3.0.0-beta7' }
You may require to have Android Studio 3
I use the filter solution above, for ie8. However.. In order to solve the freezing links problem , do also the following:
background: no-repeat center center fixed\0/; /* IE8 HACK */
This has solved the frozen links problem for me.
If you are not so keen on having to decorate code with Attributes as I am, esp when you cant tell at compile time what will happen here is my solution.
Using the Javascript Serializer
public static class JsonSerializerExtensions
{
public static string ToJsonString(this object target,bool ignoreNulls = true)
{
var javaScriptSerializer = new JavaScriptSerializer();
if(ignoreNulls)
{
javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(target.GetType(), true) });
}
return javaScriptSerializer.Serialize(target);
}
public static string ToJsonString(this object target, Dictionary<Type, List<string>> ignore, bool ignoreNulls = true)
{
var javaScriptSerializer = new JavaScriptSerializer();
foreach (var key in ignore.Keys)
{
javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(key, ignore[key], ignoreNulls) });
}
return javaScriptSerializer.Serialize(target);
}
}
public class PropertyExclusionConverter : JavaScriptConverter
{
private readonly List<string> propertiesToIgnore;
private readonly Type type;
private readonly bool ignoreNulls;
public PropertyExclusionConverter(Type type, List<string> propertiesToIgnore, bool ignoreNulls)
{
this.ignoreNulls = ignoreNulls;
this.type = type;
this.propertiesToIgnore = propertiesToIgnore ?? new List<string>();
}
public PropertyExclusionConverter(Type type, bool ignoreNulls)
: this(type, null, ignoreNulls){}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { this.type })); }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var result = new Dictionary<string, object>();
if (obj == null)
{
return result;
}
var properties = obj.GetType().GetProperties();
foreach (var propertyInfo in properties)
{
if (!this.propertiesToIgnore.Contains(propertyInfo.Name))
{
if(this.ignoreNulls && propertyInfo.GetValue(obj, null) == null)
{
continue;
}
result.Add(propertyInfo.Name, propertyInfo.GetValue(obj, null));
}
}
return result;
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException(); //Converter is currently only used for ignoring properties on serialization
}
}
I don't know if I'd call it production-ready, but there's jGABL.
It is called Expression Bodied Member and it was introduced in C# 6. It is merely syntactic sugar over a get
only property.
It is equivalent to:
public int MaxHealth { get { return Memory[Address].IsValid ?
Memory[Address].Read<int>(Offs.Life.MaxHp) : 0; }
An equivalent of a method declaration is avaliable:
public string HelloWorld() => "Hello World";
Mainly allowing you shortening of boilerplate.
it is better that you use the following query to get all column names easily
Show columns from tablename
@Prasand Kumar, here's a complete sort routine based on Prasand's concepts:
Public Sub ArrayListSort(ByRef SortArray As Variant)
'
'Uses the sort capabilities of a System.Collections.ArrayList object to sort an array of values of any simple
'data-type.
'
'AUTHOR: Peter Straton
'
'CREDIT: Derived from Prasand Kumar's post at: https://stackoverflow.com/questions/152319/vba-array-sort-function
'
'*************************************************************************************************************
Static ArrayListObj As Object
Dim i As Long
Dim LBnd As Long
Dim UBnd As Long
LBnd = LBound(SortArray)
UBnd = UBound(SortArray)
'If necessary, create the ArrayList object, to be used to sort the specified array's values
If ArrayListObj Is Nothing Then
Set ArrayListObj = CreateObject("System.Collections.ArrayList")
Else
ArrayListObj.Clear 'Already allocated so just clear any old contents
End If
'Add the ArrayList elements from the array of values to be sorted. (There appears to be no way to do this
'using a single assignment statement.)
For i = LBnd To UBnd
ArrayListObj.Add SortArray(i)
Next i
ArrayListObj.Sort 'Do the sort
'Transfer the sorted ArrayList values back to the original array, which can be done with a single assignment
'statement. But the result is always zero-based so then, if necessary, adjust the resulting array to match
'its original index base.
SortArray = ArrayListObj.ToArray
If LBnd <> 0 Then ReDim Preserve SortArray(LBnd To UBnd)
End Sub
How about extending a jquery for this?
(function () {
var ev = new $.Event('remove'),
orig = $.fn.remove;
var evap = new $.Event('append'),
origap = $.fn.append;
$.fn.remove = function () {
$(this).trigger(ev);
return orig.apply(this, arguments);
}
$.fn.append = function () {
$(this).trigger(evap);
return origap.apply(this, arguments);
}
})();
$(document).on('append', function (e) { /*write your logic here*/ });
$(document).on('remove', function (e) { /*write your logic here*/ });
Jquery 1.9+ has built support for this(I have heard not tested).
DISCLAIMER: I'm the author of gitchangelog of which I'll be speaking in the following.
TL;DR: You might want to check gitchangelog's own changelog or the ascii output that generated the previous.
If you want to generate a changelog from your git history, you'll probably have to consider:
Optionaly you might want some categorization (new things, changes, bugfixes)...
With all this in mind, I created and use gitchangelog. It's meant to leverage a git commit message convention to achieve all of the previous goals.
Having a commit message convention is mandatory to create a nice changelog (with or without using gitchangelog
).
commit message convention
The following are suggestions to what might be useful to think about adding in your commit messages.
You might want to separate roughly your commits into big sections:
Additionally, you could want to tag some commits:
Try to write your commit message by targeting users (functionality) as often as you can.
example
This is standard git log --oneline
to show how these information could be stored::
* 5a39f73 fix: encoding issues with non-ascii chars.
* a60d77a new: pkg: added ``.travis.yml`` for automated tests.
* 57129ba new: much greater performance on big repository by issuing only one shell command for all the commits. (fixes #7)
* 6b4b267 chg: dev: refactored out the formatting characters from GIT.
* 197b069 new: dev: reverse ``natural`` order to get reverse chronological order by default. !refactor
* 6b891bc new: add utf-8 encoding declaration !minor
So if you've noticed, the format I chose is:
{new|chg|fix}: [{dev|pkg}:] COMMIT_MESSAGE [!{minor|refactor} ... ]
To see an actual output result, you could look at the end of the PyPI page of gitchangelog
To see a full documentation of my commit message convention you can see the reference file gitchangelog.rc.reference
How to generate exquisite changelog from this
Then, it's quite easy to make a complete changelog. You could make your own script quite quickly, or use gitchangelog
.
gitchangelog
will generate a full changelog (with sectioning support as New
, Fix
...), and is reasonably configurable to your own committing conventions. It supports any type of output thanks to templating through Mustache
, Mako templating
, and has a default legacy engine written in raw python ; all current 3 engines have examples of how to use them and can output changelog's as the one displayed on the PyPI page of gitchangelog.
I'm sure you know that there are plenty of other git log
to changelog
tools out there also.
Hi I found the easiest way to do this.
Done!
I have used paramiko a bunch (nice) and pxssh (also nice). I would recommend either. They work a little differently but have a relatively large overlap in usage.
If anyone wants AutoClosingMessageBox in c++ I have implemented the equivalent code here is the link to gists
static intptr_t MessageBoxHookProc(int nCode, intptr_t wParam, intptr_t lParam)
{
if (nCode < 0)
return CallNextHookEx(hHook, nCode, wParam, lParam);
auto msg = reinterpret_cast<CWPRETSTRUCT*>(lParam);
auto hook = hHook;
//Hook Messagebox on Initialization.
if (!hookCaption.empty() && msg->message == WM_INITDIALOG)
{
int nLength = GetWindowTextLength(msg->hwnd);
char* text = new char[captionLen + 1];
GetWindowText(msg->hwnd, text, captionLen + 1);
//If Caption window found Unhook it.
if (hookCaption == text)
{
hookCaption = string("");
SetTimer(msg->hwnd, (uintptr_t)timerID, hookTimeout, (TIMERPROC)hookTimer);
UnhookWindowsHookEx(hHook);
hHook = 0;
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
The same, Server.UrlEncode()
calls HttpUtility.UrlEncode()
Process Spawning Manager
Sure, technically these are processes, and this program should really be called a process spawning manager, but this is only due to the way that BASH works when it forks using the ampersand, it uses the fork() or perhaps clone() system call which clones into a separate memory space, rather than something like pthread_create() which would share memory. If BASH supported the latter, each "sequence of execution" would operate just the same and could be termed to be traditional threads whilst gaining a more efficient memory footprint. Functionally however it works the same, though a bit more difficult since GLOBAL variables are not available in each worker clone hence the use of the inter-process communication file and the rudimentary flock semaphore to manage critical sections. Forking from BASH of course is the basic answer here but I feel as if people know that but are really looking to manage what is spawned rather than just fork it and forget it. This demonstrates a way to manage up to 200 instances of forked processes all accessing a single resource. Clearly this is overkill but I enjoyed writing it so I kept on. Increase the size of your terminal accordingly. I hope you find this useful.
ME=$(basename $0)
IPC="/tmp/$ME.ipc" #interprocess communication file (global thread accounting stats)
DBG=/tmp/$ME.log
echo 0 > $IPC #initalize counter
F1=thread
SPAWNED=0
COMPLETE=0
SPAWN=1000 #number of jobs to process
SPEEDFACTOR=1 #dynamically compensates for execution time
THREADLIMIT=50 #maximum concurrent threads
TPS=1 #threads per second delay
THREADCOUNT=0 #number of running threads
SCALE="scale=5" #controls bc's precision
START=$(date +%s) #whence we began
MAXTHREADDUR=6 #maximum thread life span - demo mode
LOWER=$[$THREADLIMIT*100*90/10000] #90% worker utilization threshold
UPPER=$[$THREADLIMIT*100*95/10000] #95% worker utilization threshold
DELTA=10 #initial percent speed change
threadspeed() #dynamically adjust spawn rate based on worker utilization
{
#vaguely assumes thread execution average will be consistent
THREADCOUNT=$(threadcount)
if [ $THREADCOUNT -ge $LOWER ] && [ $THREADCOUNT -le $UPPER ] ;then
echo SPEED HOLD >> $DBG
return
elif [ $THREADCOUNT -lt $LOWER ] ;then
#if maxthread is free speed up
SPEEDFACTOR=$(echo "$SCALE;$SPEEDFACTOR*(1-($DELTA/100))"|bc)
echo SPEED UP $DELTA%>> $DBG
elif [ $THREADCOUNT -gt $UPPER ];then
#if maxthread is active then slow down
SPEEDFACTOR=$(echo "$SCALE;$SPEEDFACTOR*(1+($DELTA/100))"|bc)
DELTA=1 #begin fine grain control
echo SLOW DOWN $DELTA%>> $DBG
fi
echo SPEEDFACTOR $SPEEDFACTOR >> $DBG
#average thread duration (total elapsed time / number of threads completed)
#if threads completed is zero (less than 100), default to maxdelay/2 maxthreads
COMPLETE=$(cat $IPC)
if [ -z $COMPLETE ];then
echo BAD IPC READ ============================================== >> $DBG
return
fi
#echo Threads COMPLETE $COMPLETE >> $DBG
if [ $COMPLETE -lt 100 ];then
AVGTHREAD=$(echo "$SCALE;$MAXTHREADDUR/2"|bc)
else
ELAPSED=$[$(date +%s)-$START]
#echo Elapsed Time $ELAPSED >> $DBG
AVGTHREAD=$(echo "$SCALE;$ELAPSED/$COMPLETE*$THREADLIMIT"|bc)
fi
echo AVGTHREAD Duration is $AVGTHREAD >> $DBG
#calculate timing to achieve spawning each workers fast enough
# to utilize threadlimit - average time it takes to complete one thread / max number of threads
TPS=$(echo "$SCALE;($AVGTHREAD/$THREADLIMIT)*$SPEEDFACTOR"|bc)
#TPS=$(echo "$SCALE;$AVGTHREAD/$THREADLIMIT"|bc) # maintains pretty good
#echo TPS $TPS >> $DBG
}
function plot()
{
echo -en \\033[${2}\;${1}H
if [ -n "$3" ];then
if [[ $4 = "good" ]];then
echo -en "\\033[1;32m"
elif [[ $4 = "warn" ]];then
echo -en "\\033[1;33m"
elif [[ $4 = "fail" ]];then
echo -en "\\033[1;31m"
elif [[ $4 = "crit" ]];then
echo -en "\\033[1;31;4m"
fi
fi
echo -n "$3"
echo -en "\\033[0;39m"
}
trackthread() #displays thread status
{
WORKERID=$1
THREADID=$2
ACTION=$3 #setactive | setfree | update
AGE=$4
TS=$(date +%s)
COL=$[(($WORKERID-1)/50)*40]
ROW=$[(($WORKERID-1)%50)+1]
case $ACTION in
"setactive" )
touch /tmp/$ME.$F1$WORKERID #redundant - see main loop
#echo created file $ME.$F1$WORKERID >> $DBG
plot $COL $ROW "Worker$WORKERID: ACTIVE-TID:$THREADID INIT " good
;;
"update" )
plot $COL $ROW "Worker$WORKERID: ACTIVE-TID:$THREADID AGE:$AGE" warn
;;
"setfree" )
plot $COL $ROW "Worker$WORKERID: FREE " fail
rm /tmp/$ME.$F1$WORKERID
;;
* )
;;
esac
}
getfreeworkerid()
{
for i in $(seq 1 $[$THREADLIMIT+1])
do
if [ ! -e /tmp/$ME.$F1$i ];then
#echo "getfreeworkerid returned $i" >> $DBG
break
fi
done
if [ $i -eq $[$THREADLIMIT+1] ];then
#echo "no free threads" >> $DBG
echo 0
#exit
else
echo $i
fi
}
updateIPC()
{
COMPLETE=$(cat $IPC) #read IPC
COMPLETE=$[$COMPLETE+1] #increment IPC
echo $COMPLETE > $IPC #write back to IPC
}
worker()
{
WORKERID=$1
THREADID=$2
#echo "new worker WORKERID:$WORKERID THREADID:$THREADID" >> $DBG
#accessing common terminal requires critical blocking section
(flock -x -w 10 201
trackthread $WORKERID $THREADID setactive
)201>/tmp/$ME.lock
let "RND = $RANDOM % $MAXTHREADDUR +1"
for s in $(seq 1 $RND) #simulate random lifespan
do
sleep 1;
(flock -x -w 10 201
trackthread $WORKERID $THREADID update $s
)201>/tmp/$ME.lock
done
(flock -x -w 10 201
trackthread $WORKERID $THREADID setfree
)201>/tmp/$ME.lock
(flock -x -w 10 201
updateIPC
)201>/tmp/$ME.lock
}
threadcount()
{
TC=$(ls /tmp/$ME.$F1* 2> /dev/null | wc -l)
#echo threadcount is $TC >> $DBG
THREADCOUNT=$TC
echo $TC
}
status()
{
#summary status line
COMPLETE=$(cat $IPC)
plot 1 $[$THREADLIMIT+2] "WORKERS $(threadcount)/$THREADLIMIT SPAWNED $SPAWNED/$SPAWN COMPLETE $COMPLETE/$SPAWN SF=$SPEEDFACTOR TIMING=$TPS"
echo -en '\033[K' #clear to end of line
}
function main()
{
while [ $SPAWNED -lt $SPAWN ]
do
while [ $(threadcount) -lt $THREADLIMIT ] && [ $SPAWNED -lt $SPAWN ]
do
WID=$(getfreeworkerid)
worker $WID $SPAWNED &
touch /tmp/$ME.$F1$WID #if this loops faster than file creation in the worker thread it steps on itself, thread tracking is best in main loop
SPAWNED=$[$SPAWNED+1]
(flock -x -w 10 201
status
)201>/tmp/$ME.lock
sleep $TPS
if ((! $[$SPAWNED%100]));then
#rethink thread timing every 100 threads
threadspeed
fi
done
sleep $TPS
done
while [ "$(threadcount)" -gt 0 ]
do
(flock -x -w 10 201
status
)201>/tmp/$ME.lock
sleep 1;
done
status
}
clear
threadspeed
main
wait
status
echo
i solved my problem with this:
<div class="d-flex justify-content-center"></div>
im using bootstrap with font awesome icons.
if you want to know more acess the link below: https://getbootstrap.com/docs/4.0/utilities/flex/
You can select a code snippet and use right click menu to choose the action "Execute Selection in console".
I tried all the solutions on here and none gave a clean 1px line. To achieve this do the following:
border: none; border-top: 1px dotted #000;
Alternatively:
border-top: 1px dotted #000; border-right: none; border-bottom: none; border-left: none;
suppose
alias command1='grep a <<<abc'
alias command2='grep x <<<abc'
alias command3='grep c <<<abc'
either
{ command1 1>/dev/null || { echo "cmd1 fail"; /bin/false; } } && echo "cmd1 succeed" &&
{ command2 1>/dev/null || { echo "cmd2 fail"; /bin/false; } } && echo "cmd2 succeed" &&
{ command3 1>/dev/null || { echo "cmd3 fail"; /bin/false; } } && echo "cmd3 succeed"
or
{ { command1 1>/dev/null && echo "cmd1 succeed"; } || { echo "cmd1 fail"; /bin/false; } } &&
{ { command2 1>/dev/null && echo "cmd2 succeed"; } || { echo "cmd2 fail"; /bin/false; } } &&
{ { command3 1>/dev/null && echo "cmd3 succeed"; } || { echo "cmd3 fail"; /bin/false; } }
yields
cmd1 succeed
cmd2 fail
Tedious it is. But the readability isn't bad.
Sometimes this happens because some library that you put in your code there isn't added, verify all libraries that you are using.
To add a new library in netbean:
Why not just inspect the generated markup, note the class on the button of choice and style it yourself?
while(rdr.Read())
{
string col=rdr["colName"].ToString();
}
it wil work
function getCityState($zip, $blnUSA = true) {
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";
$address_info = file_get_contents($url);
$json = json_decode($address_info);
$city = "";
$state = "";
$country = "";
if (count($json->results) > 0) {
//break up the components
$arrComponents = $json->results[0]->address_components;
foreach($arrComponents as $index=>$component) {
$type = $component->types[0];
if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
$city = trim($component->short_name);
}
if ($state == "" && $type=="administrative_area_level_1") {
$state = trim($component->short_name);
}
if ($country == "" && $type=="country") {
$country = trim($component->short_name);
if ($blnUSA && $country!="US") {
$city = "";
$state = "";
break;
}
}
if ($city != "" && $state != "" && $country != "") {
//we're done
break;
}
}
}
$arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);
die(json_encode($arrReturn));
}
MessageBox::Show
uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
$str = 'abcdef';
echo $str[0]; // a
In addition to the simple print answer, you can actually customise the print output through the use of the numpy.set_printoptions function.
Prerequisites:
>>> import numpy as np
>>> inf = np.float('inf')
>>> A = np.array([[0,1,4,inf,3],[1,0,2,inf,4],[4,2,0,1,5],[inf,inf,1,0,3],[3,4,5,3,0]])
The following option:
>>> np.set_printoptions(infstr="(infinity)")
Results in:
>>> print(A)
[[ 0. 1. 4. (infinity) 3.]
[ 1. 0. 2. (infinity) 4.]
[ 4. 2. 0. 1. 5.]
[(infinity) (infinity) 1. 0. 3.]
[ 3. 4. 5. 3. 0.]]
The following option:
>>> np.set_printoptions(formatter={'float': "\t{: 0.0f}\t".format})
Results in:
>>> print(A)
[[ 0 1 4 inf 3 ]
[ 1 0 2 inf 4 ]
[ 4 2 0 1 5 ]
[ inf inf 1 0 3 ]
[ 3 4 5 3 0 ]]
If you just want to have a specific string output for a specific array, the function numpy.array2string is also available.
What you need is the .form-inline
class. You need to be careful though, with the new .form.inline
class you have to specify the width for each control.
Take a look at this
<input type="password" id="byLast" class="bump25" autocomplete="new-password" onclick="this.type='text'" /> )
This worked for me
I faced exactly the same issue. My home drive mapped to a network drive. Also
However below worked from command line and I was able to add HOME
to environment variables.
rundll32 sysdm.cpl,EditEnvironmentVariables
import org.apache.spark.sql.functions.desc
df.orderBy(desc("columnname1"),desc("columnname2"),asc("columnname3"))
Using BroadcastReceiver
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// something
// for home listen
InnerRecevier innerReceiver = new InnerRecevier();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(innerReceiver, intentFilter);
}
// for home listen
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
// home is Pressed
}
}
}
}
}
I'm always the one to bring up findall() =)
>>> strings = ['foofo21', 'bar432', 'foobar12345']
>>> [re.findall(r'(\w+?)(\d+)', s)[0] for s in strings]
[('foofo', '21'), ('bar', '432'), ('foobar', '12345')]
Note that I'm using a simpler (less to type) regex than most of the previous answers.
If I understood your problem correctly, $(this).parents('.box').children('.something1')
Is this what you are looking for?
With the following streaming code, the Python memory usage is restricted regardless of the size of the downloaded file:
def download_file(url):
local_filename = url.split('/')[-1]
# NOTE the stream=True parameter below
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
# If you have chunk encoded response uncomment if
# and set chunk_size parameter to None.
#if chunk:
f.write(chunk)
return local_filename
Note that the number of bytes returned using iter_content
is not exactly the chunk_size
; it's expected to be a random number that is often far bigger, and is expected to be different in every iteration.
See body-content-workflow and Response.iter_content for further reference.
You can do it with jquery, just put two methods to submit for to diffrent urls, for example with this form:
<form id="myForm">
<%-- form data inputs here ---%>
<button id="edit">Edit</button>
<button id="validate">Validate</button>
</form>
you can use this script (make sure it is located in the View, in order to use the Url.Action attribute):
<script type="text/javascript">
$("#edit").click(function() {
var form = $("form#myForm");
form.attr("action", "@Url.Action("Edit","MyController")");
form.submit();
});
$("#validate").click(function() {
var form = $("form#myForm");
form.attr("action", "@Url.Action("Validate","MyController")");
form.submit();
});
</script>
All of the answers here are using an approach that the processor needs to search all of the string even if the first word is found! For big strings, this is not recommended. This approach is optimal:
function getFirstWord($string) {
$result = "";
foreach($string as $char) {
if($char == " " && strlen($result)) {
break;
}
$result .= $char;
}
return $result;
}
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String
in as the string-to-match argument to the string.replace
method, it doesn't do a string replace. It converts the string to a RegExp
and does a regex substitution. As Gumbo explains, a regex substitution requires the g
?lobal flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
A nicer implementation could be to use the category method below on NSMutableArray.
@implementation NSMutableArray(BMCommons)
- (void)removeObjectsWithPredicate:(BOOL (^)(id obj))predicate {
if (predicate != nil) {
NSMutableArray *newArray = [[NSMutableArray alloc] initWithCapacity:self.count];
for (id obj in self) {
BOOL shouldRemove = predicate(obj);
if (!shouldRemove) {
[newArray addObject:obj];
}
}
[self setArray:newArray];
}
}
@end
The predicate block can be implemented to do processing on each object in the array. If the predicate returns true the object is removed.
An example for a date array to remove all dates that lie in the past:
NSMutableArray *dates = ...;
[dates removeObjectsWithPredicate:^BOOL(id obj) {
NSDate *date = (NSDate *)obj;
return [date timeIntervalSinceNow] < 0;
}];
None of the answers mentioned that the ToString()
method can be applied to integer expressions
Debug.Assert((1000*1000).ToString()=="1000000");
even to integer literals
Debug.Assert(256.ToString("X")=="100");
Although integer literals like this are often considered to be bad coding style (magic numbers) there may be cases where this feature is useful...
After installing openjdk with brew and runnning brew info openjdk
I got this
And from that I got this command here, and after running it I got Java working
sudo ln -sfn /usr/local/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk
The property to set is => WindowStyle="None"
<Window x:Class="mdaframework.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Start" Height="350" Width="525" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" WindowStyle="None">
String Uri = request.getRequestURL()+"?"+request.getQueryString();
To select rows according to one 'cell_type' (e.g. 'hesc'), use ==
:
expr[expr$cell_type == "hesc", ]
To select rows according to two or more different 'cell_type', (e.g. either 'hesc' or 'bj fibroblast'), use %in%
:
expr[expr$cell_type %in% c("hesc", "bj fibroblast"), ]
jasonmp85 is right about passing a different array to String.format
. The size of an array can't be changed once constructed, so you'd have to pass a new array instead of modifying the existing one.
Object newArgs = new Object[args.length+1];
System.arraycopy(args, 0, newArgs, 1, args.length);
newArgs[0] = extraVar;
String.format(format, extraVar, args);
(Windows) If you have already installed MySQL server
cd C:\Program Files\MySQL\MySQL Server X.X\bin
mysqld --install
and still cannot connect, then the service did not start automatically. Just try
Start > Search "services"
and scroll down until you see "MySQLXX", where the XX represents the MySQL Server version. If the Status isn't "Started", then
Right Click > Start
I do always this:
from h in OH
where h.Hierarchy.Contains("/12/")
select h
I know I don't use the like statement but it's work fine in the background is this translated into a query with a like statement.
If your .so
file is in elf format, you can use readelf program to extract symbol information from the binary. This command will give you the symbol table:
readelf -Ws /usr/lib/libexample.so
You only should extract those that are defined in this .so
file, not in the libraries referenced by it. Seventh column should contain a number in this case. You can extract it by using a simple regex:
readelf -Ws /usr/lib/libstdc++.so.6 | grep '^\([[:space:]]\+[^[:space:]]\+\)\{6\}[[:space:]]\+[[:digit:]]\+'
or, as proposed by Caspin,:
readelf -Ws /usr/lib/libstdc++.so.6 | awk '{print $8}';
This should return month text (January - December) from the month index (1-12)
int monthNumber = 1; //1-12
string monthName = new DateTimeFormatInfo().GetMonthName(monthNumber);
I had a similar problem recently, and google landed me here, so I put this answer here in case others land here as well, for completeness.
I noticed that when I had badly formatted html, I was actually having all my html tags stripped out, with just the non-tag content remaining. I particularly had a table with a missing opening table tag, and then all my html tags from the entire string where ripped out completely.
So, if the above doesn't work, and you're still scratching your head, then also check you html for being valid.
I notice even after I got it working, MVC was adding tbody tags where I had none. This tells me there is clean up happening (MVC 5), and that when it can't happen, it strips out all/some tags.
To start, using the same ID twice is not a good idea. ID's should be unique, if you need to style elements you should use a class to apply CSS instead.
At last, you defined the name of your submit button as Tea and Coffee, but in your PHP you are using submit as index. your index should have been $_POST['Tea'] for example. that would require you to check for it being set as it only sends one , you can do that with isset().
Buy anyway , user4035 just beat me to it , his code will "fix" this for you.
You can use for loop to find your element and update it:
updateItem(newItem){
for (let i = 0; i < this.itemsArray.length; i++) {
if(this.itemsArray[i].id == newItem.id){
this.users[i] = newItem;
}
}
}
And selector is the answer here as well.
Search for bright_text_dark_focused.xml in the sources, add to your project under res/color directory and then refer from the TextView as
android:textColor="@color/bright_text_dark_focused"
If you need to resume an scp transfer from local to remote, try with rsync:
rsync --partial --progress --rsh=ssh local_file user@host:remote_file
Short version, as pointed out by @aurelijus-rozenas:
rsync -P -e ssh local_file user@host:remote_file
In general the order of args for rsync is
rsync [options] SRC DEST
Not being a developer I found a solution in running multiple ps commands in one line. E.g:
powershell "& 'c:\path with spaces\to\executable.exe' -arguments ; second command ; etc
By placing a " (double quote) before the & (ampersand) it executes the executable. In none of the examples I have found this was mentioned. Without the double quotes the ps prompt opens and waits for input.
U can try this JS code.. https://snack.expo.io/r1v0LwZFb
import React, { Component } from 'react';
import { View } from 'react-native';
export default class App extends Component {
render() {
const gradientHeight=500;
const gradientBackground = 'purple';
const data = Array.from({ length: gradientHeight });
return (
<View style={{flex:1}}>
{data.map((_, i) => (
<View
key={i}
style={{
position: 'absolute',
backgroundColor: gradientBackground,
height: 1,
bottom: (gradientHeight - i),
right: 0,
left: 0,
zIndex: 2,
opacity: (1 / gradientHeight) * (i + 1)
}}
/>
))}
</View>
);
}
}
Take a look QRCoder - pure C# open source QR code generator. Can be used in three lines of code
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(textBoxQRCode.Text, QRCodeGenerator.ECCLevel.Q);
pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(20);
Check whether a String contains at least one white space character:
public static boolean containsWhiteSpace(final String testCode){
if(testCode != null){
for(int i = 0; i < testCode.length(); i++){
if(Character.isWhitespace(testCode.charAt(i))){
return true;
}
}
}
return false;
}
Reference:
Using the Guava library, it's much simpler:
return CharMatcher.WHITESPACE.matchesAnyOf(testCode);
CharMatcher.WHITESPACE
is also a lot more thorough when it comes to Unicode support.
One situation that is a little different is when developing a CodeIgniter application. CodeIgniter seems to use the shorttags whenever PHP is being used in a template/view, otherwise with models and controllers it always uses the long tags. It's not a hard and fast rule in the framework, but for the most part the framework and a lot of the source from other uses follows this convention.
My two cents? If you never plan on running the code somewhere else, then use them if you want. I'd rather not have to do a massive search and replace when I realize it was a dumb idea.
IMHO answering this question with the use of ExpressJS is to give a superficial answer. I am going to answer the best I can with out the use of any frameworks or modules. The reason this question is often answerd with the use of a framework is becuase it takes away the requirment of understanding 'Hypertext-Transfer-Protocall'.
so with that pointed out we now know what information is being sent to the server now we can now seperate css request from html request on our serverside using a bit of javascript.
var http = require('http');
var url = require('url');
var fs = require('fs');
function onRequest(request, response){
if(request.headers.accept.split(',')[0] == 'text/css') {
console.log('TRUE');
fs.readFile('index.css', (err, data)=>{
response.writeHeader(200, {'Content-Type': 'text/css'});
response.write(data);
response.end();
});
}
else {
console.log('FALSE');
fs.readFile('index.html', function(err, data){
response.writeHead(200, {'Content_type': 'text/html'});
response.write(data);
response.end();
});
};
};
http.createServer(onRequest).listen(8888);
console.log('[SERVER] - Started!');
Here is a quick sample of one way I might seperate request. Now remember this is a quick example that would typically be split accross severfiles, some of which would have functions as dependancys to others, but for the sack of 'all in a nutshell' this is the best I could do. I tested it and it worked. Remember that index.css and index.html can be swapped with any html/css files you want.
If you like to keep records separate and not do the union.
Try query below
SELECT (SELECT name,
games,
goals
FROM tblMadrid
WHERE name = 'ronaldo') AS table_a,
(SELECT name,
games,
goals
FROM tblBarcelona
WHERE name = 'messi') AS table_b
FROM DUAL
Just tested and this works:
public class Coordinates {
byte red;
@JsonProperty("r")
public byte getR() {
return red;
}
@JsonProperty("red")
public void setRed(byte red) {
this.red = red;
}
}
The idea is that method names should be different, so jackson parses it as different fields, not as one field.
Here is test code:
Coordinates c = new Coordinates();
c.setRed((byte) 5);
ObjectMapper mapper = new ObjectMapper();
System.out.println("Serialization: " + mapper.writeValueAsString(c));
Coordinates r = mapper.readValue("{\"red\":25}",Coordinates.class);
System.out.println("Deserialization: " + r.getR());
Result:
Serialization: {"r":5}
Deserialization: 25
Just to complement @Marcus Ekwall 's answer. Doing like this will get only anchor links. And you aren't going to have problems if you have a mix of anchor links and regular ones.
jQuery(document).ready(function(jQuery) {
var topMenu = jQuery("#top-menu"),
offset = 40,
topMenuHeight = topMenu.outerHeight()+offset,
// All list items
menuItems = topMenu.find('a[href*="#"]'),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var href = jQuery(this).attr("href"),
id = href.substring(href.indexOf('#')),
item = jQuery(id);
//console.log(item)
if (item.length) { return item; }
});
// so we can get a fancy scroll animation
menuItems.click(function(e){
var href = jQuery(this).attr("href"),
id = href.substring(href.indexOf('#'));
offsetTop = href === "#" ? 0 : jQuery(id).offset().top-topMenuHeight+1;
jQuery('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
// Bind to scroll
jQuery(window).scroll(function(){
// Get container scroll position
var fromTop = jQuery(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if (jQuery(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
menuItems.parent().removeClass("active");
if(id){
menuItems.parent().end().filter("[href*='#"+id+"']").parent().addClass("active");
}
})
})
Basically i replaced
menuItems = topMenu.find("a"),
by
menuItems = topMenu.find('a[href*="#"]'),
To match all links with anchor somewhere, and changed all that what was necessary to make it work with this
See it in action on jsfiddle
When you assign a variable to empty curly braces {} eg: new_set = {}
, it becomes a dictionary.
To create an empty set, assign the variable to a 'set()' ie: new_set = set()
Use In
instead of =
select * from dbo.books
where isbn in (select isbn from dbo.lending
where act between @fdate and @tdate
and stat ='close'
)
or you can use Exists
SELECT t1.*,t2.*
FROM books t1
WHERE EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
t2.act between @fdate and @tdate and t2.stat ='close' )
If you are not into Cygwin, you can use native Windows builds. Some are here: curl Download Wizard.
Whenever gcc
on the compilation machine and gdb
on the testing machine have differing versions, you may be facing debuginfo format incompatibility.
To fix that, try downgrading the debuginfo format:
gcc -gdwarf-3 ...
gcc -gdwarf-2 ...
gcc -gstabs ...
gcc -gstabs+ ...
gcc -gcoff ...
gcc -gxcoff ...
gcc -gxcoff+ ...
Or match gdb
to the gcc
you're using.
In my opinion, the answer on this page with the most votes is the best answer, but his math was wrong and I couldn't comment on it.
I needed a text input box to be exactly 40 pixels high including a 1 pixel border all the way around. Of course I wanted the text vertically aligned in the center in all browsers.
1 pixel border top
1 pixel border bottom
8 pixel top padding
8 pixel bottom padding
22 pixel font size
1 + 1 + 8 + 8 + 22 = 40 pixels exactly.
One thing to remember is that you must remove your css height property or those pixels will get added to your total above.
<input type="text" style="padding-top:8px; padding-bottom:8px; margin: 0; border: solid 1px #000000; font-size:22px;" />
This is working in Firefox, Chrome, IE 8, and Safari. I can only assume that if something simple like this is working in IE8, it should work similarly in 6, 7, and 9 but I have not tested it. Please let me know and I'll edit this post accordingly.
simple query this query select all record from table where email is unique:
select distinct email,* from table_name
try this
<html>_x000D_
<head>_x000D_
<style type="text/css">_x000D_
body {_x000D_
font-family: sans-serif;_x000D_
font-size: 14px;_x000D_
}_x000D_
</style>_x000D_
_x000D_
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places®ion=in" type="text/javascript"></script>_x000D_
<script type="text/javascript">_x000D_
function initialize() {_x000D_
var input = document.getElementById('searchTextField');_x000D_
var autocomplete = new google.maps.places.Autocomplete(input);_x000D_
}_x000D_
google.maps.event.addDomListener(window, 'load', initialize);_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"
Change this to: "region=in" (in=india)
"http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places®ion=in" type="text/javascript"
The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.
You can link the table either manually or with VBA like this
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
Dim db As DAO.Database
' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next: db.TableDefs.Delete "tblImport": On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh
' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
& "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close: Set db = Nothing
You have to use setOnItemClickListener
someone said.
The code should be like this:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text or do whatever you need.
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
Create a table layout panel with two columns in your form and name it tlpFields
.
Then, simply add new control to table layout panel (in this case I added 5 labels in column-1 and 5 textboxes in column-2).
tlpFields.RowStyles.Clear(); //first you must clear rowStyles
for (int ii = 0; ii < 5; ii++)
{
Label l1= new Label();
TextBox t1 = new TextBox();
l1.Text = "field : ";
tlpFields.Controls.Add(l1, 0, ii); // add label in column0
tlpFields.Controls.Add(t1, 1, ii); // add textbox in column1
tlpFields.RowStyles.Add(new RowStyle(SizeType.Absolute,30)); // 30 is the rows space
}
Finally, run the code.
After some googling I found this:
curl -c cookie.txt -d "LoginName=someuser" -d "password=somepass" https://oursite/a
curl -b cookie.txt https://oursite/b
No idea if it works, but it might lead you in the right direction.
import java.security.MessageDigest;
public class CodeSnippets {
public static String getSha256(String value) {
try{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(value.getBytes());
return bytesToHex(md.digest());
} catch(Exception ex){
throw new RuntimeException(ex);
}
}
private static String bytesToHex(byte[] bytes) {
StringBuffer result = new StringBuffer();
for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
return result.toString();
}
}
OR
rm -rf `find /path/to/base/dir/* -type d -mtime +10`
Updated, faster version of it:
find /path/to/base/dir/* -mtime +10 -print0 | xargs -0 rm -f
I know the question specified dplyr
. But, since others already posted solutions using other packages, I decided to have a go using other packages too:
Base package:
df <- df[with(df, order(id, stopSequence, stopId)), ]
merge(df[!duplicated(df$id), ],
df[!duplicated(df$id, fromLast = TRUE), ],
all = TRUE)
data.table:
df <- setDT(df)
df[order(id, stopSequence)][, .SD[c(1,.N)], by=id]
sqldf:
library(sqldf)
min <- sqldf("SELECT id, stopId, min(stopSequence) AS StopSequence
FROM df GROUP BY id
ORDER BY id, StopSequence, stopId")
max <- sqldf("SELECT id, stopId, max(stopSequence) AS StopSequence
FROM df GROUP BY id
ORDER BY id, StopSequence, stopId")
sqldf("SELECT * FROM min
UNION
SELECT * FROM max")
In one query:
sqldf("SELECT *
FROM (SELECT id, stopId, min(stopSequence) AS StopSequence
FROM df GROUP BY id
ORDER BY id, StopSequence, stopId)
UNION
SELECT *
FROM (SELECT id, stopId, max(stopSequence) AS StopSequence
FROM df GROUP BY id
ORDER BY id, StopSequence, stopId)")
Output:
id stopId StopSequence
1 1 a 1
2 1 c 3
3 2 b 1
4 2 c 4
5 3 a 3
6 3 b 1
To answer your comment to Alex. Here's quick code that should allow you to get the fields like activity_details, last_name, etc. from the json dictionary that is returned:
NSDictionary *userinfo=[jsondic valueforKey:@"#data"];
NSDictionary *user;
NSInteger i = 0;
NSString *skey;
if(userinfo != nil){
for( i = 0; i < [userinfo count]; i++ ) {
if(i)
skey = [NSString stringWithFormat:@"%d",i];
else
skey = @"";
user = [userinfo objectForKey:skey];
NSLog(@"activity_details:%@",[user objectForKey:@"activity_details"]);
NSLog(@"last_name:%@",[user objectForKey:@"last_name"]);
NSLog(@"first_name:%@",[user objectForKey:@"first_name"]);
NSLog(@"photo_url:%@",[user objectForKey:@"photo_url"]);
}
}
What worked for me is I followed the following steps to improve my application perfomance in IE 11 1.) In Index.html file, add the following CDN's
<script src="https://npmcdn.com/[email protected]
beta.17/es6/dev/src/testing/shims_for_IE.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.2.201711092/classList.min.js"></script>
2.) In polyfills.ts file and add the following import:
import 'core-js/client/shim';
Do you mean this?
var listOfList = new List<List<int>>() {
new List<int>() { 1, 2 },
new List<int>() { 3, 4 },
new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));
foreach (var x in result) Console.WriteLine(x);
Results in: 9 9 9 1 2 3 4 5 6
To avoid update names that contain .com
like [email protected]
to [email protected]
, you can do this:
UPDATE Yourtable
SET Email = LEFT(@Email, LEN(@Email) - 4) + REPLACE(RIGHT(@Email, 4), '.com', '.org')
You could output them to a .csv file and open the file in excel. Is that direct enough?
That will be possible only if the HTML file is also loaded with the file
protocol from the local user's harddisk.
If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src
attribute with the file://
protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.
As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.
From Help with Serial.Read() getting string:
char inData[20]; // Allocate some space for the string
char inChar=-1; // Where to store the character read
byte index = 0; // Index into array; where to store the character
void setup() {
Serial.begin(9600);
Serial.write("Power On");
}
char Comp(char* This) {
while (Serial.available() > 0) // Don't read unless
// there you know there is data
{
if(index < 19) // One less than the size of the array
{
inChar = Serial.read(); // Read a character
inData[index] = inChar; // Store it
index++; // Increment where to write next
inData[index] = '\0'; // Null terminate the string
}
}
if (strcmp(inData,This) == 0) {
for (int i=0;i<19;i++) {
inData[i]=0;
}
index=0;
return(0);
}
else {
return(1);
}
}
void loop()
{
if (Comp("m1 on")==0) {
Serial.write("Motor 1 -> Online\n");
}
if (Comp("m1 off")==0) {
Serial.write("Motor 1 -> Offline\n");
}
}
I periodically search for a satisfactory answer to this, but no luck so far. I use soapUI + requests + manual labour.
I gave up and used Java the last time I needed to do this, and simply gave up a few times the last time I wanted to do this, but it wasn't essential.
Having successfully used the requests library last year with Project Place's RESTful API, it occurred to me that maybe I could just hand-roll the SOAP requests I want to send in a similar way.
Turns out that's not too difficult, but it is time consuming and prone to error, especially if fields are inconsistently named (the one I'm currently working on today has 'jobId', JobId' and 'JobID'. I use soapUI to load the WSDL to make it easier to extract endpoints etc and perform some manual testing. So far I've been lucky not to have been affected by changes to any WSDL that I'm using.
If you have PHP5 and the HTTP stream wrapper enabled on your server, it's incredibly simple to copy it to a local file:
copy('http://somedomain.com/file.jpeg', '/tmp/file.jpeg');
This will take care of any pipelining etc. that's needed. If you need to provide some HTTP parameters there is a third 'stream context' parameter you can provide.
A couple years late, but here is a solution that retrieves both inline styling and external styling:
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
Pass a jQuery object into css()
and it will return an object, which you can then plug back into jQuery's $().css()
, ex:
var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);
:)
You can code like two input box inside one div
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input style="width:50% " class="form-control " placeholder="first name" name="firstname" type="text" />
<input style="width:50% " class="form-control " placeholder="lastname" name="lastname" type="text" />
</div>
To put your current mobile date and time format in
Feb 9, 2018 10:36:59 PM
Date date = new Date();
String stringDate = DateFormat.getDateTimeInstance().format(date);
you can show it to your Activity
, Fragment
, CardView
, ListView
anywhere by using TextView
` TextView mDateTime;
mDateTime=findViewById(R.id.Your_TextViewId_Of_XML);
Date date = new Date();
String mStringDate = DateFormat.getDateTimeInstance().format(date);
mDateTime.setText("My Device Current Date and Time is:"+date);
`
This could help:
<select [(ngModel)]="selectedValue">
<option *ngFor="#c of countries" [value]="c.id">{{c.name}}</option>
</select>
FirefoxDriver _driver = new FirefoxDriver();
// create webdriverwait
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));
// create flag/checker
bool result = false;
// wait for the element.
IWebElement elem = wait.Until(x => x.FindElement(By.Id("Element_ID")));
do
{
try
{
// let the driver look for the element again.
elem = _driver.FindElement(By.Id("Element_ID"));
// do your actions.
elem.SendKeys("text");
// it will throw an exception if the element is not in the dom or not
// found but if it didn't, our result will be changed to true.
result = !result;
}
catch (Exception) { }
} while (result != true); // this will continue to look for the element until
// it ends throwing exception.
Drop the semicolon after the function definition.
(function (msg){alert(msg)})
('SO');
Above should work.
DEMO Page: https://jsfiddle.net/e7ooeq6m/
I have discussed this kind of pattern in this post:
EDIT:
If you look at ECMA script specification, there are 3 ways you can define a function. (Page 98, Section 13 Function Definition)
var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30
function sum(a, b)
{
return a + b;
}
alert(sum(10, 10)); //Alerts 20;
var sum = function(a, b) { return a + b; }
alert(sum(5, 5)); // alerts 10
So you may ask, what's the difference between declaration and expression?
From ECMA Script specification:
FunctionDeclaration : function Identifier ( FormalParameterListopt ){ FunctionBody }
FunctionExpression : function Identifieropt ( FormalParameterListopt ){ FunctionBody }
If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
This means following is valid.
var sum = function mySum(a, b) { return a + b; }
Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:
var test1 = function test2() { alert(typeof test2); }
alert(typeof(test2)); //alerts 'undefined', surprise!
test1(); //alerts 'function' because test2 is a function.
Compare this to
function test1() { alert(typeof test1) };
alert(typeof test1); //alerts 'function'
test1(); //alerts 'function'
Armed with this knowledge, let's try to analyze your code.
When you have code like,
function(msg) { alert(msg); }
You created a function expression. And you can execute this function expression by wrapping it inside parenthesis.
(function(msg) { alert(msg); })('SO'); //alerts SO.
This is not an example use or an explanation of how to use FLAG_ACTIVITY_NO_ANIMATION
, however it does answer how to disable the Activity
switching animation, as asked in the question title:
Android, how to disable the 'wipe' effect when starting a new activity?
To make things simple , please note that every time you do itr2.next()
the pointer moves to the next element i.e. here if you notice carefully, then the output is perfectly fine according to the logic you have written .
This may help you in understanding better:
1st Iteration of While loop(pointer is before the 1st element):
Key: if ,value: 2 {itr2.next()=if; m.get(itr2.next()=it)=>2}
2nd Iteration of While loop(pointer is before the 3rd element):
Key: is ,value: 2 {itr2.next()=is; m.get(itr2.next()=to)=>2}
3rd Iteration of While loop(pointer is before the 5th element):
Key: be ,value: 1 {itr2.next()="be"; m.get(itr2.next()="up")=>"1"}
4th Iteration of While loop(pointer is before the 7th element):
Key: me ,value: 1 {itr2.next()="me"; m.get(itr2.next()="delegate")=>"1"}
Key: if ,value: 1
Key: it ,value: 2
Key: is ,value: 2
Key: to ,value: 2
Key: be ,value: 1
Key: up ,value: 1
Key: me ,value: 1
Key: delegate ,value: 1
It prints:
Key: if ,value: 2
Key: is ,value: 2
Key: be ,value: 1
Key: me ,value: 1
It sounds like you want to use a transparent background, in which case you could try using the rgba()
function:
rgba(R, G, B, A)
R (red), G (green), and B (blue) can be either
<integer>
s or<percentage>
s, where the number 255 corresponds to 100%. A (alpha) can be a<number>
between 0 and 1, or a<percentage>
, where the number 1 corresponds to 100% (full opacity).RGBa example
rgba(51, 170, 51, .1) /* 10% opaque green */ rgba(51, 170, 51, .4) /* 40% opaque green */ rgba(51, 170, 51, .7) /* 70% opaque green */ rgba(51, 170, 51, 1) /* full opaque green */
A small example showing how rgba
can be used.
As of 2018, practically every browser supports the rgba
syntax.
If you go into any of those locations, then you will find what is defined in those schema. For example, it tells you what is the data type of the ini-method key words value.
To use the new date range picker, you can use the mat-date-range-input
and mat-date-range-picker
components.
Example
HTML
<mat-form-field>
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [rangePicker]="picker">
<input matStartDate matInput placeholder="Start date">
<input matEndDate matInput placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
You can read and learn more about this in their official documentation.
Unfortunately, they still haven't build a timepicker
on this release.
All are different.
typeof
takes a type name (which you specify at compile time).GetType
gets the runtime type of an instance.is
returns true if an instance is in the inheritance tree.class Animal { }
class Dog : Animal { }
void PrintTypes(Animal a) {
Console.WriteLine(a.GetType() == typeof(Animal)); // false
Console.WriteLine(a is Animal); // true
Console.WriteLine(a.GetType() == typeof(Dog)); // true
Console.WriteLine(a is Dog); // true
}
Dog spot = new Dog();
PrintTypes(spot);
What about
typeof(T)
? Is it also resolved at compile time?
Yes. T is always what the type of the expression is. Remember, a generic method is basically a whole bunch of methods with the appropriate type. Example:
string Foo<T>(T parameter) { return typeof(T).Name; }
Animal probably_a_dog = new Dog();
Dog definitely_a_dog = new Dog();
Foo(probably_a_dog); // this calls Foo<Animal> and returns "Animal"
Foo<Animal>(probably_a_dog); // this is exactly the same as above
Foo<Dog>(probably_a_dog); // !!! This will not compile. The parameter expects a Dog, you cannot pass in an Animal.
Foo(definitely_a_dog); // this calls Foo<Dog> and returns "Dog"
Foo<Dog>(definitely_a_dog); // this is exactly the same as above.
Foo<Animal>(definitely_a_dog); // this calls Foo<Animal> and returns "Animal".
Foo((Animal)definitely_a_dog); // this does the same as above, returns "Animal"
Step the loop manually:
i=0 max=10 while [ $i -lt $max ] do echo "output: $i" true $(( i++ )) done
If you don’t have to be totally POSIX, you can use the arithmetic for loop:
max=10 for (( i=0; i < max; i++ )); do echo "output: $i"; done
Or use jot(1) on BSD systems:
for i in $( jot 0 10 ); do echo "output: $i"; done
In command window type
php --ini
It will show you the path something like
Configuration File (php.ini) Path: /usr/local/lib
Loaded Configuration File: /usr/local/lib/php.ini
If the above command does not work then use this
echo phpinfo();
Your postgres server configuration seems correct
That should grant access from the client to the postgres server. So that leads me to believe the username / password is whats failing.
host all all 127.0.0.1/32 md5
host all all 192.168.0.1/32 trust
Test this by creating a specific user for that database
createuser -a -d -W -U postgres chaosuser
Then adjust your perl script to use the newly created user
my $dbh = DBI->connect("DBI:PgPP:database=chaosLRdb;host=192.168.0.1;port=5433", "chaosuser", "chaos123");
Easy way to remove public from laravel 5 url. You just need to cut index.php and .htaccess from public directory and paste it in the root directory,thats all and replace two lines in index.php as
require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
Note: The above method is just for the beginners as they might be facing problem in setting up virtual host and The best solution is to setup virtual host on local machine and point it to the public directory of the project.
You can install GnuWin32 and use *nix commands natively on windows. I install this before I install anything else on a minty fresh copy of windows. :)
In my and other many vim users, the best option is to,
:e file_name.extension
And then just Ctrl + 6 to change to the last buffer. Or, you can always press
:ls to list the buffer and then change the buffer using b followed by the buffer number.
:vsp for vertical split
:sp for horizantal split
And then <C-W><C-H/K/L/j>
to change the working split.
You can ofcourse edit any file in any number of splits.
Delete the CMakeCache.txt file and try this:
cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON ..
You have to enter all your command-line definitions before including the path.
public int GetResult(List<int> list){
int first = list.First();
return list.All(x => x == first) ? first : SOME_OTHER_VALUE;
}
In the top level of the IIS Manager (above Sites), you should see the Application Pools tree node. Right click on "Application Pools", choose "Add Application Pool".
Give it a name, choose .NET Framework 4.0 and either Integrated or Classic mode.
When you add or edit a web site, your new application pools will now show up in the list.
This problem can be simply solved by closing Eclipse and restarting it. Eclipse sometimes fails to establish a connection with the Emulator, so this can happen in some cases.
I've found using cmd works well as an alternative, especially when you need to pipe the output from the called application (espeically when it doesn't have built in logging, unlike msbuild)
cmd /C "$msbuild $args" >> $outputfile
I needed to print ALL lines after the pattern ( ok Ed, REGEX ), so I settled on this one:
sed -n '/pattern/,$p' # prints all lines after ( and including ) the pattern
But since I wanted to print all the lines AFTER ( and exclude the pattern )
sed -n '/pattern/,$p' | tail -n+2 # all lines after first occurrence of pattern
I suppose in your case you can add a head -1
at the end
sed -n '/pattern/,$p' | tail -n+2 | head -1 # prints line after pattern
javax.servlet.Filter
.doFilter()
method, cast the incoming ServletRequest
to HttpServletRequest
.HttpServletRequest#getRequestURI()
to grab the path.java.lang.String
methods like substring()
, split()
, concat()
and so on to extract the part of interest and compose the new path.ServletRequest#getRequestDispatcher()
and then RequestDispatcher#forward()
to forward the request/response to the new URL (server-side redirect, not reflected in browser address bar), or cast the incoming ServletResponse
to HttpServletResponse
and then HttpServletResponse#sendRedirect()
to redirect the response to the new URL (client side redirect, reflected in browser address bar).web.xml
on an url-pattern
of /*
or /Check_License/*
, depending on the context path, or if you're on Servlet 3.0 already, use the @WebFilter
annotation for that instead.Don't forget to add a check in the code if the URL needs to be changed and if not, then just call FilterChain#doFilter()
, else it will call itself in an infinite loop.
Alternatively you can also just use an existing 3rd party API to do all the work for you, such as Tuckey's UrlRewriteFilter which can be configured the way as you would do with Apache's mod_rewrite
.
At work we use ZScaler as our proxy. The only way I was able to get npm to work was to use Cntlm.
See this answer:
You can also use the latest
keyword to install the most recent version available:
"dependencies": {
"fontawesome": "latest"
}
I run into this a bit working with legacy stuff where they only work on east coast US and don't store dates in UTC, it's all EST. I have to filter on the dates based on user input in the browser so must pass the date in local time in JSON format.
Just to elaborate on this solution already posted - this is what I use:
// Could be picked by user in date picker - local JS date
date = new Date();
// Create new Date from milliseconds of user input date (date.getTime() returns milliseconds)
// Subtract milliseconds that will be offset by toJSON before calling it
new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
So my understanding is this will go ahead and subtract time (in milliseconds (hence 60000) from the starting date based on the timezone offset (returns minutes) - in anticipation for the addition of time toJSON() is going to add.
One way is to just leave merged feature branches open (and inactive):
$ hg up default
$ hg merge feature-x
$ hg ci -m merge
$ hg heads
(1 head)
$ hg branches
default 43:...
feature-x 41:...
(2 branches)
$ hg branches -a
default 43:...
(1 branch)
Another way is to close a feature branch before merging using an extra commit:
$ hg up feature-x
$ hg ci -m 'Closed branch feature-x' --close-branch
$ hg up default
$ hg merge feature-x
$ hg ci -m merge
$ hg heads
(1 head)
$ hg branches
default 43:...
(1 branch)
The first one is simpler, but it leaves an open branch. The second one leaves no open heads/branches, but it requires one more auxiliary commit. One may combine the last actual commit to the feature branch with this extra commit using --close-branch
, but one should know in advance which commit will be the last one.
Update: Since Mercurial 1.5 you can close the branch at any time so it will not appear in both hg branches
and hg heads
anymore. The only thing that could possibly annoy you is that technically the revision graph will still have one more revision without childen.
Update 2: Since Mercurial 1.8 bookmarks have become a core feature of Mercurial. Bookmarks are more convenient for branching than named branches. See also this question:
The Spinner should fire an "OnItemSelected" event when something is selected:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
You can edit your readme.md with instructions to install your laravel app in other environment like this:
## Create folders
```
#!terminal
cp .env.example .env && mkdir bootstrap/cache storage storage/framework && cd storage/framework && mkdir sessions views cache
```
## Folder permissions
```
#!terminal
sudo chown :www-data app storage bootstrap -R
sudo chmod 775 app storage bootstrap -R
```
## Install dependencies
```
#!terminal
composer install
```
Just try this instead:
res.sendFile('public/index1.html' , { root : __dirname});
This worked for me. the root:__dirname will take the address where server.js is in the above example and then to get to the index1.html ( in this case) the returned path is to get to the directory where public folder is.
Just to add to the confusion, the (Windows Explorer) Effective Permissions dialog doesn't work for these logins. I have a site "Umbo4" using pass-through authentication, and looked at the user's Effective Permissions in the site root folder. The Check Names test resolved the name "IIS AppPool\Umbo4", but the Effective Permissions shows that the user had no permissions at all on the folder (all checkboxes unchecked).
I then excluded this user from the folder explicitly, using the Explorer Security tab. This resulted in the site failing with a HTTP 500.19 error, as expected. The Effective Permissions however looked exactly as before.
curl_getinfo()
must be added before closing the curl handler
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info['request_header']);
curl_close($ch);
working now :) Code attached below
<TextView
android:text="START | lunch 20.00 | Dinner 60.00 | Travel 60.00 | Doctor 5000.00 | lunch 20.00 | Dinner 60.00 | Travel 60.00 | Doctor 5000.00 | END"
android:id="@+id/MarqueeText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:paddingLeft="15dip"
android:paddingRight="15dip"
android:focusable="true"
android:focusableInTouchMode="true"
android:freezesText="true">
Edit (on behalf of Adil Hussain):
textView.setSelected(true)
needs to be set in code behind for this to work.
First of all, there're two kinds of keystores.
Individual and General
The application will use the one indicated in the startup or the default of the system.
It will be a different folder if JRE or JDK is running, or if you check the personal or the "global" one.
They are encrypted too
In short, the path will be like:
$JAVA_HOME/lib/security/cacerts
for the "general one", who has all the CA for the Authorities and is quite important.
Swift
// remove left buttons (in case you added some)
self.navigationItem.leftBarButtonItems = []
// hide the default back buttons
self.navigationItem.hidesBackButton = true
I never suggest using Textboxes or Inputboxes to accept dates. So many things can go wrong. I cannot even suggest using the Calendar Control or the Date Picker as for that you need to register the mscal.ocx or mscomct2.ocx and that is very painful as they are not freely distributable files.
Here is what I recommend. You can use this custom made calendar to accept dates from the user
PROS:
CONS:
Ummm...Ummm... Can't think of any...
HOW TO USE IT (File missing from my dropbox. Please refer to the bottom of the post for an upgraded version of the calendar)
Userform1.frm
and Userform1.frx
from here.Userform1.frm
as shown in the image below.Importing the form
RUNNING IT
You can call it in any procedure. For example
Sub Sample()
UserForm1.Show
End Sub
SCREEN SHOTS IN ACTION
NOTE: You may also want to see Taking Calendar to new level
Google Play services has two APIs you can use to streamline the SMS-based verification process
Provides a fully automated user experience, without requiring the user to manually type verification codes and without requiring any extra app permissions and should be used when possible. It does, however, require you to place a custom hash code in the message body, so you must have control over server side as well.
Request SMS Verification in an Android App
Perform SMS Verification on a Server
Does not require the custom hash code, however require the user to approve your app's request to access the message containing the verification code. In order to minimize the chances of surfacing the wrong message to the user, SMS User Consent
will filter out messages from senders in the user's Contacts list.
The SMS User Consent API
is part of Google Play Services. To use it you’ll need at least version 17.0.0
of these libraries:
implementation "com.google.android.gms:play-services-auth:17.0.0"
implementation "com.google.android.gms:play-services-auth-api-phone:17.1.0"
Step 1: Start listening for SMS messages
SMS User Consent will listen for incoming SMS messages that contain a one-time-code for up to five minutes. It won’t look at any messages that are sent before it’s started. If you know the phone number that will send the one-time-code, you can specify the senderPhoneNumber
, or if you don’t null
will match any number.
smsRetriever.startSmsUserConsent(senderPhoneNumber /* or null */)
Step 2: Request consent to read a message
Once your app receives a message containing a one-time-code, it’ll be notified by a broadcast. At this point, you don’t have consent to read the message — instead you’re given an Intent
that you can start to prompt the user for consent. Inside your BroadcastReceiver
, you show the prompt using the Intent
in the extras
.
When you start that intent, it will prompt the user for permission to read a single message. They’ll be shown the entire text that they will share with your app.
val consentIntent = extras.getParcelable<Intent>(SmsRetriever.EXTRA_CONSENT_INTENT)
startActivityForResult(consentIntent, SMS_CONSENT_REQUEST)
Step 3: Parse the one-time-code and complete SMS Verification
When the user clicks “Allow”
— it’s time to actually read the message! Inside of onActivityResult
you can get the full text of the SMS Message from the data:
val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
You then parse the SMS message and pass the one-time-code to your backend!
Try using the not()
method instead of the :not()
selector.
$(".content a").click(function() {
$(".content a").not(this).hide("slow");
});
You can use the File.deleteOnExit()
method
https://developer.android.com/reference/java/io/File.html#deleteOnExit()
It is referenced here https://developer.android.com/reference/java/io/File.html#createTempFile(java.lang.String, java.lang.String, java.io.File)
You can't use a condition to change the structure of your query, just the data involved. You could do this:
update table set
columnx = (case when condition then 25 else columnx end),
columny = (case when condition then columny else 25 end)
This is semantically the same, but just bear in mind that both columns will always be updated. This probably won't cause you any problems, but if you have a high transactional volume, then this could cause concurrency issues.
The only way to do specifically what you're asking is to use dynamic SQL. This is, however, something I'd encourage you to stay away from. The solution above will almost certainly be sufficient for what you're after.
Just a thought - if you're not targeting IE7, you could get away with any image being base64-encoded and embedded into css. I'm assuming your goal is to avoid an unnecessary http request rather than to actually make a css button as its own goal.
Use pickle, like this: import pickle
Your code would look like this:
import pickle
mybytes = [120, 3, 255, 0, 100]
with open("bytesfile", "wb") as mypicklefile:
pickle.dump(mybytes, mypicklefile)
To read the data back, use the pickle.load method
this sample code loads the Japanese yield curve, and creates PCA components. It then estimates a given date's move using the PCA and compares it against the actual move.
%matplotlib inline
import numpy as np
import scipy as sc
from scipy import stats
from IPython.display import display, HTML
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import datetime
from datetime import timedelta
import quandl as ql
start = "2016-10-04"
end = "2019-10-04"
ql_data = ql.get("MOFJ/INTEREST_RATE_JAPAN", start_date = start, end_date = end).sort_index(ascending= False)
eigVal_, eigVec_ = np.linalg.eig(((ql_data[:300]).diff(-1)*100).cov()) # take latest 300 data-rows and normalize to bp
print('number of PCA are', len(eigVal_))
loc_ = 10
plt.plot(eigVec_[:,0], label = 'PCA1')
plt.plot(eigVec_[:,1], label = 'PCA2')
plt.plot(eigVec_[:,2], label = 'PCA3')
plt.xticks(range(len(eigVec_[:,0])), ql_data.columns)
plt.legend()
plt.show()
x = ql_data.diff(-1).iloc[loc_].values * 100 # set the differences
x_ = x[:,np.newaxis]
a1, _, _, _ = np.linalg.lstsq(eigVec_[:,0][:, np.newaxis], x_) # linear regression without intercept
a2, _, _, _ = np.linalg.lstsq(eigVec_[:,1][:, np.newaxis], x_)
a3, _, _, _ = np.linalg.lstsq(eigVec_[:,2][:, np.newaxis], x_)
pca_mv = m1 * eigVec_[:,0] + m2 * eigVec_[:,1] + m3 * eigVec_[:,2] + c1 + c2 + c3
pca_MV = a1[0][0] * eigVec_[:,0] + a2[0][0] * eigVec_[:,1] + a3[0][0] * eigVec_[:,2]
pca_mV = b1 * eigVec_[:,0] + b2 * eigVec_[:,1] + b3 * eigVec_[:,2]
display(pd.DataFrame([eigVec_[:,0], eigVec_[:,1], eigVec_[:,2], x, pca_MV]))
print('PCA1 regression is', a1, a2, a3)
plt.plot(pca_MV)
plt.title('this is with regression and no intercept')
plt.plot(ql_data.diff(-1).iloc[loc_].values * 100, )
plt.title('this is with actual moves')
plt.show()
I had found a particular case where swiping (ADB shell input touchscreen swipe ... ) to unlock the home screen doesn't work. More exactly for Acer Z160 and Acer S57. The phones are history but still, they need to be taken into consideration by us developers. Here is the code source that solved my problem. I had made my app to start with the device. and in the "onCreate" function I had changed temporarily the lock type.
Also, just in case google drive does something to the zip file I will post fragments of that code below.
AndroidManifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.gresanuemanuelvasi.test_wakeup">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ServiceStarter" android:enabled="true" android:exported="false" android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
android:directBootAware="true" tools:targetApi="n">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>
class ServiceStarter: BroadcastReceiver() {
@SuppressLint("CommitPrefEdits")
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("EMY_","Calling onReceive")
context?.let {
Log.i("EMY_", "Received action: ${intent!!.getAction()}, user unlocked: " + UserManagerCompat.isUserUnlocked(context))
val sp =it.getSharedPreferences("EMY_", Context.MODE_PRIVATE)
sp.edit().putString(MainActivity.MY_KEY, "M-am activat asa cum trebuie!")
if (intent!!.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
val i = Intent(it, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
it.startActivity(i)
}
}
}
}
class MainActivity : AppCompatActivity() {
companion object {
const val MY_KEY="MY_KEY"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val kgm = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
val kgl = kgm.newKeyguardLock(MainActivity::class.java.simpleName)
if (kgm.inKeyguardRestrictedInputMode()) {
kgl.disableKeyguard()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(arrayOf(Manifest.permission.RECEIVE_BOOT_COMPLETED), 1234)
}
else
{
afisareRezultat()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if(1234 == requestCode )
{
afisareRezultat()
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
private fun afisareRezultat() {
Log.d("EMY_","Calling afisareRezultat")
val sp = getSharedPreferences("EMY_", Context.MODE_PRIVATE);
val raspuns = sp.getString(MY_KEY, "Doesn't exists")
Log.d("EMY_", "AM primit: ${raspuns}")
sp.edit().remove(MY_KEY).apply()
}
}
To have a little better navigation in insert mode, why not map some keys?
imap <C-b> <Left>
imap <C-f> <Right>
imap <C-e> <End>
imap <C-a> <Home>
" <C-a> is used to repeat last entered text. Override it, if its not needed
If you can work around making the Meta key work in your terminal, you can mock emacs mode even better. The navigation in normal-mode is way better, but for shorter movements it helps to stay in insert mode.
For longer jumps, I prefer the following default translation:
<Meta-b> maps to <Esc><C-left>
This shifts to normal-mode and goes back a word