text:
Q: When switching to Jenkins mid-project, how to build artifacts for old tags? I'm working on a project that has already been going on for a while. Unless I am mistaken, part of the use of Jenkins is to store artifacts for desired builds (i.e., releases or tags). This is preferable to me because I don't want to store binaries in the VCS system (SVN).
Moving forward, I can tag successful builds through Jenkins, and the artifacts will be stored forever. But what about old tags? Is there any way I can build all of the previous SVN tags so that the artifacts are available to anyone who needs?
I guess I could make a separate build for each tag, but that would be very tedious and make it difficult to find the artifacts.

A: You can add parameters to the jenkins task, and have the parameter dropdowns populate from the SCM tags.  You can then use the parameter variables in the URL for the scm pulls.
So, when you go to run a build task, you can select the tag, and the appropriate source will be pulled.
If this is inline with what you're envisioning.  I'd be glad to expand.

A: You can create a parameterized build task, which will check out by tag to build.  thus, you need only input the tag name at each build.
But I think you are mistaken -- Jenkins does store artifacts, but it does so more as a side effect of the build, and generally keeps only a couple of the last builds for disk space management.  If you want to maintain a library of previous builds, you probably want something like artifactory.


text:
Q: How to make a progressbar show in a fragment from an Adapter So I have these 4 things.

*

*A Fragment that has my progress bar

*In that fragment there is a recycler view.

*That recyclerview is being handled by an Adapter

*In that adapter, I have a button onclick listening, which when I press the button, will fire off a query on the Firestore database.

What I want to happen is when I click the button and while async tasks are taking place, I want it to show a progress bar.
How do I make this happen?

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTC VIVE Unity C# VRTK use simple pointer and bezier pointer on the same controller? I am developing for the HTC VIVE on Unity with VR Tool Kit and I am trying to use on the same controller the simple pointer script and the bezier pointer script. The problem is that both script use by default the touchpad and the same event "aliasPointer" for enable or disable.
I would like to know if it is possible to use the bezier pointer for the touchpad and the simple pointer for the trigger for example ?

A: At the moment this isn't possible unless you change the code to listen to alternative events for activation.
But it is probably worth raising your issue on the github issues page at: https://github.com/thestonefox/VRTK/issues as this may be a
In the latest version of VRTK on Github master you can now do this by creating a new script that inherits the pointer you want to override (e.g. SimplePointer) and then just override the button registration method:
https://github.com/thestonefox/VRTK/blob/master/Assets/VRTK/Scripts/Pointers/VRTK_BasePointer.cs#L165
You can then register whichever buttons you want to activate and set the pointer.


text:
Q: Arduino passing char to function I apologize if this is a stupid question (It probably is) but I am having a hard time getting a function to work correctly.
My code as it stands:
#define photoPin A0
char photoCode[] = "L";

void loop(void) {
   analogSensor(photoPin, photoCode);
   delay(5000);
}

void analogSensor(int sensorPin, char* sensorCode) {
   //Poll the Photo Cell and append that to the buffer
   int sensorValue=analogRead(sensorPin);
   Serial.print(sensorCode);
   sprintf(buf + strlen(buf), "," + sensorCode + ":%04i", sensorValue);

}

When I try to compile this, I get the following message:
In function 'void analogSensor(int, char*)':
i2c_Sensor:104: error: invalid operands of types 'const char [2]' and 'char*' to binary 'operator+'

But, if I comment out the sprintf line, it compiles fine, and ever 5 seconds, an "L" prints out on the screen.  Ultimately, I am confused as all get out, and don't know where to turn at this point.
Any help is appreciated.

A: The last one the formatting got borked :)
I'm afriad you cant concatenate char* with the + operator :) You'd have to call sprintf or strcat :) See your local man pages.
Instead of this:
sprintf(buf + strlen(buf), "," + sensorCode + ":%04i", sensorValue);

Try this:
sprintf( buf+strlen(buf), ",%s:%04i", sensorCode, sensorValue );


text:
Q: MongoDB: Reduce array of objects into a single object by computing the average of each field I use the MongoDB aggregation API to aggregate some data daily.
The result of this aggregation is of this format:
[
  {
    aggDate: '2019-05-23',
    results: [
      {
        foo: 0.58,
        bar: 0.42
      }, {
        foo: 0.32,
        bar: 0.98
      }
    ]
  }
]

The aggregation on the date is fine, but now I would like to aggregate the objects in the results array.
The result of this aggregation should be of the following format:
[
  {
    aggDate: '2019-05-23',
    result: {
      foo: 0.45 // avg of all the `foo`, here: (0.58 + 0.32) / 2
      bar: 0.7 // avg of all the `bar`, here: (0.42 + 0.98) / 2
    }
  }
]

My problem here is that the keys foo and bar can change/new fields can be added in results objects. To avoid recoding the query each time it occurs, I want to use some generic way to say to MongoDB

Take this array of objects and reduce it into a single object where each value is the average of the same field in all objects.

I know the $reduce operator exists in MongoDB but I can't figure out how to use it and I am not even sure if it can help me here.

A: You do not need to use $reduce. Simply $sum can do the job.
db.collection.aggregate([
  { "$project": {
    "result": {
      "foo": { "$divide": [{ "$sum": "$results.foo" }, { "$size": "$results" }] },
      "bar": { "$divide": [{ "$sum": "$results.bar" }, { "$size": "$results" }] }
    }
  }}
])

Update-> according to dynamic keys inside results array
db.collection.aggregate([
  { "$project": {
    "aggDate": 1,
    "results": {
      "$reduce": {
        "input": {
          "$map": { "input": "$results", "in": { "$objectToArray": "$$this" }}
        },
        "initialValue": [],
        "in": { "$concatArrays": ["$$value", "$$this"] }
      }
    }
  }},
  { "$project": {
    "aggDate": 1,
    "result": {
      "$arrayToObject": {
        "$map": { "input": { "$setUnion": ["$results.k"] },
          "as": "m",
          "in": {
            "$let": {
              "vars": {
                "fil": {
                  "$filter": {
                    "input": "$results",
                    "as": "d",
                    "cond": { "$eq": ["$$d.k", "$$m"] }
                  }
                }
              },
              "in": {
                "k": "$$m",
                "v": { "$divide": [{ "$sum": "$$fil.v" }, { "$size": "$$fil" }] }
              }
            }
          }
        }
      }
    }
  }}
])

MongoPlayground
With more simplified version and with single $project stage
db.collection.aggregate([
  { "$project": {
    "aggDate": 1,
    "result": {
      "$let": {
        "vars": {
          "red": {
            "$reduce": {
              "input": {
                "$map": { "input": "$results", "in": { "$objectToArray": "$$this" }}
              },
              "initialValue": [],
              "in": { "$concatArrays": ["$$value", "$$this"] }
            }
          }
        },
        "in": {
          "$arrayToObject": {
            "$map": { "input": { "$setUnion": ["$$red.k"] },
              "as": "m",
              "in": {
                "$let": {
                  "vars": {
                    "fil": {
                      "$filter": {
                        "input": "$$red",
                        "as": "d",
                        "cond": { "$eq": ["$$d.k", "$$m"] }
                      }
                    }
                  },
                  "in": {
                    "k": "$$m",
                    "v": { "$divide": [{ "$sum": "$$fil.v" }, { "$size": "$$fil" }] }
                  }
                }
              }
            }
          }
        }
      }
    }
  }}
])

MongoPlayground
And both output as
[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "aggDate": "2019-05-23",
    "result": {
      "bar": 0.7,
      "foho": 0.32,
      "foo": 0.58,
      "sdbar": 0.98
    }
  }
]

A: You should run $unwind and aggregate the data using $group stages. You also need $arrayToObject and $objectToArray to work with dynamic keys. $reduce is not an option here since keys are unknwon
db.col.aggregate([
    {
        $project: {
            aggDate: 1,
            results: {
                $map: { input: "$results", in: { $objectToArray: "$$this" } }
            }
        }
    },
    {
        $unwind: "$results"
    },
    {
        $unwind: "$results"
    },
    {
        $group: {
            _id: { aggDate: "$aggDate", k: "$results.k" },
            sum: { $sum: "$results.v" },
            count: { $sum: 1 }
        }
    },
    {
        $project: {
            _id: 1,
            v: { $divide: [ "$sum", "$count" ] }
        }
    },
    {
        $group: {
            _id: "$_id.aggDate",
            results: { $push: { k: "$_id.k", v: "$v" } }
        }
    },
    {
        $project: {
            _id: 0,
            aggDate: "$_id",
            results: { $arrayToObject: "$results" }
        }
    }
])

Mongo Playground

A: EDIT:
not the most elegant but:
    {
        "$unwind" : "$result"
    },
    {
        "$addFields" : {
            "value" : {
                "$objectToArray" : "$result"
            }
        }
    },
    {
        "$unwind" : "$value"
    },
    {
        "$group" : {
            "_id" : null,
            "length" : {
                "$sum" : 1.0
            },
            "total" : {
                "$sum" : "$value.v"
            }
        }
    },
    {
        "$addFields" : {
            "avg" : {
                "$divide" : [
                    "$total",
                    "$length"
                ]
            }
        }
    }


text:
Q: Store a revenue based dataset in a relational database I have several revenue based datasets with below structure:
Subject                 2012   2013    2014    2015
online marketing         54      50     60      80
website ads             900     850    320     250
mobile ads               60      80    120     130
video ads                30      40     50      80

there are over 10 tables (example: website_1 / website_2 / website_3). I was planning to change the dataset to below structure so I can join tables and do comparison of data based on year.
Subject                 revenue   year
online marketing        54        2012
online marketing        50        2013
online marketing        60        2014
online marketing        80        2015
website ads             900       2012
....
mobile ads              60        2012
....
video ads
...

I dont think the above structure is efficient.
what would be the best way to store such data in a relational database?

A: Why do you believe that the second design is not efficient? It would be the design that I would recommend to you. It allows the data set to be scaled to add more subjects and more years without needing to adjust the schema.
To extend the normalization, place the subjects within their own table and reference that from your main table. This will reduce duplicate names in your main table and also reduce the space required to store your data.
Depending on whether you can or not, you could also reduce your table count down to 3 by adding a column to your main tables called website, then create a new table to hold the website list and reference this again from your main table.
You would then end up with a structure similar to this:
create table "websites"
(
  id int not null primary key,
  name varcher(64) not null unique
);
create table "subjects"
(
  id int not null primary key,
  name varcher(100) not null unique
);
create table "revenue"
(
  id int not null primary key,
  website int not null,
  subject int not null,
  year smallint not null,
  value int not null,
  constraint uk_revenue unique (website, subject, year),
  constraint fk_revenue_website foreign key (website) references website (id),
  constraint fk_revenue_subject foreign key (subject) references subject (id)
);

This creates a table for the website, a table for subjects and one for the revenue. The revenue table contains references to the former tables and also creates a unique constraint across the combination of the website, subject and year to prevent duplicate entries.
Naturally, normalization makes query definitions larger (as you now need to join to other tables) but this is trivial really and the ability to scale out to multiple websites, subjects and years easily is in my opinion worth the extra effort of writing a longer query.
After time, should the data set grow to a point whereby querying it becomes very slow, you can either archive off data that you don't need anymore or warehouse it in a denormalized fashion.


text:
Q: Spoofing an echo reply Given that I'm on a local network, if I can capture a ICMP echo request packet, and considering that I want to spoof a echo reply, what part of the original packet would I need to change supposing I make a copy of the original before i send it back?  I'm guessing the IP header would need to change, (the destination IP of the original would become the source, and vice versa) as well as the ICMP header (the type would need to change to ECHO_REPLYPACKET).  But besides those 2 are there any others?

A: Quoting RFC 792 :
Echo or Echo Reply Message

0                   1                   2                   3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|     Type      |     Code      |          Checksum             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|           Identifier          |        Sequence Number        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|     Data ...
+-+-+-+-+-

To form an echo reply message, the source and destination addresses
are simply reversed, the type code changed to 0, and the checksum
recomputed.

Identifier and Sequence Number must be 0 as well.
RFC 1071 shows you how to calculate the Checksum


text:
Q: check files in the folder for more than ten hours using awk command I created script to check the files in the folder for 4 hours ago it is working fine because I am using HP UX.
fourago=`date  +"%m %d %H %M" | awk '{ fourago=$3 - 4 ; if ((fourago<4)&&(fourago>3)) { fourago=59 } printf("%.2d%.2d%.2d%.2d\n",$1,$2,fourago,$4) }'`

To check 16 hours ago can I use this like below
sixteenhourago=`date  +"%m %d %H %M" | awk '{ sixteenhourago=$3 - 16 ; if ((sixteenhourago<16)&&(sixteenhourago>3)) { fourhourago=59 } printf("%.2d%.2d%.2d%.2d\n",$1,$2,fourhourago,$16) }'`

I created above command based on below logic Not sure it is correct or not Please help on this.
 $3 (current Hour) -1, or one hour ago.  To make it 16 hours ago we need to use -16.
some files might be 3 hours 59 minutes ago those should still be counted.


text:
Q: What do you call the "@Body()" in the following function signature: "create(@Body() createCatDto: CreateCatDto) {}" in typescript/nestjs I'm trying to learn NestJS, and I noticed the following function signatures on their documentation:
@Post()
async create(@Body() createCatDto: CreateCatDto) {
  this.catsService.create(createCatDto);
}

it's my first time seeing the @Body() before the parameter name. What is it? and what do you call it? It looks like its a decorator but feels like it somehow casts the parameter, but i think that's the point of the parameter type right?
Regards,

A: These are called param decorators you can further read this for a better explanation
https://docs.nestjs.com/custom-decorators#param-decorators
Coming to your question @Body() is a param decorator which parses your incoming JSON payload into the Dto (Data Transfer Object) Structure  Provided (Dto can be a class or can be an interface).
For example assume the following Dto Structure :
export class CreateCatDto {
  name: string;
  age: number;
  breed: string;
}

This structure expects the client-side to pass the following structure JSON
{
 "name" : "abc",
 "age"  : 22,
 "breed" : "abc"

}

And then @Body() param decorator will parse the incoming JSON payload to the Dto provided.
And hence you can simply get the JSON values in the shape of class object or inteface Like this :
@Post()
async create(@Body() createCatDto: CreateCatDto) {
  console.log(createCatDto.name);
  console.log(createCatDto.age);
  console.log(createCatDto.breed);
  this.catsService.create(createCatDto);
}

Note: Any parameter missing will result undefined in Dto.


text:
Q: Is it possible to trigger an intent based on the response(from webhook) of another intent? I have an intent named "intent.address" with the action name "address_action" and the training phrase "My address". When this intent is triggered, response comes from my webhook saying "Alright! your address is USER_ADDRESS".
Used app.ask() here

What I want is, when this response comes from the webhook then another intent named "intent.conversation" (event name "actions_intent_CONFIRMATION")(here also webhook enabled) gets triggered, which will ask for user confirmation to continue or not?
For example :
Alright your address is USER_ADDRESS

then next
Do you want ask address/directions again?

A: Intents do not reflect what your webhook says, it reflects what the user says. Intents are what the user intends to do - what they want.
So no, you can't just trigger another Intent this way. There are a few ways to do what you're asking, however.
Using the Confirmation helper with the actions-on-google v1 node.js library
If you really want to use the Confirmation helper, you need to send back JSON, since the node.js v1 library doesn't support sending this helper directly. Your response will need to look something like:
{
  "data": {
    "google": {
      "expectUserResponse": true,
      "systemIntent": {
        "intent": "actions.intent.CONFIRMATION",
        "data": {
          "@type": "type.googleapis.com/google.actions.v2.ConfirmationValueSpec",
          "dialogSpec": {
            "requestConfirmationText": "Please confirm your order."
          }
        }
      }
    }
  }
}

If you're not already doing JSON in your responses, then you probably don't want to go this route.
Using the Confirmation helper with the actions-on-google v2 node.js library
If you've already switched to v2 of this library, then you have the ability to send a Confirmation with something like this
app.intent('ask_for_confirmation_detail', (conv) => {
  conv.ask("Here is some information.");
  conv.ask(new Confirmation('Can you confirm?'));
});

Or you can just use the Dialogflow way of doing this
In this scenario - you don't use the Confirmation helper at all, since it is pretty messy.
Instead, you include your question as part of the response, and you add two Followup Intents - one to handle what to do if they say "yes", and one if they say "no".


text:
Q: Elgato Wave 3 only as input or output but not both I was not able to find anything similar to this, so I hope this is not a duplicated question...
I have the following issue with my Elgato Wave 3 microphone: when I want to use it as an input (microphone), it works like a charm, but when I connect the headphones at the back of it, using it also as an output (selecting it on settings panel or PulseAudio control), the microphone stops registering as an input, so I cannot use it anymore as a microphone, but headphones works...
I saw that it could have missing the output + input or duplex profile or something related to the profile, but I have no idea if I can add it or what can I do to solve this. I tried researching about pactl but I do not understand it fully.
The profiles I see are:

*

*Analog Stereo Output

*Digital Stereo (IEC958) Output

*Analog Mono Input

*Off

Thank you !

A: I had the same issue. Solved this and tested through Zoom recordings.
Currently on Pop Os - 20.10 Using Generic Pulse Mixer

*

*Open Pulse Audio Volume Mixer

*Go to Configuration Tab

*Elgato Wave 3 device DropSelect -> "Analog Stereo Output + Multichannel Input"

*Input Devices Tab > Elgato Wave 3 Multichannel -> Port: Select Multichannel Input

*Output Tab > Elgato Wave:3 Analog Stereo -> Port:  Analog Output.

*Adjust controls physical on the device to suit input gain, output and Crossover to taste.

You may need to select "Show : All devices" if not showing up the first time, at the bottom of the mixer window.
You may need to restart Pulse Audio via the terminal with
systemctl --user restart pulseaudio.service
If your device is not seen.
Have a test call and record it. Hope it helps others.

A: I was able to "fix it" just by upgrading Ubuntu to 20.04... it seems it is related to the Kernel or similar, I am ignorant about that...

Who ever downvoted, upgrade and it will work... It is the kernel version...


text:
Q: how to extract all the href from the a tags and test if they start with '/' or not using beautifulsoup? - Python I'm using beautifulsoup to extract all the hrefers from the a tags, but some of the hrefers starts like "/videos.com" instead "www.example/videos.com", they haven't the domain. So what I'm trying to do is extracting all the hrefers from the a tags but I want to test if it starts with "/", if so I will add the domain "www.example.com".
I wanted something like:
    from bs4 import BeautifulSoup

    domain_name = 'www.example.com'

    for a in soup.find_all('a', href=True):
        if a['href'] starts with '/':
            link = domain_name + a['href']
        else:
            link = a['href']

How to extract all the hrefs from the a tags and test if they start with '/' or not?
I was thinking to use regex, but I'm not sure how to say "if a['href'] starts with regex.

A: I think you are looking for .startswith():
from bs4 import BeautifulSoup

domain_name = 'www.example.com'

for a in soup.find_all('a', href=True):
    if a['href'].startswith('/'):
        link = domain_name + a['href']
    else:
        link = a['href']

But note you can also operate with slicings:
if a['href'][0] == '/':

Some performance analysis can be found here.


text:
Q: Improve Crawl rate We have  2 wfe, and 2 AS.
We have 18,000 sites worth 500GB of data in 5 content DBs
We have continuous crawl enabled every 15 minutes, but every crawl  takes about 1 hour and 30 minutes.
We have about 7 million searchable items.
We need to improve the crawl rate, in my opinion its too low (4.3)
Question :
How can the crawl rate be improved? Add servers that do only crawling and content processing for example?

A: You could consider using dedicated servers for search. There are guidance on Technet regarding the relatively new "best practice" physical topology called Streamlined Topologies, where one setup is using a dedicated server for search.
Streamlined topologies is an attempt to make the server topology more simple, and configure it based on latency/cpu/ram usage rather than the older topology that was more designed with roles in mind.
You could choose to run a dedicated setup for search to free resources for indexing. In a typical Streamlined setup, it is recommended to scale search out on dedicated servers when going above 2 batch servers (roughly translates to App servers in the old application server topology).
Also read the hardware requirements for search topologies in the article "Scale search for performance and availability.." to be sure that especially your server running index component has enough RAM.
Streamlined topologies.
Streamlined topologies topology examples.


text:
Q: Asterisk new PJSIP driver security option I have a working asterisk environment, but I get a lot of unwanted traffic, like sip scanners of people who even try to call as a guest.
I'm using res_pjsip, the configuration is stored in pjsip.conf. But I can't find options like alwaysauthreject and allowguests in this configuration.
And I can't find any of the security options of pjsip on the wiki. Only for chan_sip.
Can someone tell me that these options are present in this driver? Or that they have ben replaced by an other function.
Thank you in advance

A: I have found an answer.
alwaysauthreject
allowguests

These 2 functions aren't part of pjsip.conf anymore and are standard.
Furthermore you need to secure your server with a firewall and fail2ban. Security needs to be done on OS level.

A: It's not clear what type of security options you are looking for - since simplistic restrictions like refusing guest, requiring registration, etc. will not reduce the load created by SIP scanners, hackers trying to get in, etc.
If you are trying to secure your server check out this page www.voip-info.org for details.  Solutions range from basic Asterisk server settings to perimeter protection to advanced security like Asterisk plug-ins which look at the source IP of attackers to block geographic areas, watch for heuristic attack patterns, etc.
You will find that some older apps/plus-ins struggle with PJSIP but some fully support it.

A: According to this:

There is no option for "alwaysauthreject". It is always on.
There is no equivalent settings functionality wise for "domain" and
  "allowexternaldomains".
The "allowguest" option is always set to no unless you create an
  endpoint named "anonymous".
The "deny" and "permit" options can be set at a global and endpoint
  basis.

Example of old configuration:
alwaysauthreject=yes

domain = asterisk.mydomain.com

allowexternaldomains = no

allowguest = no

deny=0.0.0.0/0.0.0.0
permit=10.0.0.0/255.0.0.0

And as the author of the question wrote, you have to use a firewall and fail2ban.
Here are the ports used (taken from here):

*

*4569 UDP - IAX/2, forward this port if you have purchased IAX trunking , IAX can traverse your firewall easier than SIP

*5060 UDP - SIP

*10000 - 20000 UDP - SIP RTP Media   (configured inside rtp.conf)


text:
Q: Transparent gradient for top and bottom of background image css Is it possible to place transparent gradients over both the top and the bottom of a background image? At the moment I can only find it being done on one or the other.
UPDATE:
Tried by putting 2  with in the area that the background image is being applied then used two classes(one the reverse of the other to try and create the desired effect but it didn't quite workout. I'd also like it if possible if it didn't affect any other content and it's positioning within the section it is being applied.
CSS
.picture-gradient {
z-index: 1;
height: 50px;
width: auto;
position: relative;
background: -webkit-linear-gradient(rgba(64,64,64,1), rgba(64,64,64,0));
background: -o-linear-gradient(rgba(64,64,64,1), rgba(64,64,64,0));
background: -moz-linear-gradient(rgba(64,64,64,1), rgba(64,64,64,0));
background: linear-gradient(rgba(64,64,64,1), rgba(64,64,64,0));
padding: 15px;
margin: -15px;
}

.picture-gradient2 {
z-index: 1;
height: 50px;
width: auto;
position: relative;
background: -webkit-linear-gradient(rgba(64,64,64,0), rgba(64,64,64,1));
background: -o-linear-gradient(rgba(64,64,64,0), rgba(64,64,64,1));
background: -moz-linear-gradient(rgba(64,64,64,0), rgba(64,64,64,1));
background: linear-gradient(rgba(64,64,64,0), rgba(64,64,64,1));
padding: 15px;
margin: -15px;
}

HTML(Basic)

    enter code here

Text

More Text

        <form class="form-wrapper2 searchbar2">

                    <input type="text" placeholder="Search for activities and places" required />
                    <button type="submit"></button>

        </form>

A: Something like this?
JsFiddle
http://jsfiddle.net/r3wN8/
CSS
background: -moz-linear-gradient(top,  rgba(255,255,255,0) 0%, rgba(41,137,216,1) 50%, rgba(125,185,232,0) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,0)), color-stop(50%,rgba(41,137,216,1)), color-stop(100%,rgba(125,185,232,0))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  rgba(255,255,255,0) 0%,rgba(41,137,216,1) 50%,rgba(125,185,232,0) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  rgba(255,255,255,0) 0%,rgba(41,137,216,1) 50%,rgba(125,185,232,0) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  rgba(255,255,255,0) 0%,rgba(41,137,216,1) 50%,rgba(125,185,232,0) 100%); /* IE10+ */
background: linear-gradient(to bottom,  rgba(255,255,255,0) 0%,rgba(41,137,216,1) 50%,rgba(125,185,232,0) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00ffffff', endColorstr='#007db9e8',GradientType=0 ); /* IE6-9 */

Generated by http://www.colorzilla.com/gradient-editor/

A: You can have multiple stops in a gradient, so if you wanted the top 10% to fade to transparent and the bottom 10% to fade back, you could do something like this:
background-image: linear-gradient(
    to bottom,
    rgba(64, 64, 64, 1) 0%,
    rgba(64, 64, 64, 0) 10%,
    rgba(64, 64, 64, 0) 90%,
    rgba(64, 64, 64, 1) 100%
);

Demo with  tag: http://jsfiddle.net/sh6Hh/ or without the extra
: http://jsfiddle.net/sh6Hh/262/
Demo with css background picture: http://jsfiddle.net/sh6Hh/1/


text:
Q: PHP: Curl is still not returning the sourcecode I have now tried a lot of different solutions but non of those curl settings has ever worked... I just want to get the sourcecode of the webpage back...
And yeah, I know there is file_get_contents(). But I need and want to use curl instand of file_get_contents(). Where is the error? How can I get the content of the webpage with curl?
$url = "https://google.de";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_HTTPHEADER, array(
//    "API-Token: " . APITOKEN . "",
//    "API-Secret: " . APISECRET . "",
//));

$response = curl_exec($curl);
echo "This is the response...:\n" . $response;

$response is always empty... Even if I save the variable to a text file... Here the picture which proves it!
Picture
Greetings and Thank You!

A: Please dump curl_error($curl). Then you will get "SSL certificate problem: unable to get local issuer certificate".
You can simply set the following options to avoid this error:
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

Warn: the above solution disables SSL verification and is not secure. A secure solution is to set the certification of cURL:
curl_setopt ($curl, CURLOPT_CAINFO, "PATH_TO/cacert.pem");

A:             If you will check error  then you will show below error

        if(!curl_exec($curl)){
          die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
           }

 Error: "SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed" - Code: 60

    To solve this issue you can follow this link-

    https://wehavefaces.net/fixing-ssl-certificate-problem-when-performing-https-requests-in-php-e3b2bb5c58f6


text:
Q: Error parsing JSON using Bing Traffic API I'm trying to get some traffic data using the Bing Traffic API, but I keep getting a JSONException.
The JSON is located HERE. I used a JSON formatter located here in order to better get an idea of the data that's available to me. The url is publicly facing so I don't know if I need to provide some sort of authentication data or not, because I can just plug the url into my browser and view the JSON result right there.
Here's how I'm making the call
String url = "http://dev.virtualearth.net/REST/v1/Traffic/Incidents/37,-105,45,-94?key=" + API_KEY;

    // Create JSONParser instance
    JSONParser jParser = new JSONParser();

    // Get JSON from url
    final JSONObject jObject = jParser.getJSONFromUrl(url);

    try {
        JSONArray trafficData = jObject.getJSONObject(TAG_RESOURCESETS).getJSONArray(TAG_RESOURCES);
        Log.w("TrafficIncidentProvider", "Traffic Array consists of " + trafficData.toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I'm trying to get the object named "resourceSets" and the object named "resources", since it seems that that's where the data I need is embedded inside.. but obviously I'm going about it the wrong way because logCat is telling me that there's no value that matches that data. Here's the error logcat is giving me
  12-10 17:12:42.924: E/JSON Parser(26560): Error parsing data  org.json.JSONException:   End of input at character 0 of
  12-10 17:12:42.944: W/System.err(26560): org.json.JSONException: No value for  resourceSets
  12-10 17:12:43.004: W/System.err(26560):  at org.json.JSONObject.get(JSONObject.java:354)
  12-10 17:12:43.004: W/System.err(26560):  at org.json.JSONObject.getJSONObject(JSONObject.java:569)
  12-10 17:12:43.014: W/System.err(26560):  at com.brightr.weathermate.providers.TrafficIncidentProvider.getTrafficIncidents(TrafficIncidentProvider.java:43)
  12-10 17:12:43.014: W/System.err(26560):  at com.brightr.weathermate.activities.LocationMapview$showTrafficConditions.doInBackground(LocationMapview.java:323)
  12-10 17:12:43.024: W/System.err(26560):  at com.brightr.weathermate.activities.LocationMapview$showTrafficConditions.doInBackground(LocationMapview.java:1)
  12-10 17:12:43.034: W/System.err(26560):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
  12-10 17:12:43.034: W/System.err(26560):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
  12-10 17:12:43.044: W/System.err(26560):  at java.util.concurrent.FutureTask.run(FutureTask.java:138)
  12-10 17:12:43.044: W/System.err(26560):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
  12-10 17:12:43.044: W/System.err(26560):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)

Any clarity on this issue would be greatly appreciated, guys. Thanks as always!
EDIT: As requested, here is my JSONParser code which contains my HttpPost method
 public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parsing the string to a JSON object
    try {
        if(json != null){
        jObj = new JSONObject(json);
        }else{
            jObj = null;
        }
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

A: Parse this json as:
         try {
                JSONObject jobject=new JSONObject("Your_json_String");
                JSONArray jarray=jobject.getJSONArray("resourceSets");
                  System.out.println("dateNow jarray :"+jarray.length());
                  for(int i=0;i<jarray.length();i++){
                      if(!jarray.isNull(i)){
                      JSONObject jobjresources=jarray.getJSONObject(i);
                      System.out.println("dateNow jobjresources :"+jobjresources.length());
                      //estimatedTotal
                      if(!jobjresources.isNull("estimatedTotal")){
                        String str_estimatedTotal=jobjresources.getString("estimatedTotal");
                        System.out.println("resources str_estimatedTotal :"+str_estimatedTotal);

                      }
                      else{
                          System.out.println("resources str_estimatedTotal NULL for :"+i+" ITEM");
                      }
                        if(!jobjresources.isNull("resources")){
                        //resources
                        JSONArray jarrresources=jobjresources.getJSONArray("resources");
                        for(int j=0;j<jarrresources.length();j++){
                            System.out.println("$$$$$$$$$$ ITEM "+j+" START $$$$$$$$$$$$$$$$#");
                            if(!jarrresources.isNull(j)){

                            JSONObject jobjjarrresources=jarrresources.getJSONObject(j);
                            if(!jobjjarrresources.isNull("__type")){
                              //__type"
                            String str_type=jobjjarrresources.getString("__type");
                            System.out.println("resources str_type :"+str_type);
                            }
                            else{
                                System.out.println("resources __type NULL for :"+j+" ITEM");
                            }
                              //description"
                            if(!jobjjarrresources.isNull("description")){
                            String strdescription=jobjjarrresources.getString("description");
                            System.out.println("resources description :"+strdescription);
                            }
                            else{
                                System.out.println("resources description NULL for :"+j+" ITEM");
                            }
                              //lane"
                            if(!jobjjarrresources.isNull("lane")){
                            String strlane=jobjjarrresources.getString("lane");
                            System.out.println("resources lane :"+strlane);
                            }
                            else{
                                System.out.println("resources lane NULL for :"+j+" ITEM");
                            }
                              //lane"
                            if(!jobjjarrresources.isNull("point")){
                                JSONObject jobjpoint=jobjjarrresources.getJSONObject("point");
                                //point
                                if(!jobjpoint.isNull("coordinates")){
                                JSONArray jarcoordinates=jobjpoint.getJSONArray("coordinates");
                                for(int k=0;k<jarcoordinates.length();k++){
                                    //JSONObject jobjcoordinates=jarcoordinates.getString(k);
                                     if(!jarcoordinates.isNull(k)){
                                    String str_zero=jarcoordinates.getString(k);
                                    System.out.println("coordinates :"+k+": "+str_zero);
                                     }
                                     else{
                                         System.out.println("coordinates :"+k+" is NULL:"+j+" ITEM");
                                     }
                                 }
                                }
                                else{
                                    System.out.println("resources coordinates NULL for :"+j+" ITEM");
                                }
                            }
                            else{
                                System.out.println("resources point NULL for :"+j+" ITEM");
                            }

                              //roadClosed"
                              //lane"
                            if(!jobjjarrresources.isNull("roadClosed")){

                            String strroadClosed=jobjjarrresources.getString("roadClosed");
                            System.out.println("resources roadClosed :"+strroadClosed);
                            }
                            else{
                                System.out.println("resources roadClosed NULL for :"+j+" ITEM");
                            }
                              //severity"
                            if(!jobjjarrresources.isNull("severity")){
                            String strroadseverity=jobjjarrresources.getString("severity");
                            System.out.println("resources severity :"+strroadseverity);
                            }
                            else
                            {
                                System.out.println("resources severity NULL for :"+j+" ITEM");
                            }
                        }
                            else{
                                System.out.println("jarrresources    NULL for :"+j+" ITEM");
                            }

                            System.out.println("##################### ITEM "+j+" END ##############");
                        }
                       }
                        else{
                            System.out.println("resources    NULL for :"+i+" ITEM");
                        }
                  }

                   else{
                       System.out.println("resources     NULL for : ITEM");
                      }
          }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

}


text:
Q: What is the best way to compute string similarity? Consider you are given with two strings S1 and S2. What are the different algorithms available to compute how similar these strings in terms of their context and which one of them is the most efficient in terms of accuracy?

A: If you are going to use python, the most recent technology is word embedding. You can think of it as converting words to high-dimensional vectors (from 200 to 1000 dimensions) by training on millions of documents.
For example, if your string is "Human computer interaction", you would be looking for something like this.
[(2, 0.99844527), # The EPS user interface management system
(0, 0.99809301), # Human machine interface for lab abc computer applications
(3, 0.9865886), # System and human system engineering testing of EPS
(1, 0.93748635), # A survey of user opinion of computer system response time
(4, 0.90755945), # Relation of user perceived response time to error measurement
(8, 0.050041795), # Graph minors A survey
(7, -0.098794639), # Graph minors IV Widths of trees and well quasi ordering
(6, -0.1063926), # The intersection graph of paths in trees
(5, -0.12416792)] # The generation of random binary unordered trees

from: https://radimrehurek.com/gensim/tut3.html

A: Try following algorithms:
Jaro–Winkler distance
Levenshtein distance these 2 algos are helpful for the string matching. It is depends on your string. According to string decide which is feasible for you.


text:
Q: Unable to assign value from then callback I'm trying to get a Future value and assign it to a bool. I cannot use async/await.
This is my code, but value just prints null. futureFunction returns Future<bool>
bool value;
futureFunction().then((a) { value = a; } );
print(value);

A: if you put it inside StatefulWidget, this should work
bool value;

_StatefulWidgetDemoState() {
  futureFunction().then(
    (returnedValue) => setState(() {
      value = returnedValue;
    })
  );
}

A: then will not wait to finish any task. After completing the future function, code inside then will execute. Instate of using then use await keyword and don't forget to make the function async.
Example:
getBool() async{
 bool value = await futureFunction();
 print(value);
}


text:
Q: How to create ARM GCC makefile for a project that includes freeRTOS and libraries? I am working on a project which uses STM32L053 nucleo board.
I need to create a project for STM32L053, with freeRTOS and STM's STM32CubeL0 libraries. I have FreeRTOS port ready for implementation.
But I don't know how to add this freeRTOS and libraries to my project.

A: Its always best to start with an existing project, then adapt that.  If you don't have a suitable existing project then I suggest:
1) Create a makefile that builds a simple hello world style application for your hardware - without adding in the FreeRTOS source files yet.
2) Ensure your project builds and runs as expected.  That will give you a known good starting point before you add in more source code.
3) Add the FreeRTOS source files to your project.  You will find information on the files that are needed, and the include paths that must be set, on the following page: http://www.freertos.org/Creating-a-new-FreeRTOS-project.html .  The port layer files you need are in the FreeRTOS/source/portable/gcc/ARM_CM0 directory (assuming this is a Cortex-M0 part?).
4) You will need a FreeRTOSConfig.h file.  The one used by the official FreeRTOS STM32F051 demo will probably be a good starting point.
5) Make sure the project builds, and you can still run the hello world application.
6) Now create your FreeRTOS tasks - here is a good place to start: http://www.freertos.org/Hardware-independent-RTOS-example.html

A: You can also have a look at PolyMCU: https://github.com/labapart/polymcu
PolyMCU is an open-source firmware framework. It is based on CMake, so you can build on any OS (Windows/Linux/MacOS).
PolyMCU uses vendor SDKs (such as ST's STM32Cube).
There are few examples (including one for FreeRTOS and CMSIS RTOS) https://github.com/labapart/polymcu/tree/master/Application/Examples that you can duplicate to quickly start.


text:
Q: Generating different sizes of Images Does anyone know how Facebook, Pinterest and Twitter keep different sizes of images of a given image. Facebook, for example, scales a given image to 4 different sizes and stores them. Pinterest keeps two sizes of images (one is 236px and the other is 736px); tumblr does the same with different values. I am trying to do the same thing but i do not get correct results. In python, using the Image library (from PIL), if i use resize, image gets stretched, if i used thumbnails, i get images based on aspect ratio rather than the dimensions i want (e.g. 300px by 300px).
If you look at one's Facebook profile picture, it is scaled from 520px by 520px to 160px by 160px, but there was no cropping done to achieve that. If anyone has an idea of how can this be achieved, I would really like to know

A: I guess this may help you Demo
HTML

    <form>

            Width:
            <input id="width" type="number" name="width" value="100">
            Height:
            <input id="height" type="number" name="height" value="100">
            <input type="checkbox" id="crop">
            crop thumbnail background:<input type="text" value="white" id="bg">

            <input type="checkbox" id="jpeg">
            JPG Quality
    <input type="number" max="100" min="0" value="50" id="quality"> %

This demo needs a canvas and FileReader capable browser

    </form>
    <output>

Thumbnails (click to remove, hover to see filesize)

    </output>

js
/*
  canvasthumber by Christian Heilmann
  Version: 1.0
  Homepage: http://thewebrocks/demos/canvasthumber
  Copyright (c) 2012, Christian Heilmann
  Code licensed under the BSD License:
  http://wait-till-i.com/license.txt
*/
(function () {
    var s = document.querySelector('#dropzone'),
        o = document.querySelector('output'),
        cr = document.querySelector('#crop'),
        j = document.querySelector('#jpeg'),
        c = document.createElement('canvas'),
        cx = c.getContext('2d'),
        thumbwidth = thumbheight = 100,
        crop = false,
        background = 'white',
        jpeg = false,
        quality = 0.8;

    function init() {
        if (typeof FileReader !== 'undefined') {
            document.body.classList.add('dragdrop');
            s.innerHTML = 'Drop images here';
            cr.addEventListener('click', function (evt) {
                document.body.classList.toggle('cropon');
            }, false);
            j.addEventListener('click', function (evt) {
                document.body.classList.toggle('jpegon');
            }, false);
            o.addEventListener('click', function (evt) {
                var t = evt.target;
                if (t.tagName === 'IMG') {
                    t.parentNode.removeChild(t);
                }
            }, false);
            s.addEventListener('dragover', function (evt) {
                evt.preventDefault();
            }, false);
            s.addEventListener('drop', getfiles, false);
        }
    };

    function getfiles(ev) {
        var files = ev.dataTransfer.files,
            url = window.URL || window.webkitURL,
            objURL = url.createObjectURL || false;

        if (files.length > 0) {
            var i = files.length;
            while (i--) {
                var file = files[i];
                if (file.type.indexOf('image') === -1) {
                    continue;
                }
                if (objURL) {
                    loadImage(url.createObjectURL(file));
                } else {
                    var reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = function (ev) {
                        loadImage(ev.target.result);
                    };
                }
            }
        }
        ev.preventDefault();
    }

    function loadImage(file) {
        var img = new Image();
        img.src = file;
        img.onload = function () {
            grabformvalues();
            imagetocanvas(this, thumbwidth, thumbheight, crop, background);
        };
    }

    function grabformvalues() {
        thumbwidth = document.querySelector('#width').value;
        thumbheight = document.querySelector('#height').value;
        crop = document.querySelector('#crop').checked;
        background = document.querySelector('#bg').value;
        jpeg = document.querySelector('#jpeg').checked,
        quality = document.querySelector('#quality ').value / 100;
    }

    function imagetocanvas(img, thumbwidth, thumbheight, crop, background) {
        c.width = thumbwidth;
        c.height = thumbheight;
        var dimensions = resize(img.width, img.height, thumbwidth, thumbheight);
        if (crop) {
            c.width = dimensions.w;
            c.height = dimensions.h;
            dimensions.x = 0;
            dimensions.y = 0;
        }
        if (background !== 'transparent') {
            cx.fillStyle = background;
            cx.fillRect(0, 0, thumbwidth, thumbheight);
        }
        cx.drawImage(
        img, dimensions.x, dimensions.y, dimensions.w, dimensions.h);
        addtothumbslist(jpeg, quality);
    };

    function addtothumbslist(jpeg, quality) {
        var thumb = new Image(),
            url = jpeg ? c.toDataURL('image/jpeg', quality) : c.toDataURL();
        thumb.src = url;
        thumb.title = Math.round(url.length / 1000 * 100) / 100 + ' KB';
        o.appendChild(thumb);
    };

    function resize(imagewidth, imageheight, thumbwidth, thumbheight) {
        var w = 0,
            h = 0,
            x = 0,
            y = 0,
            widthratio = imagewidth / thumbwidth,
            heightratio = imageheight / thumbheight,
            maxratio = Math.max(widthratio, heightratio);
        if (maxratio > 1) {
            w = imagewidth / maxratio;
            h = imageheight / maxratio;
        } else {
            w = imagewidth;
            h = imageheight;
        }
        x = (thumbwidth - w) / 2;
        y = (thumbheight - h) / 2;
        return {
            w: w,
            h: h,
            x: x,
            y: y
        };
    };
    init();
})();

css
* {
    margin: 0;
    padding: 0;
}
body {
    font-size: 15px;
    font-family: helvetica, arial, sans-serif;
    padding: 2em;
}
footer, section, output, header, aside, figure {
    display: block;
}
a {
    color: #060;
}
h1 {
    font-size: 24px;
    padding-bottom: 10px;
}
.dragdrop #dropzone {
    width: 250px;
    height: 250px;
    border-radius: 10px;
    border: 2px dotted #393;
    background: #cfc;
    color: #393;
    text-align: center;
    line-height: 200px;
    float: left;
    margin-right: 10px;
}
.dragdrop output {
    width: 520px;
    display: block;
    float: left
}
output img {
    margin: 5px;
    display: block;
    float: left;
}
footer {
    clear:both;
}
section, header, footer {
    width: 800px;
}
input[type=number] {
    width: 3em;
}
input[type=checkbox] {
    margin-right: 10px
}
label {
    padding-right: 10px;
    font-weight: bold;
}
#bg {
    width: 5em;
}
.jpeg {
    opacity: 0.2;
    -webkit-transition: 1s;
    -moz-transition: 1s;
    -ms-transition: 1s;
    -o-transition: 1s;
    transition: 1s;
}
.crop {
    opacity: 1;
    -webkit-transition: 1s;
    -moz-transition: 1s;
    -ms-transition: 1s;
    -o-transition: 1s;
    transition: 1s;
}
.cropon .crop {
    opacity: 0.2;
}
.jpegon .jpeg {
    opacity: 1;
}
.options {
    background: #060;
    color: #fff;
    border-radius: 5px;
    margin: 1em 0;
    padding: 5px 10px;
    box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.8);
}
h1 {
    text-transform: uppercase;
    color: #333;
    letter-spacing: -1px;
}
output img {
    display:block;
}
output img:hover {
    box-shadow: 0 0 5px 5px #ccc;
    border: 1px solid #999;
}
h2 {
    font-size: 12px;
}
footer {
    clear: both;
    text-align: right;
    padding: 50px 0 20px 0;
    font-size: 12px;
}
footer a {
    color: #000;
}


text:
Q: Is there a way to get a list of all Dropbox Share Folders with their members? I've reached out to Dropbox on this and they advised that there isn't a way to do it through their platform, they suggested using other tools like GitHub, Zapier, and the like.
I have admin access to Dropbox and I have little to no experience coding, I've seen a few API's that could help me with what I'm trying to accomplish.
Is there an App or service I can use along with the Dropbox API to fetch all Share folders and their members? We are talking about 300+ folders so entering all the info manually won't be ideal since this task is time sensitive.
Thank you for any input or advise you guys can give me on this


text:
Q: Can I use both version of bootstrap? Here in my question remove space in bootstrap template the answer (unaccepted one) is in both condition i.e. span* it's older version of bootstrap and col-* it's newer version of bootstrap.
So, my question is that can I use both version of bootstrap styling? Should I include both version of bootstrap to get work?

Or if I include there might be conflict?

Or, Can I integrate both css files in one?

A: In fact, you may add a custom CSS file that re-wrap all old CSS names to the new definitions.
Looking at changes seems to not raise any conflict (I may be wrong because I didn't try).
On the contrary, having both CSS files (Bootstrap2 and Bootstrap3) will obviously raise problems depending on the order you load the CSS files (remember that CSS are "casscading" definition, only the last one is taken into account).
But, indeed, an upgrade of your HTML code would be the simplest way to go. Using automatic tools such as Bootply, will make it smoother.


text: Q: Dual Screen Application C/Linux I have a stable application written in C using GTK. I have a client who would like us to provide him with a version of the application that runs in dual-screen mode. I'm investigating options for having the application GUI being split in to two different windows and ultimately appear on two separate screens. Any leads on where I can get started are appreciated. Thanks in advance!


text:
Q: Errors using subfigure \begin{figure}[h]
   \begin{subfigure}
       \includegraphics[scale=0.2]{section7task4_1}
       \caption{low frequency noise}
   \end{subfigure}
   \begin{subfigure}
       \includegraphics[scale=0.2]{section7task4_2}
       \caption{spectrally narrow noise}
   \end{subfigure}
\end{figure}

Do any one see why I should get errors on this?

A: Similar to a minipage environment, you have to specify the width of the subfigure environment, i.e. \begin{subfigure}{<width>}. For example:
\documentclass{article}
\usepackage{subcaption}
\usepackage[demo]{graphicx}

\begin{document}

\begin{figure}[h]
   \begin{subfigure}{0.45\linewidth}
       \centering
       \includegraphics[scale=0.2]{section7task4_1}
       \caption{low frequency noise}
   \end{subfigure}\hfill
   \begin{subfigure}{0.45\linewidth}
       \centering
       \includegraphics[scale=0.2]{section7task4_2}
       \caption{spectrally narrow noise}
   \end{subfigure}
\end{figure}

\end{document}


text:
Q: 'While true' loop suddenly stops So I want to run a one liner while loop that prints the size of a file whilst I'm coping it, so I tried this:
while true; size1=$(ls -hl /Volumes/WD\ Elements/redundancy/20221117_0148_backup.tar.gz | awk '{print($5)}'); do printf "$size1\r"; done
So for a few seconds it works, I can see the size of the file growing and in the same line of the terminal, but then it stops for no reason.
I googled to no avail to see what could be breaking it, but can't find a reason why.
Am I bottlenecking the Terminal? Should I insert a sleepsomewhere?
Any help would be greatly appreciated!
EDIT: Of course after googling a few lot about all this topic, I read about pv  will also be trying it out and see.


text:
Q: How can I view/alter data stored using the SPPersistedDataObject class manually? I am currently storing data using an SPPersistedObject.
I am transitioning from previously using a SharePoint List.  However, one benefit of the list was being able to go in and change the data manually (if needed).
I'd like to still provide this functionality either using a view ( if possible ) or possibly interacting with the data in SQL Server or SharePoint Designer ( if possible ).
Are there any other alternatives that I'm not considering ?

A: The SPPersistedObject worked well as a solution.


text:
Q: Fancybox and custom script I have a link
 Details...

And form
<form id="detail_form" class="hidden">
...
</form>

This my script to handle click a#detail_form. It works correctly
$(".detail").on('click', function() {
                var self = $(this).parent().parent();
                $.ajax({
                    type: 'post',
                    url: 'details',
                    data: {id: self.children("input").attr("value")}
                }).done(function(data) {
                    if (data=="true")
                    {
                        var a = self.children("a").children("span");
                        a.html(parseInt(a.html())+1);

                    }
                });
                return false;
            });

Also I call fancybox
$(".fancybox.detail").fancybox({
        width: 600,
        autoDimensions: true,
        fitToView : false,
        scrolling : 'no'
    });

When I clicked a#detail_form, my script is starting, but fancybox doesn't respond.


text:
Q: How to update column value in laravel I have a page model. It has following columns in database table:

*

*id

*title

*image

*body

I want to update only "image" column value.
Here's my code:
public function delImage($path, $id) {
    $page = Page::find($id);
    $page->where('image', $path)->update(array('image' => 'asdasd'));
    \File::delete($path);
}

it throws me an error, that i am trying to use where() on a non-object. How can i correctly update my "image" column value?

A: Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();

Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();

In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();

A: Try this method short and clean :
Page::where('id', $id)
  ->update(['image' => $path]);

An example from Laravel doc
Flight::where('active', 1)
      ->where('destination', 'San Diego')
      ->update(['delayed' => 1]);

A: I tried to update a field with
$table->update(['field' => 'val']);

But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"
Hope it will help someone :)

A: You may try this:
Page::where('id', $id)->update(array('image' => 'asdasd'));

There are other ways too but no need to use Page::find($id); in this case. But if you use find() then you may try it like this:
$page = Page::find($id);

// Make sure you've got the Page model
if($page) {
    $page->image = 'imagepath';
    $page->save();
}

Also you may use:
$page = Page::findOrFail($id);

So, it'll throw an exception if the model with that id was not found.

A:        DB::table('agents')
       ->where('id', $agentid)
       ->update(['status' => '0']);


text:
Q: gl_MultiTexCoord0 not allowed in vert shader in cocos2d v2 alpha? I'm trying to use to gl_MultiTexCoord0 in the main of my .vert shader, but the shader won't link with no descriptive error.  Removing the reference to gl_MultiTexCoord0 results in no error.  Is this not supported?  Is there a known workaround?
This is on cocos2d v2 alpha for the iPhone.

A: There are no gl_MultiTexCoordN in OpenGL ES (like lots of other built-in variables), so you have to pass the texture coordinates as an attribute:
    glVertexAttribPointer(texture_id, 2, GL_FLOAT, 0, 0, texture_coords_ptr);
    glEnableVertexAttribArray(texture_id);

To receive readable diagnostics from your shader you have to get an error using the glGetShaderInfoLog.


text:
Q: permissions of a proxy model in a new app not well created? The permissions of my proxy Model of a User Model are not well created.
In my "customers" app, I have:
models.py file:
from django.contrib.auth.models import User

class Customer(User):
    class Meta:
        proxy=True
        app_label = 'customers'
        verbose_name = 'Customer account'
        verbose_name_plural = 'Customer accounts'

admin.py file:
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin

class CustomerAdmin(UserAdmin):

   def queryset(self, request):
        qs = super(UserAdmin, self).queryset(request)
        qs = qs.exclude(Q(is_staff=True) | Q(is_superuser=True))
        return qs

admin.site.register(Customer, CustomerAdmin)

When I look at the permissions table, I see that the created permissions for my proxy Model are related to the User Content Type and not the Content Type of my proxy Model.
I then have in the admin permissions like that:
auth | Customer account | Can add Customer account
instead of:
customers | Customer account | Can add Customer account
I manually changed the content type of the permissions on the database and it worked but why is it not created the way I was expecting? Is that a bug or am I wrong?
Thanks

A: This was a known bug in Django. https://code.djangoproject.com/ticket/11154. It's reported as fixed in version 2.2.
For earlier versions, you can either insert them yourself or use a post_syncdb handler, if you run into this again.


text:
Q: Why is this limit integrable? In the book Real Analysis by Bass, it asks to evaluate the Lebesgue integral
$$ \lim_{n\to\infty} \int_{0}^{n} \bigg(1 - \frac{x}{n} \bigg)^{n} \log(2+\cos(x/n)) \ \mathrm{d}x $$
I assume I should use one of the convergence theorems.
Define the integrand as $f_n(x)$.
Is it possible to evaluate this even if $f_n(x)$ is not defined for all $x \in \mathbb{R}$ for some values of $n \in \mathbb{R}$? To be specific, $f_n(x)$ is defined for all $x\in\mathbb{R}$, and the integral as well, if $n \in \mathbb{N}$. Is this enough for the limit to be integrable? Another thing that confuses me is that the upper limit of the integral is $n$, should I define the sequence of functions $g_n = \int_{0}^{n} \left(1 - \frac{x}{n} \right)^{n} \log(2+\cos(x/n)) \, \mathrm{d}x$ for each positive integer $n$?
My edit:
What I mean is that the integrand is real-valued on $(0,n)$ but I don't know how to tackle cases where the integration interval varies with the limit.

A: $0 \leq I_{(0,n)}(x) (1-\frac  xn)^{n} \log(2+cos (\frac x n))\leq (\log 3)e^{-x}$ and $e^{-x}$ is integrable on $(0,\infty)$. So we can apply DCT.

A: $HINT$
$1_{[0,n]}\leq 1, \forall n \in \Bbb{N}$
Note that $|\log{(2+\cos{(x/n)})}| \leq \log{3}$
Also since $1-x \leq e^{-x}$ we have that $$(1-\frac{x}{n})^ \leq e^{-\frac{x}{n}}$$
So by m DCT you have the limit.

A: Here is another line of argument: Using the substitution $y = \frac{x}{n}$, the integral inside the limit reduces to
$$ \int_{0}^{1} n (1 - y) ^n \log(2+\cos y) \, \mathrm{d}y. $$
Now the following theorem kicks in:

Theorem. Let $\phi : [0, 1] \to \mathbb{R}$ be bounded and continuous at $0$. Then
  $$ \lim_{n\to\infty} \int_{0}^{1} n (1-y)^{n-1} \phi(y) \, \mathrm{d}y = \phi(0). $$

In our case, we can set $\phi(y) = (1-y) \log(2 + \cos y)$ to find out that the limit is $\phi(0) = \log 3$.
Proof of Theorem. For any $\epsilon > 0$, there exists $\delta \in (0, 1)$ such that $|\phi(y) - \phi(0)| < \epsilon$ whenever $|y| < \delta$. Also, let $M > 0$ be a bound of $\phi$. Then
\begin{align*}
\left| \int_{0}^{1} n (1-y)^{n-1} \phi(y) \, \mathrm{d}y - \phi(0) \right|
&\leq \int_{0}^{1} n (1-y)^{n-1} |\phi(y) - \phi(0)| \, \mathrm{d}y \\
&\leq 2M \int_{\delta}^{1} n (1-y)^{n-1} \, \mathrm{d}y + \epsilon \int_{0}^{\delta} n (1-y)^{n-1} \, \mathrm{d}y \\
&\leq 2M(1-\delta)^n + \epsilon,
\end{align*}
and so,
$$ \limsup_{n\to\infty} \left| \int_{0}^{1} n (1-y)^{n-1} \phi(y) \, \mathrm{d}y - \phi(0) \right| \leq \epsilon. $$
But since the left-hand side is independent of $\epsilon > 0$, we can let $\epsilon \downarrow 0$ to find that this limsup is zero, which implies the desired claim. $\square$


text:
Q: Does a function defined inside another function gets redefined throughout the while-loop? The code:
def useful_function():
    def multiply(a, b):
        return a * b
    return multiply(2, 2)

while True:
    print(useful_function())

Does the fact that the multiply function is defined inside useful_function mean that each time the while-loop works, the multiply function is redefined?


text:
Q: Stub native ECMAScript modules Is there any way to stub or rewire imports of native ECMAScript modules?
All solution I found uses @std/esm or a transpiler.
For example: I would like to replace the 'nedb-promise with a stub
import Datastore from 'nedb-promise'


text:
Q: need help in solving segmentation fault in C i am currently having issues with the segmentation fault. this is my project for school and i keep on getting the segmentation fault i dont know why. i was tasked to produce a program to read in the value from the txt file and display it in C.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    float training_input[90][8],training_output[90][1],testing_input[10][8],testing_output[10][1];
    int i;
    FILE *fpointer;
    fpointer= fopen("project.txt","r");
    for (i=0;i <=90; i++ )
    {
        fscanf(fpointer, "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f",&training_input[i][0],&training_input[i][1],&training_input[i][2],&training_input[i][3],&training_input[i][4],&training_input[i][5],&training_input[i][6],&training_input[i][7],&training_input[i][8],&training_output[i][9]);
        printf("\n %f,%f,%f,%f,%f,%f,%f,%f,%f,%f ",training_input[i][0],training_input[i][1],training_input[i][2],training_input[i][3],training_input[i][4],training_input[i][5],training_input[i][6],training_input[i][7],training_input[i][8],training_output[i][9]);
    }
    for (i=91; 1<=101; i++)
    {
        fscanf(fpointer, "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, ",&testing_input[i][0],&testing_input[i][1],&testing_input[i][2],&testing_input[i][3],&testing_input[i][4],&testing_input[i][5],&testing_input[i][6],&testing_input[i][7],&testing_input[i][8],&testing_output[i][9]);
        printf("\n %f,%f,%f,%f,%f,%f,%f,%f,%f, %f, ",testing_input[i][0],testing_input[i][1],testing_input[i][2],testing_input[i][3],testing_input[i][4],testing_input[i][5],testing_input[i][6],testing_input[i][7],testing_input[i][8],testing_output[i][9]);
    }
    fclose (fpointer);
    return 0;

the segmentation fault always occur in the fscanf and printf.

A: When you have an array defined with 90 elements in one dimension:
float training_input[90][8]

You cannot iterate on it like:
for (i=0;i <=90; i++ )

Because you will also try to access the index 90, which is ouside the bounds of the array - the valid indices are from 0 to 89. This is why you get a segmentation fault. The check in the loop must be i < 90.
Also, in the second loop, you are iterating up to 101, while your array is defined as having 10 elements. This would be a second segmentation fault.


text:
Q: Delphi - Enumerate the Disk(s) and other Drives on Windows PC
Possible Duplicate:
Get drive information (free space, etc.) for drives on Windows and populate a memo box

I am quite new to programing (especially Delphi), and have been unable to find any examples as to how to enumerate all the drives on a PC.
I really care about Hard Disks and CD-Rom drives but I have been unable to find anything useable.
Can anyone point me in the direction of a good working sample?

A: See GLibWMI Library; With It you can access information about system drives.

A: The simplest way is actually to use GetDiskFreeSpaceEx from the sysutils.pas file.
There are 2 parts to this example. the 1st is the important part using GetDiskFreeSpaceEX.
function DriveSpace(DriveLetter : String; var FreeSpace, UsedSpace, TotalSpace : int64) : Boolean;
begin
  Result := SysUtils.GetDiskFreeSpaceEx(Pchar(DriveLetter), UsedSpace, TotalSpace, @FreeSpace);

  if UsedSpace > 0 then
    UsedSpace := TotalSpace - FreeSpace;

  if not Result then
  begin
    UsedSpace   := 0;
    TotalSpace  := 0;
    FreeSpace   := 0;
  end;
end;

If you are going to request drives that you already know the drive letter for such as C: then that is all you need.
Usage would be something like:
var
  FS,
  US,
  TS : Int64
begin
  DriveSpace('C:', FS, US, TS);
  //Do something with the 3 variables.
end;

Having said that if you want to find the drives as well you could use something like this:
procedure ListDrivesOfType(DriveType : Integer; var Drives : TStringList);
var
  DriveMap,
  dMask : DWORD;
  dRoot : String;
  I     : Integer;
begin
  dRoot     := 'A:\'; //' // work around highlighting
  DriveMap  := GetLogicalDrives;
  dMask     := 1;

  for I := 0 to 32 do
  begin
    if (dMask and DriveMap) <> 0 then
      if GetDriveType(PChar(dRoot)) = DriveType then
      begin
        Drives.Add(dRoot[1] + ':');
      end;

    dMask := dMask shl 1;
    Inc(dRoot[1]);
  end;
end;

Note the DriveType integer, should be one of the following:
DRIVE_UNKNOWN     = 0;
DRIVE_NO_ROOT_DIR = 1;
DRIVE_REMOVABLE   = 2;
DRIVE_FIXED       = 3;
DRIVE_REMOTE      = 4;
DRIVE_CDROM       = 5;
DRIVE_RAMDISK     = 6;

(I have taken these straight out of windows.pas)

Now finally to answer your question (and this is very rough) the following would add information into a memo (called memo1) for all FIXED HARD DRIVES:
Procedure TAform.SomeNameICantThinkOfNow;
const
  BytesPerMB = 1048576;
var
  MyDrives   : TStringlist;
  I : Integer;
  FreeSpace,
  UsedSpace,
  TotalSpace : int64;
begin
  MyDrives := TStringlist.Create;
  ListDrivesOfType(DRIVE_FIXED, MyDrives);

  Memo1.Lines.Clear;

  for I := 0 to MyDrives.Count - 1 do
  begin
    FreeSpace  := 0;
    UsedSpace  := 0;
    TotalSpace := 0;

    if DriveSpace(MyDrives.Strings[I], FreeSpace, UsedSpace, TotalSpace) then
    begin
      FreeSpace  := FreeSpace  div BytesPerMB;
      UsedSpace  := UsedSpace  div BytesPerMB;
      TotalSpace := TotalSpace div BytesPerMB;

      Memo1.Lines.Add('Drive: ' + MyDrives.Strings[I] + ' = Free Space :' + IntToStr(FreeSpace) +
                      ' Used Space: ' + IntToStr(UsedSpace) + ' Total Space: ' + IntToStr(TotalSpace));
    end;
  end;
end;

I did say it would be nasty! I have just run this up in the IDE and it works, I have done as MB but really you should convert to Double and choose your formatting if doing as MB to be more precise as the example I have create above will of course just round up.
Hope this is of some small assistance.


text:
Q: XCode linking error to cached library information without being called (Undefined symbols for architecture) I am attempting to use a static library (.a) for which I also have the header files (no .m files), but when I add the library to my target (without even referencing/importing the library in my project code), I receive the Undefined symbols for architecture armv7 linking error at compile time. The linker is complaining about classes that supposedly no longer exist in the newest version of the library, and may be using cached data? That suspicion could be supported by the finding that if I create a blank project and add the library in the exact same way as I added it to my project, the new project compiles without issue. But on another note, when I grep my file system for the classes/ivars the linker is complaining about, I get matches in my static library file and my xcuserdata workspace folders. So I am wondering if the issue is in my project, the library I am trying to import, or the way in which I am trying to add the library to my project? And also, why do I get linker errors when I am not even importing/calling the library from my code? I am using XCode 4.6.1.
The linking error is as follows:
Undefined symbols for architecture armv7:
"_OBJC_IVAR_$_GenericPopupView.delegateTheme", referenced from:
  -[MyListView setDelegateTheme:] in myLib.a(MyListView.o)
  -[MyListView tableView:cellForRowAtIndexPath:] in myLib.a(MyListView.o)
"_OBJC_CLASS_$_SampleMarkView", referenced from:
  objc-class-ref in myLib.a(MyListView.o)
"_OBJC_CLASS_$_CheckMarkView", referenced from:
  objc-class-ref in myLib.a(MyListView.o)
"_OBJC_METACLASS_$_GenericPopupView", referenced from:
  _OBJC_METACLASS_$_MyListView in myLib.a(MyListView.o)
"_OBJC_CLASS_$_GenericPopupView", referenced from:
  _OBJC_CLASS_$_MyListView in myLib.a(MyListView.o)
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I added the library to my target by performing the following steps:

*

*Right-click on my project

*Select 'Add Files to "My Project"'

*Locate the .a file through the popup Finder window

*Verify the library path is in my Target -> Build Settings -> Library Search Paths (automatically added when I complete step 3)

*Add the header directory to Target -> Build Settings -> Header Search Paths

*Verify that the library is listed in Target -> Build Phases -> Link Binary With Libraries

*Verify that the library is compiled for armv7 via file, otool, & lipo (I heard the library may also include armv6s, but I didn't see armv6 when I used the three commands)
$ file myLib.a
myLib.a: Mach-O universal binary with 2 architectures
myLib.a (for architecture armv7):   current ar archive random library
myLib.a (for architecture cputype (12) cpusubtype (11)): current ar archive random library

$ otool -L myLib.a
Archive : myLib.a (architecture cputype (12) cpusubtype (11))
…

$ lipo -info myLib.a
Architectures in the fat file: myLib.a are: armv7 (cputype (12) cpusubtype (11))

Here are things I have tried inbetween each compile attempt without any success:

*

*Clean the project with (apple)+shift+k

*Clean the build directory (DerivedData) with (apple)+alt+shift+k

*Delete all the DerivedData directories from the command line

*Remove and re-add the library and its headers to my project

*Add the library without the headers

*Put the libraries in a project that is a target dependency instead of in my project directly

*

*Note that I am unable to add the library as a Target Dependency in Build Settings; should I be able to?

*I am also unable to add the library to the target's Build Scheme (via XCode menu's Product -> Scheme -> Edit Scheme... -> Build -> +)

*Check the minimum iOS version via iOS Deployment Target in Build Settings – both my target and the library are iOS 6.0

*Removed all target search paths except those required for my project to build without the new library as shown below (most importantly I removed the DerivedData from the linker path); my overall project build settings (not the target's build settings) contains no other search paths
Header Search Paths
$(BUILT_PRODUCTS_DIR)/usr/local/include
$(SRCROOT)/../MyLibDirectory/headers

Library Search Paths
$(inherited)
$(SRCROOT)/../TargetDependencyDirectory
$(SRCROOT)/../openssl/lib
$(SRCROOT)/../MyLibDirectory

*Removed all other instances of the library on my machine (old versions)

*Set the user-defined build setting USE_HEADERMAP = NO

*Install on a newly imaged machine with a fresh project checkout and repeat all of the above steps

*Add –ObjC++ to the other linker flags (-ObjC is already a linker flag)

*Use armv6s by itself and with armv6 in the Valid Architecture under Build Settings for my target and the target dependencies

*Set Build Active Architecture Only to Yes

*Switched between adding the library in a project group vs. at the parent project group level

*Add an import and instantiation of an object from the library in my project code

*Played with the library's different settings for Location under Identity and Type in the Utilities window on the right side of XCode when the library is selected

*Add the library to the target's Build Phases -> Link Binary With Libraries via the + then Add Other...
I have already tried the recommended steps in these and other posts (only the last two of these listed have actual instructions):

*

*Xcode referencing old
framework

*Xcode referencing old/removed frameworks, causing multiple interface
declarations

*Xcode custom framework - No known method error

*Undefined symbols for architecture armv7
I have not tried changing all of my files to .mm (I didn't need to for previous versions of this library), but I have a lot of .m files that I think might break if I change them all...
Any help or succestions are greatly appreciated! I'm really having a hard time figuring out why this new version of the library is giving me problems.

A: I resolved my own problem, or rather, the issue was with the black box of a library that I was including.  From the command line performed the following command in a terminal window:
grep SampleMarkView myLib.a

Which resulted in:
Binary File:myLib.a matches

I talked to the person who created the library and they sent me an updated version that didn't cause the problem - I guess they had old references in their code.  So at the very least I hope this post provides a list of various things to try if you are having a library referencing problem!


text:
Q: Creating a single column vector from a list column in R I'm currently trying to divide up a dataset of text documents (coded in UTF-8) by paragraph in R, but I'm having trouble getting them into the format I want for tidytext, which is a single column of the different paragraphs.
My data so far looks something like this:
list <- c("Lorem ipsum dolor sit amet, movet omittantur ut vel, vim an offendit prodesset. Sumo summo intellegam vel ei, dicunt persecuti vim ne. Lorem noluisse at est. Per ex postulant philosophia, ut vel amet affert tantas, pro ne consetetur scriptorem. Id mel aeque deleniti.

Nam ut erat eligendi, pro eu minim molestie persequeris. Civibus interesset te nec, cu aeque fabellas luptatum has. Ad usu nominati tractatos. Eu voluptatum disputationi vis, alienum delicatissimi pri eu. Et molestie copiosae nam, ex vix ignota dignissim. Dico suas illum at mea, no case modus antiopam sea.

Ius te copiosae lobortis contentiones. Est ceteros dissentiet ne, qui malis iuvaret tacimates an. Vivendo erroribus nec no. No quo corpora indoctum iracundia, mel ad mollis accusam praesent. Sit at admodum sensibus mediocrem, no pri decore nemore.",

"Lorem ipsum dolor sit amet, movet omittantur ut vel, vim an offendit prodesset. Sumo summo intellegam vel ei, dicunt persecuti vim ne. Lorem noluisse at est. Per ex postulant philosophia, ut vel amet affert tantas, pro ne consetetur scriptorem. Id mel aeque deleniti.

Nam ut erat eligendi, pro eu minim molestie persequeris. Civibus interesset te nec, cu aeque fabellas luptatum has. Ad usu nominati tractatos. Eu voluptatum disputationi vis, alienum delicatissimi pri eu. Et molestie copiosae nam, ex vix ignota dignissim. Dico suas illum at mea, no case modus antiopam sea.

Ius te copiosae lobortis contentiones. Est ceteros dissentiet ne, qui malis iuvaret tacimates an. Vivendo erroribus nec no. No quo corpora indoctum iracundia, mel ad mollis accusam praesent. Sit at admodum sensibus mediocrem, no pri decore nemore.",

"Lorem ipsum dolor sit amet, movet omittantur ut vel, vim an offendit prodesset. Sumo summo intellegam vel ei, dicunt persecuti vim ne. Lorem noluisse at est. Per ex postulant philosophia, ut vel amet affert tantas, pro ne consetetur scriptorem. Id mel aeque deleniti.

Nam ut erat eligendi, pro eu minim molestie persequeris. Civibus interesset te nec, cu aeque fabellas luptatum has. Ad usu nominati tractatos. Eu voluptatum disputationi vis, alienum delicatissimi pri eu. Et molestie copiosae nam, ex vix ignota dignissim. Dico suas illum at mea, no case modus antiopam sea.

Ius te copiosae lobortis contentiones. Est ceteros dissentiet ne, qui malis iuvaret tacimates an. Vivendo erroribus nec no. No quo corpora indoctum iracundia, mel ad mollis accusam praesent. Sit at admodum sensibus mediocrem, no pri decore nemore.")
df <- as.data.frame(list)
df_spl <- str_split(df$list, "\n", n = Inf)
df_spl

Basically it's a large list of different vectors that have different paragraphs in them from each original row.
What I ultimately want is a single column vector with all the list items, like this:
 vector <- c("Lorem ipsum dolor sit amet, movet omittantur ut vel, vim an offendit prodesset. Sumo summo intellegam vel ei, dicunt persecuti vim ne. Lorem noluisse at est. Per ex postulant philosophia, ut vel amet affert tantas, pro ne consetetur scriptorem. Id mel aeque deleniti.", "Nam ut erat eligendi, pro eu minim molestie persequeris. Civibus interesset te nec, cu aeque fabellas luptatum has. Ad usu nominati tractatos. Eu voluptatum disputationi vis, alienum delicatissimi pri eu. Et molestie copiosae nam, ex vix ignota dignissim. Dico suas illum at mea, no case modus antiopam sea.", "Ius te copiosae lobortis contentiones. Est ceteros dissentiet ne, qui malis iuvaret tacimates an. Vivendo erroribus nec no. No quo corpora indoctum iracundia, mel ad mollis accusam praesent. Sit at admodum sensibus mediocrem, no pri decore nemore.", "Lorem ipsum dolor sit amet, movet omittantur ut vel, vim an offendit prodesset. Sumo summo intellegam vel ei, dicunt persecuti vim ne. Lorem noluisse at est. Per ex postulant philosophia, ut vel amet affert tantas, pro ne consetetur scriptorem. Id mel aeque deleniti." "Nam ut erat eligendi, pro eu minim molestie persequeris. Civibus interesset te nec, cu aeque fabellas luptatum has. Ad usu nominati tractatos. Eu voluptatum disputationi vis, alienum delicatissimi pri eu. Et molestie copiosae nam, ex vix ignota dignissim. Dico suas illum at mea, no case modus antiopam sea.", "Ius te copiosae lobortis contentiones. Est ceteros dissentiet ne, qui malis iuvaret tacimates an. Vivendo erroribus nec no. No quo corpora indoctum iracundia, mel ad mollis accusam praesent. Sit at admodum sensibus mediocrem, no pri decore nemore.", "Lorem ipsum dolor sit amet, movet omittantur ut vel, vim an offendit prodesset. Sumo summo intellegam vel ei, dicunt persecuti vim ne. Lorem noluisse at est. Per ex postulant philosophia, ut vel amet affert tantas, pro ne consetetur scriptorem. Id mel aeque deleniti.", "Nam ut erat eligendi, pro eu minim molestie persequeris. Civibus interesset te nec, cu aeque fabellas luptatum has. Ad usu nominati tractatos. Eu voluptatum disputationi vis, alienum delicatissimi pri eu. Et molestie copiosae nam, ex vix ignota dignissim. Dico suas illum at mea, no case modus antiopam sea.", "Ius te copiosae lobortis contentiones. Est ceteros dissentiet ne, qui malis iuvaret tacimates an. Vivendo erroribus nec no. No quo corpora indoctum iracundia, mel ad mollis accusam praesent. Sit at admodum sensibus mediocrem, no pri decore nemore.")

I've already tried commands like cbind(), stack(), and unnest(), but none of them have gotten me that single column :(
Any help would be greatly, greatly appreciated! Thanks!!

A: We can unlist the list element into avectorandpaste` if we need a single string
out <- paste(unlist(df_spl), collapse=" ")

A: To turn a list into a vector you can use:
unlist(df_spl)


text:
Q: PHP array saying nonexistance I searched through the site, with keywords like "PHP array error" and "data not being found by PHP" but I can't find an answer that fits what I need.
I am making a really basic password protected site, with text files. I will include code below, but the error that comes up is;
Array ( ) count of banned = 1
Notice: Undefined index: banned[0] in C:\xampp\htdocs\dns\domains\bank\login.php on line 17

But I am unsure why. The code is in php, and is below.
<?php
//variables
$user = $_POST["user"];
$pass = $_POST["password"];
$banned = array("admin");
$users = array("admin");
$c = count($users);
$users = print_r(glob("../users/*.txt"));
$r = count($banned);
$k = $r - 1;
echo "count of banned = $r";
$loop = 0;
$isbanned = true;

//check if banned
while ($loop <= $k) {
if ($GLOBALS["user"] == $GLOBALS["banned"][$loop]) {
echo "sorry but this account is banned from this site!";
$GLOBALS["isbanned"] = true;
}
$loop = $loop + 1;
}
if ($isbanned == false) {
//if you are not banned, check if you are even a proper user with password!
$loop = 0;
while ($loop <= $r) {
if ($GLOBALS["user"] == $GLOBALS["users[$loop]"]) {
$person = print_r(file($GLOBALS["user"] . ".txt"));
if ($GLOBALS["pass"] == $GLOBALS["person[0]"]) {
header('location /welcome.php');
die();
}
}
$loop = $loop + 1;
}
}
?>

and below is the contents of my folder. The index.php is only a basic form, which works.
-index.php
-login.php
-Users
|-user.txt

and sorry for all the snip its, but the contents of each .txt file are as they follow;
1234
2000

The first line is the password, the second for a later project, is the cash.
If there is any other information you wish to see I will try to get it.
Thank you for reviewing my question.
--------------------------------------Part 2------------------------------------
Thank you Barmar for answering the 1st question.
After fixing the code, if not correct on here sorry, the system still wont fetch the content of the files to the array, so it still wont work as a login system. I know I should make this a new question, but it seemed to fit better like this. Thank you for reviewing my questions.

A: $GLOBALS["banned[$loop]"] should be $GLOBALS["banned"][$loop]. The index is not part of the variable name. The variable contains an array, and then you need to index that.
But there's no need to use $GLOBALS at all. Your code is at the global scope, so it can access global variables normally. That line should be:
if ($user == $banned[$loop])

And if you want to access a global variable inside a function, you can use the global declaration:
global $user, $banned, $users, $is_banned;


text:
Q: Extracting strings between two Regex expression I have a string (log file), I want to extract all the text between two strings (multiple instances).
This is the text I have:
++ PLANNING ITERATIONS of DEMAND 337 ++
=========================================

 Demand: 337   Event: 1189.001   Object/State: 7058/0   Tier: 0   Start: 1608130700   Duration: 90   At: 19-7-2016 16:19:36
 Demand: 337   Event: 1190.001   Object/State: 7059/0   Tier: 0   Start: 1608130830   Duration: 330   At: 19-7-2016 16:19:36
 Demand: 337   Event: 1191.001   Object/State: 7060/0   Tier: 0   Start: 1608140000   Duration: 360   At: 19-7-2016 16:19:36

++ EVENT PLAN of DEMAND 337 ++
===============================

event_time(1242.001,1,1609070800,1609071430)
event_time(1241.001,1,1609060800,1609061430)
event_time(1240.001,1,1609050800,1609051430)

++ PLANNING ITERATIONS of DEMAND 174 ++
=========================================

 Demand: 174   Event: 212.001   Object/State: 6948/0   Tier: 0   Start: 1609010800   Duration: 390   At: 19-7-2016 16:19:38
 Demand: 174   Event: 213.001   Object/State: 6949/0   Tier: 0   Start: 1609020800   Duration: 390   At: 19-7-2016 16:19:38

++ EVENT PLAN of DEMAND 174 ++
===============================

event_time(213.001,1,1609020800,1609021430)
event_time(212.001,1,1609010800,1609011430)

I want to get every thing between
++ PLANNING ITERATIONS of DEMAND 337 ++
=========================================

And
++ EVENT PLAN of DEMAND 174 ++
===============================

The results I expect to get is:
Demand: 337   Event: 1189.001   Object/State: 7058/0   Tier: 0   Start: 1608130700   Duration: 90   At: 19-7-2016 16:19:36
Demand: 337   Event: 1190.001   Object/State: 7059/0   Tier: 0   Start: 1608130830   Duration: 330   At: 19-7-2016 16:19:36
Demand: 337   Event: 1191.001   Object/State: 7060/0   Tier: 0   Start: 1608140000   Duration: 360   At: 19-7-2016 16:19:36
Demand: 174   Event: 212.001   Object/State: 6948/0   Tier: 0   Start: 1609010800   Duration: 390   At: 19-7-2016 16:19:38
Demand: 174   Event: 213.001   Object/State: 6949/0   Tier: 0   Start: 1609020800   Duration: 390   At: 19-7-2016 16:19:38

I tried to solved it myself and i got up to some point, but it returns the first match up to the end of the text.
This is the regular expression i used:
Demand:(?s)(.*)[+][+]

Online Example

A: I think the best way would be to just find all the Demand: ... lines.
You could do this with the following regex:
(?m)Demand:\s+.*$

This regex finds one line of the type you want. You need to use the function in whatever language/library you use that searches for all the strings that match that regex in you text.
The (?m) at the beginning sets the m option, which stands for multiline, so that the $ will match the end of the line and not the end of the entire txt.
After that the regex is quite simple. It searches for Demmand: followed by at least one space, then everything until the end of the line. The regex by default doesn't expand the . search across lines, and thus is limited to the line it scans. But had it expanded (like by using also the option s inside the preceding parenthesis) you would have had to update the regex to (?m)Demand:\s+.*?$ - that is add the ? symbol to make the search until the end of the line non greedy.

A: Your example is line based, so from my point of view the best solution would be to parse and compare the lines - no magic with regular expressions.
If you want to solve this with regular expressions, first try to find the anchors. I asume == would be a good beginning and ++ an ending. Between these anchors use a non-greedy (not the question mark) dotall:
==\s(.*?)\+\+ (use mode DOTALL, which would be a trailing s in your online example)
Then extract the first submatch group, which is the text you want.


text:
Q: Different arrows in set theory: $\rightarrow$ and $\mapsto$ Can someone explain the difference between symbols:
$\rightarrow$ and $\mapsto$
Thanks.

A: For sets $X$ and $Y$, $f\colon X \to Y$ is a function "from $X$ to $Y$", meaning that $f$ has domain $X$ and codomain $Y$. If $y = f(x)$, then we may write $x \mapsto y$, read as "$x$ maps to $y$". This is used only when the function that maps $x$ to $y$ is clear from the context. Sometimes, you may see a function defined as
\begin{align*}
f\colon\ & \mathbb R \to \mathbb R\\
& x \mapsto 4x^3
\end{align*}
instead of $f(x) = 4x^3$.
See here.

A: When referring to functions, $\rightarrow$ points from the domain of the function to its codomain. When we write $f:A\to B$, we mean that $f$ takes things in $A$ and maps them to thing in $B$. The symbol $\mapsto$ points from an element of the domain to its image in the codomain. $f:x\mapsto y$ means that $f(x)=y$.

A: In programming parlance, $\to$ is part of a type signature, while $\mapsto$ is part of a function definition.
The expression
$$x \mapsto \operatorname{floor}(1/x)$$
denotes the function that takes in a number and spits out the floor of its reciprocal.
There are many different type signatures that can be consistently assigned to this function. If you drop in numbers between $0$ and $1$, the function will spit out positive integers, so
$$(0, 1) \to \mathbb{N}$$
is one valid type signature.
As M. Vinay noted, it's not unusual to combine these notations in a function definition. For example, I could declare a function $g$ with the definition and type signature above by writing
$$\begin{align*}
g \colon (0,1) & \to \mathbb{N} \\
x & \mapsto \operatorname{floor}(1/x).
\end{align*}$$


text:
Q: Issue parsing multiline JSON file using Python I am trying to parse a JSON multiline file using json library in Python 2.7. A simplified sample file is given below:
{
"observations": {
    "notice": [
        {
            "copyright": "Copyright Commonwealth of Australia 2015, Bureau of Meteorology. For more information see: http://www.bom.gov.au/other/copyright.shtml http://www.bom.gov.au/other/disclaimer.shtml",
            "copyright_url": "http://www.bom.gov.au/other/copyright.shtml",
            "disclaimer_url": "http://www.bom.gov.au/other/disclaimer.shtml",
            "feedback_url": "http://www.bom.gov.au/other/feedback"
        }
    ]
}
}

My code is as follows:
import json

with open('test.json', 'r') as jsonFile:
    for jf in jsonFile:
        jf = jf.replace('\n', '')
        jf = jf.strip()
        weatherData = json.loads(jf)
        print weatherData

Nevertheless, I get an error as shown below:
Traceback (most recent call last):
File "test.py", line 8, in <module>
weatherData = json.loads(jf)
File "/home/usr/anaconda2/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/home/usr/anaconda2/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/home/usr/anaconda2/lib/python2.7/json/decoder.py", line 380, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting object: line 1 column 1 (char 0)

Just to do some testing, I modified the code such that after removing newlines and striping away the leading and trailing white spaces, I write the contents to another file (with the json extension). Surprisingly, when I read back the latter file, I do not get any error and the parsing is successful. The modified code is as follows:
import json

filewrite = open('out.json', 'w+')

with open('test.json', 'r') as jsonFile:
    for jf in jsonFile:
        jf = jf.replace('\n', '')
        jf = jf.strip()
        filewrite.write(jf)

filewrite.close()

with open('out.json', 'r') as newJsonFile:
    for line in newJsonFile:
        weatherData = json.loads(line)
        print weatherData

The output is as follows:
{u'observations': {u'notice': [{u'copyright_url': u'http://www.bom.gov.au/other/copyright.shtml', u'disclaimer_url': u'http://www.bom.gov.au/other/disclaimer.shtml', u'copyright': u'Copyright Commonwealth of Australia 2015, Bureau of Meteorology. For more information see: http://www.bom.gov.au/other/copyright.shtml http://www.bom.gov.au/other/disclaimer.shtml', u'feedback_url': u'http://www.bom.gov.au/other/feedback'}]}}

Any idea what might be going on when new lines and white spaces are stripped before using json library?

A: In the first snippet, you try to parse it line by line. You should parse it all at once. The easiest is to use json.load(jsonfile). (The jf variable name is misleading as it's a string). So the correct way to parse it:
import json

with open('test.json', 'r') as jsonFile:
    weatherData = json.loads(jsonFile)

Although it's a good idea to store the json in one line, as it's more concise.
In the second snippet your problem is that you print it as unicode string which is and u'string here' is python specific. A valid json uses double quotation marks

A: FYI, you can have both files opened in single with statement:
with open('file_A') as in_, open('file_B', 'w+') as out_:
    # logic here
    ...

A: You will go crazy if you try to parse a json file line by line. The json module has helper methods to read file objects directly or strings i.e. the load and loads methods.  load takes a file object (as shown below) for a file that contains json data, while loads takes a string that contains json data.
Option 1: - Preferred
import json
with open('test.json', 'r') as jf:
    weatherData = json.load(jf)
    print weatherData

Option 2:
import json
with open('test.json', 'r') as jf:
    weatherData = json.loads(jf.read())
    print weatherData

If you are looking for higher performance json parsing check out ujson